Created
March 15, 2017 19:23
-
-
Save reginaldojunior/dd530cf3cb5bd2ef74e6d4a0ee317fcc to your computer and use it in GitHub Desktop.
classebemlouca.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| class Product extends Eloquent | |
| { | |
| /** | |
| * The database table used by the model. | |
| * | |
| * @var string | |
| */ | |
| protected $table = 'products'; | |
| protected $dates = ['deleted_at']; | |
| protected $b2w; | |
| protected $plugg; | |
| protected $atributteAllowed; | |
| public $debug = false; | |
| // product creatiation | |
| protected $error; | |
| protected $productAttribute; | |
| // Shares | |
| protected $share_price = null; | |
| protected $share_description = null; | |
| protected $share_title = null; | |
| protected $share_available_quantity = null; | |
| protected $share_dimensions = null; | |
| protected $share_imagens = null; | |
| protected $user_attributes = null; | |
| protected $product; | |
| protected $result; | |
| protected $userId; | |
| protected $countVariance; | |
| // new variations | |
| protected $fillable = array('id', 'extra_id', 'pluggto_id', 'user_id', 'extra_token', 'sku', 'productIdOrigin', 'sellingTitle', | |
| 'brand', 'ean'); | |
| // used to register observers | |
| public static function boot() | |
| { | |
| parent::boot(); | |
| Product::observe(new Observer); | |
| } | |
| public function loadPlugg($user_id = null) | |
| { | |
| if (empty($this->plugg)) { | |
| if (empty($user_id)) { | |
| $this->plugg = loadClass('Plugg'); | |
| } else { | |
| $this->plugg = new Plugg($user_id); | |
| } | |
| } | |
| } | |
| // | |
| public function getUserAttributes() | |
| { | |
| if (is_null($this->user_attributes)) { | |
| $this->user_attributes = DB::table('user_attributes')->where('user_id', $this->plugg->id)->get(); | |
| } | |
| $attribues = array(); | |
| foreach ($this->user_attributes as $att) { | |
| $possibleAttributes = explode(',', $att->pluggto_code); | |
| foreach ($possibleAttributes as $possible) { | |
| $attribues[$possible] = $att->b2w_code; | |
| } | |
| } | |
| return $attribues; | |
| } | |
| public function getProductAttributes($productAttributes,$product) | |
| { | |
| if (!is_array($productAttributes)) { | |
| return ''; | |
| } | |
| $this->getAllowedAttributes(); | |
| $Userattributes = $this->getUserAttributes(); | |
| $returnAtt = array(); | |
| $attrArray = array(); | |
| foreach ($productAttributes as $attribute) { | |
| $att = array(); | |
| if (isset($Userattributes[$attribute['code']]) && !empty($Userattributes[$attribute['code']]) //&& | |
| // in_array($Userattributes[$attribute['code']], $this->atributteAllowed) | |
| ) { | |
| $att = array(); | |
| $att['name'] = $Userattributes[$attribute['code']]; | |
| $attrArray[] = $Userattributes[$attribute['code']]; | |
| if (isset($attribute['value']['code']) && !empty($attribute['value']['code'])) { | |
| $att['value'] = $attribute['value']['code']; | |
| } elseif (isset($attribute['value']['label']) && !empty($attribute['value']['label'])) { | |
| $att['value'] = $attribute['value']['label']; | |
| } else { | |
| $att['value'] = 'unico'; | |
| } | |
| } | |
| if (!empty($att)) { | |
| $returnAtt[] = $att; | |
| } | |
| } | |
| foreach ($product['attributes'] as $attribute) { | |
| $att = array(); | |
| if (isset($Userattributes[$attribute['code']]) && !empty($Userattributes[$attribute['code']]) //&& | |
| // in_array($Userattributes[$attribute['code']], $this->atributteAllowed) | |
| ) { | |
| $att = array(); | |
| $att['name'] = $Userattributes[$attribute['code']]; | |
| $attrArray[] = $Userattributes[$attribute['code']]; | |
| if (isset($attribute['value']['code']) && !empty($attribute['value']['code'])) { | |
| $att['value'] = $attribute['value']['code']; | |
| } elseif (isset($attribute['value']['label']) && !empty($attribute['value']['label'])) { | |
| $att['value'] = $attribute['value']['label']; | |
| } else { | |
| $att['value'] = 'unico'; | |
| } | |
| } | |
| if (!empty($att)) { | |
| $returnAtt[] = $att; | |
| } | |
| } | |
| if (in_array('TAMANHO', $attrArray) && !in_array('COR', $attrArray)) { | |
| if (isset($att['value'])) { | |
| $cor['name'] = 'COR'; | |
| if (!empty($this->productAttribute)) { | |
| foreach ($this->productAttribute as $att) { | |
| if ($att['name'] == 'COR') { | |
| $cor['value'] = $att['value']; | |
| } | |
| } | |
| $returnAtt[] = $cor; | |
| } | |
| } | |
| } elseif (!in_array('TAMANHO', $attrArray) && in_array('COR', $attrArray)) { | |
| if (isset($att['value'])) { | |
| $tam['name'] = 'TAMANHO'; | |
| if (!empty($this->productAttribute)) { | |
| foreach ($this->productAttribute as $att) { | |
| if ($att['name'] == 'TAMANHO') { | |
| if (isset($att['value'])) $tam['value'] = $att['value']; | |
| } | |
| $returnAtt[] = $tam; | |
| } | |
| } | |
| } | |
| } | |
| if(in_array('MARCA', $this->atributteAllowed) && isset($product['brand'])){ | |
| $returnAtt[] = array('name'=>'MARCA','value'=>$product['brand']); | |
| } | |
| return $returnAtt; | |
| } | |
| // Função que verifica se EAN possui 13 digitos e é numerico | |
| public function validaEan($string) | |
| { | |
| if (is_numeric($string) && strlen($string) == 13) { | |
| return true; | |
| } else { | |
| $this->error[] = 'Campo ean deve ser númerico com 13 dígitos'; | |
| } | |
| } | |
| // Função, que a apartir do retorno de erro da B2W, formata para o Pluggto | |
| public function generateB2wError($errors) | |
| { | |
| foreach ($errors as $error) { | |
| $this->error[] = 'Erro retornado da B2W: ' . $error['message'] . ' campo: ' . $error['fieldName']; | |
| } | |
| } | |
| // pega os atributos do produto | |
| public function getAllowedAttributes() | |
| { | |
| if (empty($this->atributteAllowed)) { | |
| $this->atributteAllowed = array(); | |
| $b2w = new B2w(); | |
| $categoryId = Session::get('category'); | |
| if (!empty($categoryId)) { | |
| $attributes = $b2w->request('marketstructure/category/' . $categoryId . '/attribute', 'GET'); | |
| } else { | |
| // $attributes = $b2w->request('marketstructure/category/9999/attribute', 'GET'); | |
| $attributes = null; | |
| } | |
| if (isset($attributes['body']) && is_array($attributes['body'])) { | |
| foreach ($attributes['body'] as $att) { | |
| if(isset($att['name'])){ | |
| $this->atributteAllowed[] = $att['name']; | |
| } | |
| } | |
| } | |
| } | |
| if (!in_array('COR', $this->atributteAllowed)) { | |
| $this->atributteAllowed[] = "COR"; | |
| } | |
| if (!in_array('TAMANHO', $this->atributteAllowed)) { | |
| $this->atributteAllowed[] = "TAMANHO"; | |
| } | |
| return $this->atributteAllowed; | |
| } | |
| public function checkPrice($price, $user,$field='price',$productData,$variation=null,$tablePriceName=null) | |
| { | |
| if(!is_object($user)){ | |
| try{ | |
| $user = User::where('plugg_id',$user)->firstOrFail(); | |
| } catch (exception $e){ | |
| // not found user, just return the price | |
| return $this->numberFormat($price); | |
| } | |
| } | |
| if(!empty($tablePriceName)){ | |
| $tablepriceName = $tablePriceName; | |
| } else if(isset($user->table_data)){ | |
| $tablepriceName = $user->table_data; | |
| } elseif(isset($user->b2w->table_data)) { | |
| $tablepriceName = $user->b2w->table_data; | |
| } else { | |
| $tablepriceName = null; | |
| } | |
| if(!empty($tablepriceName)){ | |
| if(isset($variation['price_table']) && is_array($variation['price_table'])) { | |
| foreach($variation['price_table'] as $table){ | |
| if($table['code'] == $tablepriceName){ | |
| if(!isset($table['action'])){ | |
| continue; | |
| } | |
| if($table['action'] == 'overwrite' && !empty($field)){ | |
| if($field == 'price' && isset($table['price']) && !empty($table['price'])){ | |
| $fprice = $table['price']; | |
| } else if($field == 'special_price' && isset($table['special_price']) && !empty($table['special_price'])){ | |
| $fprice = $table['special_price']; | |
| } else if($field == 'special_price' && isset($table['special_price']) && !empty($table['price'])){ | |
| $fprice = $table['price']; | |
| } | |
| } else if ($table['action'] == 'increase' && isset($table['percentage']) && !empty($table['percentage'])){ | |
| $fprice = $price + ($price * ($table['percentage'] / 100)); | |
| } else if ($table['action'] == 'decrease' && isset($table['percentage']) && !empty($table['percentage'])){ | |
| $fprice = $price - ($price * ($table['percentage'] / 100)); | |
| } | |
| if (isset($fprice) && $fprice > 0) { | |
| return $this->numberFormat($fprice); | |
| } | |
| } | |
| } | |
| } else if(isset($productData['price_table']) && is_array($productData['price_table'])){ | |
| foreach($productData['price_table'] as $table){ | |
| if($table['code'] == $tablepriceName){ | |
| if(!isset($table['action'])){ | |
| continue; | |
| } | |
| if($table['action'] == 'overwrite' && !empty($field)){ | |
| if($field == 'price' && isset($table['price']) && !empty($table['price'])){ | |
| $fprice = $table['price']; | |
| } else if($field == 'special_price' && isset($table['special_price']) && !empty($table['special_price'])){ | |
| $fprice = $table['special_price']; | |
| } else if($field == 'special_price' && isset($table['special_price']) && !empty($table['price'])){ | |
| $fprice = $table['price']; | |
| } | |
| } else if ($table['action'] == 'increase' && isset($table['percentage']) && !empty($table['percentage'])){ | |
| $fprice = $price + ($price * ($table['percentage'] / 100)); | |
| } else if ($table['action'] == 'decrease' && isset($table['percentage']) && !empty($table['percentage'])){ | |
| $fprice = $price - ($price * ($table['percentage'] / 100)); | |
| } | |
| if (isset($fprice) && $fprice > 0) { | |
| return $this->numberFormat($fprice); | |
| } | |
| } | |
| } | |
| } | |
| } | |
| if (!empty($user->dec_inc)) { | |
| if (!empty($user->porcentagem)) { | |
| if ($user->dec_inc == 'dec') { | |
| $fprice = $price - ($price * ($user->porcentagem / 100)); | |
| } elseif ($user->dec_inc == 'inc') { | |
| $fprice = $price + ($price * ($user->porcentagem / 100)); | |
| } | |
| if ($fprice > 0) { | |
| $price = $fprice; | |
| } | |
| } | |
| } | |
| return $this->numberFormat($price); | |
| } | |
| public function formatPriceManul($get_valor) | |
| { | |
| $source = array('.', ','); | |
| $replace = array('', '.'); | |
| $valor = str_replace($source, $replace, $get_valor); //remove os pontos e substitui a virgula pelo ponto | |
| return self::numberFormat($valor, 2, '.', ''); //retorna o valor formatado para gravar no banco | |
| } | |
| public static function numberFormat($number) | |
| { | |
| return number_format($number, 2, '.', ''); | |
| } | |
| public static function formatImagesOrder($ProductPhotos) | |
| { | |
| $photoArray = array(); | |
| foreach ($ProductPhotos as $onephoto) { | |
| if (isset($onephoto['order'])) { | |
| $photoArray[(int)$onephoto['order']] = $onephoto; | |
| } else { | |
| $photoArray[] = $onephoto; | |
| } | |
| } | |
| // sort array | |
| ksort($photoArray); | |
| return $photoArray; | |
| } | |
| public function checkIfPriceIsBiggerThanSpecialPrice($price,$specialPrice){ | |
| if(empty($specialPrice) || $specialPrice == '0.00' ){ | |
| $specialPrice = $price; | |
| } | |
| if ($specialPrice > $price) { | |
| $specialPrice = $price; | |
| } | |
| return $specialPrice; | |
| } | |
| public function getBrandPrice($product,$variacao=null){ | |
| $brandPrice = array(); | |
| if(isset($this->plugg->b2w->table_data_lojasamericans)){ | |
| if(isset($variacao['price']) && isset($variacao['special_price'])){ | |
| $specialprice = $this->checkPrice($variacao['special_price'], $this->plugg,'special_price',$product,$variacao,$this->plugg->b2w->table_data_lojasamericans); | |
| } else { | |
| $specialprice = $this->checkPrice($product['special_price'], $this->plugg,'special_price',$product,null,$this->plugg->b2w->table_data_lojasamericans); | |
| } | |
| if(isset($variacao['price']) && isset($variacao['special_price'])){ | |
| $price = $this->checkPrice($variacao['price'], $this->plugg,'price',$product,$variacao,$this->plugg->b2w->table_data_lojasamericans); | |
| } else { | |
| $price = $this->checkPrice($product['price'], $this->plugg,'price',$product,null,$this->plugg->b2w->table_data_lojasamericans); | |
| } | |
| $specialprice = $this->checkIfPriceIsBiggerThanSpecialPrice($price,$specialprice); | |
| if(!empty($price) && !empty($specialprice)){ | |
| $brandPrice[] = array('store'=>'LOJASAMERICANAS','listPrice'=>$price,'sellPrice'=>$specialprice); | |
| } | |
| } | |
| if(isset($this->plugg->b2w->table_data_submarino)){ | |
| if(isset($variacao['price']) && isset($variacao['special_price'])){ | |
| $specialprice = $this->checkPrice($variacao['special_price'], $this->plugg,'special_price',$product,$variacao,$this->plugg->b2w->table_data_submarino); | |
| } else { | |
| $specialprice = $this->checkPrice($product['special_price'], $this->plugg,'special_price',$product,null,$this->plugg->b2w->table_data_submarino); | |
| } | |
| if(isset($variacao['price']) && isset($variacao['special_price'])){ | |
| $price = $this->checkPrice($variacao['price'], $this->plugg,'price',$product,$variacao,$this->plugg->b2w->table_data_submarino); | |
| } else { | |
| $price = $this->checkPrice($product['price'], $this->plugg,'price',$product,null,$this->plugg->b2w->table_data_submarino); | |
| } | |
| $specialprice = $this->checkIfPriceIsBiggerThanSpecialPrice($price,$specialprice); | |
| if(!empty($price) && !empty($specialprice)){ | |
| $brandPrice[] = array('store'=>'SUBMARINO','listPrice'=>$price,'sellPrice'=>$specialprice); | |
| } | |
| } | |
| if(isset($this->plugg->b2w->table_data_shoptime)){ | |
| if(isset($variacao['price']) && isset($variacao['special_price'])){ | |
| $specialprice = $this->checkPrice($variacao['special_price'], $this->plugg,'special_price',$product,$variacao,$this->plugg->b2w->table_data_shoptime); | |
| } else { | |
| $specialprice = $this->checkPrice($product['special_price'], $this->plugg,'special_price',$product,null,$this->plugg->b2w->table_data_shoptime); | |
| } | |
| if(isset($variacao['price']) && isset($variacao['special_price'])){ | |
| $price = $this->checkPrice($variacao['price'], $this->plugg,'price',$product,$variacao,$this->plugg->b2w->table_data_shoptime); | |
| } else { | |
| $price = $this->checkPrice($product['price'], $this->plugg,'price',$product,null,$this->plugg->b2w->table_data_shoptime); | |
| } | |
| $specialprice = $this->checkIfPriceIsBiggerThanSpecialPrice($price,$specialprice); | |
| if(!empty($price) && !empty($specialprice)){ | |
| $brandPrice[] = array('store'=>'SHOPTIME','listPrice'=>$price,'sellPrice'=>$specialprice); | |
| } | |
| } | |
| if(isset($this->plugg->b2w->table_data_soubarato)){ | |
| if(isset($variacao['price']) && isset($variacao['special_price'])){ | |
| $specialprice = $this->checkPrice($variacao['special_price'], $this->plugg,'special_price',$product,$variacao,$this->plugg->b2w->table_data_soubarato); | |
| } else { | |
| $specialprice = $this->checkPrice($product['special_price'], $this->plugg,'special_price',$product,null,$this->plugg->b2w->table_data_soubarato); | |
| } | |
| if(isset($variacao['price']) && isset($variacao['special_price'])){ | |
| $price = $this->checkPrice($variacao['price'], $this->plugg,'price',$product,$variacao,$this->plugg->b2w->table_data_soubarato); | |
| } else { | |
| $price = $this->checkPrice($product['price'], $this->plugg,'price',$product,null,$this->plugg->b2w->table_data_soubarato); | |
| } | |
| $specialprice = $this->checkIfPriceIsBiggerThanSpecialPrice($price,$specialprice); | |
| if(!empty($price) && !empty($specialprice)){ | |
| $brandPrice[] = array('store'=>'SOUBARATO','listPrice'=>$price,'sellPrice'=>$specialprice); | |
| } | |
| } | |
| return $brandPrice; | |
| } | |
| public function removeNotAllowedTags($description) | |
| { | |
| $description = preg_replace('/class=".*?"/', '', $description); | |
| //Substitui as tags | |
| //Chave do array = tag que deseja substituir | |
| //Valor do array = nova tag | |
| $tags_to_replace = array( | |
| '<li>' => '<p>-', | |
| '</li>' => '</p>', | |
| '<p> </p>' => '' | |
| ); | |
| //Substitui as tags conforme array acima | |
| $description = strtr($description, $tags_to_replace); | |
| //Remove todas as tags que não estejam sendo passadas no método | |
| $description = strip_tags($description, '<br><b><p><strong><i>'); | |
| //Substitui todos os caracteres especiais em HTML ( , ã ... e todos os outros ...) | |
| $description = html_entity_decode($description); | |
| return $description; | |
| return strip_tags($description, '<b></b><strong></strong><i></i><br></br><p></p>'); | |
| } | |
| // Envia skus para o b2w em massa | |
| public function createSku($id_product, $product, $options, $variacao = false, $manual = true) | |
| { | |
| if ($variacao) { | |
| $productSku = Sku::firstOrNew(array('sku' => $variacao['sku'])); | |
| $productSku->push(); | |
| $productSku->pluggto_id = $product['id']; | |
| $var['id'] = $productSku->id; | |
| $sku = $variacao['sku']; | |
| } else { | |
| $productSku = Sku::firstOrNew(array('sku' => $product['sku'])); | |
| $productSku->push(); | |
| $sku = $product['sku']; | |
| } | |
| if (!empty($sku)) { | |
| $productSku->sku = $sku; | |
| } | |
| $productSku->user_id = $this->plugg->id; | |
| if ($this->plugg->origin_sku) { | |
| $var['id'] = $this->formateSkuToB2w($productSku->sku); | |
| $productSku->b2w_sku = $this->formateSkuToB2w($productSku->sku); | |
| } else { | |
| $productSku->b2w_sku = $productSku->id; | |
| $var['id'] = $productSku->id; | |
| } | |
| $productSku->product_id = $id_product; | |
| // Product Name | |
| if (isset($options['name'])) { | |
| $this->share_title = false; | |
| $productSku->name = $options['name']; | |
| $var['name'] = $options['name']; | |
| } elseif (isset($variacao['name']) && !empty($variacao['name'])) { | |
| $productSku->name = $variacao['name']; | |
| $var['name'] = $variacao['name']; | |
| } else { | |
| $productSku->name = $product['name']; | |
| $var['name'] = $product['name']; | |
| } | |
| if (isset($options['description'])) { | |
| $this->share_description = false; | |
| $var['description'] = $options['description']; | |
| $productSku->description = $options['description']; | |
| } else { | |
| $var['description'] = $this->removeNotAllowedTags($product['description']); | |
| $productSku->description = $this->removeNotAllowedTags($product['description']); | |
| } | |
| // Peso e medidas | |
| if (isset($options['weight']) && $options['weight'] != 0) { | |
| $this->share_dimensions = false; | |
| $weight = $options['weight']; | |
| } elseif (isset($product['dimension']['weight']) && | |
| !empty($product['dimension']['weight']) && | |
| $product['dimension']['weight'] != 0 | |
| ) { | |
| $weight = $product['dimension']['weight']; | |
| } else { | |
| $weight = 1; | |
| } | |
| if (isset($options['height']) && $options['height'] != 0) { | |
| $this->share_dimensions = false; | |
| $height = $options['height']; | |
| } elseif (isset($product['dimension']['height']) && | |
| !empty($product['dimension']['height']) && | |
| $product['dimension']['height'] != 0 | |
| ) { | |
| $height = $product['dimension']['height']; | |
| } | |
| if (isset($options['lenght']) && $options['lenght'] != 0) { | |
| $this->share_dimensions = false; | |
| $lenght = $options['lenght']; | |
| } elseif (isset($product['dimension']['length']) && | |
| !empty($product['dimension']['length']) && | |
| $product['dimension']['length'] != 0 | |
| ) { | |
| $lenght = $product['dimension']['length']; | |
| } | |
| if (isset($options['width']) && $options['width'] != 0) { | |
| $this->share_dimensions = false; | |
| $width = $options['width']; | |
| } elseif (isset($product['dimension']['width']) && | |
| !empty($product['dimension']['width']) && | |
| $product['dimension']['width'] != 0 | |
| ) { | |
| $width = $product['dimension']['width']; | |
| } | |
| if (isset($weight)) { | |
| if ($this->plugg->peso == 'Kilo') { | |
| $var['weight'] = (float)$weight; | |
| $productSku->weight = (float)$weight; | |
| } else { | |
| $var['weight'] = (float)$weight / 1000; | |
| $productSku->weight = (float)$var['weight']; | |
| } | |
| } | |
| if (isset($width)) { | |
| if ($this->plugg->dimensions == 'Metros') { | |
| $var['width'] = (float)$width; | |
| $productSku->width = $width; | |
| } else { | |
| $var['width'] = (float)$width / 100; | |
| $productSku->width = $var['width']; | |
| } | |
| } | |
| if (isset($lenght)) { | |
| if ($this->plugg->dimensions == 'Metros') { | |
| $var['length'] = (float)$lenght; | |
| $productSku->length = $lenght; | |
| } else { | |
| $var['length'] = (float)$lenght / 100; | |
| $productSku->length = $var['length']; | |
| } | |
| } | |
| if (isset($height)) { | |
| if ($this->plugg->dimensions == 'Metros') { | |
| $var['height'] = (float)$height; | |
| $productSku->height = $height; | |
| } else { | |
| $var['height'] = (float)$height / 100; | |
| $productSku->height = $var['height']; | |
| } | |
| } | |
| if (isset($options['quantity'])) { | |
| $this->share_available_quantity = false; | |
| $var['stockQuantity'] = (int)$options['quantity']; | |
| $productSku->quantity = (int)$options['quantity']; | |
| } elseif ($variacao && isset($variacao['quantity'])) { | |
| $var['stockQuantity'] = (int)$variacao['quantity']; | |
| $productSku->quantity = (int)$variacao['quantity']; | |
| } else { | |
| $var['stockQuantity'] = (int)$product['quantity']; | |
| $productSku->quantity = (int)$product['quantity']; | |
| } | |
| if ($var['stockQuantity'] > 0) { | |
| $var['enable'] = true; | |
| $productSku->enable = true; | |
| } else { | |
| $var['enable'] = false; | |
| $productSku->enable = false; | |
| } | |
| // preço POR R$ .... | |
| // primeiro das opcoes | |
| if (isset($options['sale_price'])) { | |
| $this->share_price = false; | |
| $var['price']['sellPrice'] = $this->formatPriceManul($options['sale_price']); | |
| $productSku->special_price = false; | |
| // 2 - do preco espcial da variacao , caso exista e nao esteja zerada | |
| } elseif (isset($variacao['special_price']) && !empty($variacao['special_price'])) { | |
| $var['price']['sellPrice'] = $this->checkPrice($variacao['special_price'], $this->plugg,'special_price',$product,$variacao); | |
| $productSku->special_price = $var['price']['sellPrice']; | |
| // 3 - da preoco especial do produto , caso exista e nao esteja zerada | |
| } elseif(isset($product['special_price']) && !empty($product['special_price'])) { | |
| $var['price']['sellPrice'] = $this->checkPrice($product['special_price'], $this->plugg,'special_price',$product,$variacao); | |
| $productSku->special_price = $var['price']['sellPrice']; | |
| // 4 - da preoco da variacao , caso exista e nao esteja zerada | |
| } elseif(isset($variacao['price']) && !empty($variacao['price'])) { | |
| $var['price']['sellPrice'] = $this->checkPrice($variacao['price'], $this->plugg,'price',$product,$variacao); | |
| $productSku->special_price = $var['price']['sellPrice']; | |
| // 5 - da preco da produto | |
| } else { | |
| $var['price']['sellPrice'] = $this->checkPrice($product['price'], $this->plugg,'price',$product,$variacao); | |
| $productSku->special_price = $var['price']['sellPrice']; | |
| } | |
| // Preço DE R$ | |
| if (isset($options['price'])) { | |
| $this->share_sale_price = false; | |
| $var['price']['listPrice'] = $this->formatPriceManul($options['price']); | |
| $productSku->price = $this->formatPriceManul($options['price']); | |
| } else { | |
| $var['price']['listPrice'] = $this->checkPrice($product['price'], $this->plugg,'special_price',$product,$variacao); | |
| $productSku->price = $var['price']['listPrice']; | |
| } | |
| if ($var['price']['listPrice'] < $var['price']['sellPrice']) { | |
| $var['price']['listPrice'] = $var['price']['sellPrice']; | |
| } | |
| $brandPrice = $this->getBrandPrice($product,$var); | |
| if(!empty($brandPrice)){ | |
| $var['brandPrices'] = $brandPrice; | |
| } | |
| if ($variacao && isset($variacao['photos']) && is_array($variacao['photos']) && !empty($variacao['photos'])) { | |
| $count = 0; | |
| $VariProductPhotos = $this->formatImagesOrder($variacao['photos']); | |
| foreach ($VariProductPhotos as $photo) { | |
| $var['urlImage'][] = $photo['url']; | |
| $count++; | |
| if ($count >= 4) { | |
| break; | |
| } | |
| } | |
| } else { | |
| $count = 0; | |
| $ProductPhotos = $this->formatImagesOrder($product['photos']); | |
| foreach ($ProductPhotos as $photo) { | |
| $var['urlImage'][] = $photo['url']; | |
| $count++; | |
| if ($count >= 4) { | |
| break; | |
| } | |
| } | |
| } | |
| $variance = $this->countVariance; | |
| $productSku->variance = $variance; | |
| $var['variance'] = $this->countVariance; | |
| if (isset($options['handlingTime'])) { | |
| $var['crossDocking'] = $options['handlingTime']; | |
| $productSku->crossdocking = $options['handlingTime']; | |
| } elseif (!empty($product['handling_time'])) { | |
| $var['crossDocking'] = $product['handling_time']; | |
| $productSku->crossdocking = $product['handling_time']; | |
| } else { | |
| $var['crossDocking'] = $this->plugg->b2w->crossdoking; | |
| $productSku->crossdocking = $this->plugg->b2w->crossdoking; | |
| } | |
| if ($variacao) { | |
| if($this->plugg->b2w->send_ean){ | |
| if (isset($options['ean']) && !empty($options['ean'])) { | |
| $var['ean'][] = $options['ean']; | |
| $productSku->ean = $options['ean']; | |
| } elseif (isset($variacao['ean']) && !empty($variacao['ean'])) { | |
| $var['ean'][] = (int)$variacao['ean']; | |
| $productSku->ean = (int)$variacao['ean']; | |
| } elseif ($this->plugg->validate_ean) { | |
| $this->error[] = 'É obrigatório o cadastro do EAN do produto, verifique SKU ' . $sku; | |
| } else { | |
| if ($manual) { | |
| $var['marketStructure'] = $this->getMarketStructure(); | |
| } | |
| } | |
| } else { | |
| if ($manual) { | |
| $var['marketStructure'] = $this->getMarketStructure(); | |
| } | |
| } | |
| } else { | |
| if($this->plugg->b2w->send_ean){ | |
| if (isset($options['ean']) && !empty($options['ean']) ) { | |
| $var['ean'][] = (int)$options['ean']; | |
| $productSku->ean = (int)$options['ean']; | |
| } elseif (isset($product['ean']) && !empty($product['ean']) && !empty($product['ean'])) { | |
| $var['ean'][] = (int)$product['ean']; | |
| $productSku->ean = (int)$product['ean']; | |
| } elseif ($this->plugg->validate_ean) { | |
| $this->error[] = 'É obrigatório o cadastro do EAN do produto, verifique SKU ' . $sku; | |
| } else { | |
| $var['marketStructure'] = $this->getMarketStructure(); | |
| } | |
| } else { | |
| $var['marketStructure'] = $this->getMarketStructure(); | |
| } | |
| } | |
| $marketStructure = $this->getMarketStructure(); | |
| if(!empty($marketStructure)){ | |
| $var['marketStructure'] = $this->getMarketStructure(); | |
| } | |
| if (isset($var['urlImage'])) { | |
| $productSku->images = json_encode($var['urlImage']); | |
| } | |
| if ($variacao) { | |
| $var['attributeValues'] = $this->getProductAttributes($variacao['attributes'],$product); | |
| if (empty($var['attributeValues'])) { | |
| unset($var['attributeValues']); | |
| } else { | |
| $productSku->atributes = json_encode($var['attributeValues']); | |
| } | |
| } else { | |
| $var['attributeValues'] = $this->getProductAttributes($product['attributes'],$product); | |
| if (empty($var['attributeValues'])) { | |
| unset($var['attributeValues']); | |
| } else { | |
| $productSku->atributes = json_encode($var['attributeValues']); | |
| } | |
| } | |
| if (empty($this->error)) { | |
| $productSku->situation = 'NOT_INDEXED'; | |
| $productSku->save(); | |
| } | |
| return $var; | |
| } | |
| function tirarAcentos($string){ | |
| return preg_replace(array("/(á|à|ã|â|ä)/","/(Á|À|Ã|Â|Ä)/","/(é|è|ê|ë)/","/(É|È|Ê|Ë)/","/(í|ì|î|ï)/","/(Í|Ì|Î|Ï)/","/(ó|ò|õ|ô|ö)/","/(Ó|Ò|Õ|Ô|Ö)/","/(ú|ù|û|ü)/","/(Ú|Ù|Û|Ü)/","/(ñ)/","/(Ñ)/","/(&)/",'/;/'),explode(" ","a A e E i I o O u U n N - "),$string); | |
| } | |
| public function formateSkuToB2w($sku){ | |
| return $this->tirarAcentos(str_replace(' ','',$sku)); | |
| } | |
| // pega a estrutura de marketing / categorias | |
| public function getMarketStructure() | |
| { | |
| $categoryId = Session::get('category'); | |
| $subCategoryId = Session::get('subcategory'); | |
| $familyId = Session::get('family'); | |
| $subfamilyId = Session::get('subfamily'); | |
| if (!empty($categoryId) && | |
| !empty($subCategoryId) && | |
| !empty($familyId) && | |
| !empty($subfamilyId) | |
| ) { | |
| return array( | |
| 'categoryId' => (int)$categoryId, | |
| 'subCategoryId' => (int)$subCategoryId, | |
| 'familyId' => (int)$familyId, | |
| 'subFamilyId' => (int)$subfamilyId, | |
| ); | |
| } else { | |
| return array(); | |
| $this->error[] = 'Para produtos sem EAN é obrigatório informar a categoria do produto na B2W.'; | |
| } | |
| } | |
| // envia produto para a b2w | |
| public function createProduct($product, $options) | |
| { | |
| $this->loadPlugg(); | |
| $this->countVariance = 0; | |
| if (!is_array($product)) { | |
| $product = $this->plugg->request('products/' . $product, 'GET', array(), 'query'); | |
| } | |
| $item = Product::firstOrNew(array('pluggto_id' => $product['id'])); | |
| $this->error = array(); | |
| $item->user_id = $this->plugg->id; | |
| // PRODUCT | |
| // ID | |
| if ($this->plugg->origin_sku) { | |
| $item->sku = $product['sku']; | |
| $toB2w['id'] = $this->formateSkuToB2w($product['sku']); | |
| $item->b2w_sku = $toB2w['id']; | |
| } else { | |
| $toB2w['id'] = $product['id']; | |
| $item->b2w_sku = $toB2w['id']; | |
| $item->sku = $toB2w['id']; | |
| } | |
| // BRAND | |
| if (isset($options['brand'])) { | |
| $this->share_brand = false; | |
| $toB2w['manufacturer']['name'] = $options['brand']; | |
| $item->manufactory_name = $options['brand']; | |
| } elseif (isset($product['brand']) && !empty($product['brand'])) { | |
| $toB2w['manufacturer']['name'] = $product['brand']; | |
| $item->manufactory_name = $product['brand']; | |
| } else { | |
| $this->error[] = 'Brand cannot be empty'; | |
| } | |
| // DELIVERY TYPE | |
| if (isset($options['deliveryType'])) { | |
| $toB2w['deliveryType'] = $options['deliveryType']; | |
| $item->delivery_type = $options['deliveryType']; | |
| } elseif (isset($product['deliveryType']) && !empty($product['deliveryType'])) { | |
| switch ($product['deliveryType']): | |
| case 'withdrawInStore'; | |
| $toB2w['deliveryType'] = 'WITHDRAW'; | |
| $item->delivery_type = 'WITHDRAW'; | |
| break; | |
| case 'post': | |
| $toB2w['deliveryType'] = 'SHIPMENT'; | |
| $item->delivery_type = 'SHIPMENT'; | |
| break; | |
| case 'both': | |
| $toB2w['deliveryType'] = 'ALL'; | |
| $item->delivery_type = 'ALL'; | |
| break; | |
| endswitch; | |
| } else { | |
| $item->delivery_type = $this->plugg->b2w->deliveryType; | |
| $toB2w['deliveryType'] = $this->plugg->b2w->deliveryType; | |
| } | |
| // Product Name | |
| if (isset($options['name'])) { | |
| $this->share_title = false; | |
| $toB2w['name'] = $options['name']; | |
| $item->name = $options['name']; | |
| } else { | |
| $item->name = $product['name']; | |
| $toB2w['name'] = $product['name']; | |
| } | |
| // NBM | |
| if (isset($product['nbm']) && !empty($product['nbm'])) { | |
| $toB2w['nbm']['number'] = $product['nbm']; | |
| $item->nbm_number = $product['nbm']; | |
| } | |
| if (isset($product['origin']) && !empty($product['origin'])) { | |
| $toB2w['nbm']['origin'] = $product['origin']; | |
| $item->nbm_origin = $product['origin']; | |
| } else { | |
| $toB2w['nbm']['origin'] = $this->plugg->b2w->origin; | |
| $item->nbm_origin = $this->plugg->b2w->origin; | |
| } | |
| // Skus | |
| $this->productAttribute = $this->getProductAttributes($product['attributes'],$product); | |
| if (isset($product['variations']) && is_array($product['variations']) | |
| && !empty($product['variations']) | |
| ) { | |
| foreach ($product['variations'] as $vari) { | |
| $toB2w['sku'][] = $this->createSku($item->id, $product, $options, $vari); | |
| $this->countVariance++; | |
| } | |
| } else { | |
| $toB2w['sku'][] = $this->createSku($item->id, $product, $options); | |
| } | |
| $b2w = new B2w(); | |
| //debug($toB2w);die; | |
| // retorna erro | |
| if (!empty($this->error)) { | |
| return $this->returnError($product, 'html', $item); | |
| } | |
| $item->push(); | |
| $result = $b2w->request('product', 'POST', $toB2w, 'jsonCreate'); | |
| // retry 3 times in case of error at b2w | |
| if ($result['status']['http_code'] != 201 && isset($result['body']['message'])) { | |
| $result = $b2w->request('product', 'POST', $toB2w, 'jsonCreate'); | |
| if ($result['status']['http_code'] != 201 && isset($result['body']['message'])) { | |
| $result = $b2w->request('product', 'POST', $toB2w, 'jsonCreate'); | |
| } | |
| } | |
| if ($result['status']['http_code'] == 201) { | |
| $toPlugg = array( | |
| 'available' => 1, | |
| 'update' => 0, | |
| ); | |
| try { | |
| $plugg = new Plugg($item->user_id); | |
| $plugg->request('products/' . $item->pluggto_id, 'PUT', $toPlugg); | |
| } catch (exception $e) { | |
| } | |
| if (isset($result['header']['location'])) { | |
| $item->location = $result['header']['location']; | |
| $item->save(); | |
| $skusOks = Sku::where('pluggto_id', $item->pluggto_id)->get(); | |
| // seta o status do sku sem erro | |
| foreach ($skusOks as $skusOk) { | |
| $skusOk->status = 'enviado'; | |
| $skusOk->error_mensage = null; | |
| $skusOk->save(); | |
| } | |
| return; | |
| } else { | |
| $this->error[] = 'Ocorreu um erro inesperado, tente novamente'; | |
| return $this->returnError($product, 'html', $item); | |
| } | |
| } else { | |
| $skusErros = Sku::where('pluggto_id', $item->pluggto_id)->get(); | |
| foreach ($skusErros as $skerror) { | |
| if (isset($result['body']['message'])) { | |
| $skerror->error_mensage = $result['body']['message']; | |
| } else { | |
| $skerror->error_mensage = 'Erro não informado pela B2W'; | |
| } | |
| $skerror->status = 'error'; | |
| $skerror->enable = 0; | |
| $skerror->save(); | |
| } | |
| $item->status = 'error'; | |
| $item->push(); | |
| if (isset($result['body']['message'])) { | |
| if (!empty($result['body']['message'])) { | |
| $this->error[] = $result['body']['message']; | |
| } | |
| } else { | |
| $this->error[] = 'Ocorreu um problema interno na B2W, tente novamente mais tarde'; | |
| } | |
| if (isset($result['body']['validationErrors'])) { | |
| $this->generateB2wError($result['body']['validationErrors']); | |
| } | |
| return $this->returnError($product, null, $item); | |
| } | |
| } | |
| public function returnError($product, $type = 'html', $item) | |
| { | |
| if (is_array($this->error) && !empty($this->error)) { | |
| if ($type == 'html') { | |
| $error = implode('<br>', $this->error); | |
| } else { | |
| $error = implode('/n', $this->error); | |
| } | |
| } else { | |
| $error = $this->error; | |
| } | |
| $result['erro']['description'] = $error; | |
| $result['erro']['sellingTitle'] = $product['name']; | |
| $result['erro']['pluggid'] = $product['id']; | |
| $result['erro']['status'] = 'error'; | |
| $result['erro']['product'] = $item; | |
| return $result; | |
| } | |
| // from extra | |
| public function saveManual($item, $POST) | |
| { | |
| if ($item->has_vari) { | |
| if (isset($POST['variacao'])) { | |
| $toreturn = array(); | |
| $toreturn['status'] = 'success'; | |
| foreach ($POST['variacao'] as $key => $variacoes) { | |
| $findItem = ItemVari::where('pluggto_id', $key)->firstOrFail(); | |
| $retorno = $this->manualChange($findItem, $variacoes); | |
| if ($retorno['status'] == 'fail') { | |
| $toreturn['status'] = 'fail'; | |
| $toreturn['response'] = $retorno['response']; | |
| } | |
| } | |
| return $toreturn; | |
| } | |
| } else { | |
| return $this->manualChange($item, $POST); | |
| } | |
| } | |
| public function joinAllProduct($user_id = null) | |
| { | |
| $b2w = new B2w($user_id); | |
| $page = 0; | |
| $productsArray = array(); | |
| $showing = 0; | |
| do { | |
| $body = array(); | |
| $body['offset'] = $page; | |
| $body['limit'] = 50; | |
| $resource = $b2w->request('sku', 'GET', $body, 'query'); | |
| $status = $resource['status']['http_code']; | |
| if ($status == 200) { | |
| $showing = count($resource['body']['skus']); | |
| $page = $page + $body['limit']; | |
| $productsArray = array_merge($productsArray, $resource['body']['skus']); | |
| $already = $showing + count($productsArray); | |
| } else if($status == 423){ | |
| if(isset($resource['body']['message']) && !empty($resource['body']['message'])){ | |
| throw new exception($resource['body']['message']); | |
| } | |
| } | |
| } while ($showing > 0 && $status == 200); | |
| return $productsArray; | |
| } | |
| public function CreateOnPluggto($sku, $userid) | |
| { | |
| try { | |
| $plugg = new Plugg($userid); | |
| } catch (exception $e) { | |
| return false; | |
| } | |
| if (isset($sku['id'])) $body['sku'] = $sku['id']; | |
| if (isset($sku['name'])) $body['name'] = $sku['name']; | |
| if (isset($sku['description'])) $body['description'] = $sku['description']; | |
| if (isset($sku['ean'][0])) $body['ean'] = $sku['ean'][0]; | |
| if (isset($sku['height'])) $body['dimension']['height'] = $sku['height']; | |
| if (isset($sku['width'])) $body['dimension']['width'] = $sku['width']; | |
| if (isset($sku['length'])) $body['dimension']['length'] = $sku['length']; | |
| if (isset($sku['weight'])) $body['dimension']['weight'] = $sku['weight']; | |
| if (isset($sku['stockQuantity'])) $body['quantity'] = $sku['stockQuantity']; | |
| if (isset($sku['enable'])) $body['available'] = $sku['enable']; | |
| if (isset($sku['price']['listPrice'])) $body['price'] = $sku['price']['listPrice']; | |
| if (isset($sku['price']['sellPrice'])) $body['special_price'] = $sku['price']['sellPrice']; | |
| if (isset($sku['urlImage'])) { | |
| $i = 0; | |
| foreach ($sku['urlImage'] as $img) { | |
| $i++; | |
| $tophotos[] = array('url' => $img, 'order' => (int)$i); | |
| } | |
| } | |
| if (isset($sku['attributeValues'])) { | |
| $attributes = array(); | |
| foreach ($sku['attributeValues'] as $att) { | |
| $thisatt = array(); | |
| $thisatt['value']['code'] = $att['value']; | |
| $thisatt['code'] = $att['name']; | |
| $attributes[] = $thisatt; | |
| } | |
| $body['attributes'] = $attributes; | |
| } | |
| try { | |
| $result = $plugg->request('products', 'POST', $body, 'json'); | |
| return $result; | |
| } catch (exception $e) { | |
| return false; | |
| } | |
| } | |
| public function importOrJoinFromB2w($sendToPluggTo = false) | |
| { | |
| $skus = $this->joinAllProduct(); | |
| $notfound = array(); | |
| foreach ($skus as $sku) { | |
| $result = $this->createFromB2wSku($sku, $sendToPluggTo); | |
| if (isset($result['notfound'])) { | |
| $notfound[] = $result['notfound']; | |
| } | |
| } | |
| return $notfound; | |
| } | |
| public function createFromB2wSku($sku, $sendToPluggTo = false) | |
| { | |
| $plugg = loadClass('Plugg'); | |
| try{ | |
| $result = $plugg->request('products', 'GET', array('bysku' => $sku['id']), 'query'); | |
| } catch (exception $e){ | |
| $tries = 0; | |
| $ok = false; | |
| while(!$ok){ | |
| if($tries > 3){ | |
| $result = array(); | |
| break; | |
| } | |
| try{ | |
| $result = $plugg->request('products', 'GET', array('bysku' => $sku['id']), 'query'); | |
| $ok = true; | |
| } catch (exception $e){ | |
| } | |
| $tries ++; | |
| } | |
| } | |
| if (isset($result["body"]["result"]["0"]["Product"])) { | |
| $Pluggproduct = $result["body"]["result"]["0"]["Product"]; | |
| } elseif ($sendToPluggTo) { | |
| $Pluggproduct = $this->CreateOnPluggto($sku, $plugg->id); | |
| if (isset($Pluggproduct['body']['Product'])) { | |
| $Pluggproduct = $Pluggproduct['body']['Product']; | |
| } else { | |
| return; | |
| } | |
| } else { | |
| $notFound['notfound'] = $sku['id']; | |
| return $notFound; | |
| } | |
| // is variation | |
| if (isset($Pluggproduct['variations']) && count($Pluggproduct['variations']) > 0) { | |
| foreach ($Pluggproduct['variations'] as $varia) { | |
| if ($varia['sku'] == $sku['id']) { | |
| $bdsku = Sku::firstOrCreate(array('pluggto_var_id' => $varia["id"])); | |
| } | |
| } | |
| if (!isset($bdsku)) { | |
| // TODO somenthing where not find this variation (should not happen) | |
| return false; | |
| } | |
| // is not a variation | |
| } else { | |
| try { | |
| $bdsku = Sku::firstOrCreate(array('pluggto_id' => $Pluggproduct['id'])); | |
| } catch (exception $e) { | |
| debug($Pluggproduct); | |
| die; | |
| } | |
| } | |
| $bdproduct = Product::firstOrCreate(array('pluggto_id' => $Pluggproduct['id'])); | |
| $bdproduct->user_id = $plugg->id; | |
| $bdproduct->pluggto_id = $Pluggproduct['id']; | |
| $bdproduct->sku = $Pluggproduct['sku']; | |
| if (isset($sku['name'])) $bdproduct->name = $sku['name']; | |
| if (isset($sku['link']['href'])) $bdproduct->location = $sku['link']['href']; | |
| $bdproduct->push(); | |
| $bdsku->user_id = $plugg->id; | |
| $bdsku->pluggto_id = $Pluggproduct['id']; | |
| if (isset($sku['id'])) $bdsku->b2w_sku = $sku['id']; | |
| if (isset($sku['id'])) $bdsku->sku = $sku['id']; | |
| if (isset($bdproduct['id'])) $bdsku->product_id = $bdproduct['id']; | |
| if (isset($sku['name'])) $bdsku->name = $sku['name']; | |
| if (isset($sku['description'])) $bdsku->description = $sku['description']; | |
| if (isset($sku['ean'][0])) $bdsku->ean = $sku['ean'][0]; | |
| if (isset($sku['height'])) $bdsku->height = $sku['height']; | |
| if (isset($sku['width'])) $bdsku->width = $sku['width']; | |
| if (isset($sku['length'])) $bdsku->length = $sku['length']; | |
| if (isset($sku['weight'])) $bdsku->weight = $sku['weight']; | |
| if (isset($sku['stockQuantity'])) $bdsku->quantity = $sku['stockQuantity']; | |
| if (isset($sku['enable'])) $bdsku->enable = $sku['enable']; | |
| if (isset($sku['urlImage'])) $bdsku->images = json_encode($sku['urlImage']); | |
| if (isset($sku['variance'])) $bdsku->variance = $sku['variance']; | |
| if (isset($sku['crossDocking'])) $bdsku->crossdocking = $sku['crossDocking']; | |
| if (isset($sku['attributeValues'])) $bdsku->atributes = json_encode($sku['attributeValues']); | |
| if (isset($sku['price']['sellPrice'])) $bdsku->special_price = $sku['price']['sellPrice']; | |
| if (isset($sku['price']['listPrice'])) $bdsku->price = $sku['price']['listPrice']; | |
| if (isset($sku['B2WLinks']['americanas'])) $bdsku->link_americana = $sku['B2WLinks']['americanas']; | |
| if (isset($sku['B2WLinks']['submarino'])) $bdsku->link_submarino = $sku['B2WLinks']['submarino']; | |
| if (isset($sku['B2WLinks']['shoptime'])) $bdsku->link_shoptime = $sku['B2WLinks']['shoptime']; | |
| $bdsku->share_quantity = 1; | |
| $bdsku->share_price = 1; | |
| $bdsku->push(); | |
| } | |
| // from b2w | |
| public function saveSku($sku, $POST) | |
| { | |
| $updatePrice = false; | |
| $error = array(); | |
| $b2w = new B2w(); | |
| if (isset($POST['defaultprice']) && isset($POST['specialprice'])) { | |
| $toB2W['listPrice'] = (float)$this->formatPriceBd($POST['defaultprice'], 2); | |
| $toB2W['sellPrice'] = (float)$this->formatPriceBd($POST['specialprice'], 2); | |
| $updatePrice = true; | |
| } elseif (isset($POST['specialprice'])) { | |
| $updatePrice = true; | |
| $toB2W['sellPrice'] = (float)$this->formatPriceBd($POST['specialprice'], 2); | |
| $toB2W['listPrice'] = (float)$sku->price; | |
| } elseif (isset($POST['defaultprice'])) { | |
| $updatePrice = true; | |
| $toB2W['listPrice'] = (float)$this->formatPriceBd($POST['defaultprice'], 2); | |
| $toB2W['sellPrice'] = (float)$sku->special_price; | |
| } | |
| if ($updatePrice) { | |
| $result = $b2w->request('sku/' . $sku->b2w_sku . '/price', 'PUT', $toB2W, 'json'); | |
| if ($result['status']['http_code'] == '204') { | |
| $sku->price = $toB2W['listPrice']; | |
| $sku->special_price = $toB2W['sellPrice']; | |
| $sku->share_price = 0; | |
| $sku->push(); | |
| } else if($result['status']['http_code'] == '422') { | |
| $toB2W = array(); | |
| $toB2W['quantity'] = (int)$POST['availableQuantity']; | |
| $result = $b2w->request('sku/' . strtoupper($sku->b2w_sku) . '/price', 'PUT', $toB2W, 'json'); | |
| if ($result['status']['http_code'] == '204') { | |
| $sku->price = $toB2W['listPrice']; | |
| $sku->special_price = $toB2W['sellPrice']; | |
| $sku->share_price = 0; | |
| $sku->push(); | |
| } else { | |
| if (isset($result['body']['message'])) { | |
| $error[] = $result['body']['message']; | |
| } elseif ($result['body']) { | |
| $error[] = $result; | |
| } else { | |
| $error[] = 'Ocorreu um erro ao atualizar a quantidade do produto.'; | |
| } | |
| } | |
| } else { | |
| if (isset($result['body']['errorDesc'])) { | |
| $error[] = $result['body']['errorDesc']; | |
| } elseif ($result['body']) { | |
| $error[] = print_r($result,1); | |
| } else { | |
| $error[] = 'Ocorreu um erro ao atualizar o preço do Sku'; | |
| } | |
| } | |
| } | |
| if (isset($POST['availableQuantity'])) { | |
| $toB2W = array(); | |
| $toB2W['quantity'] = (int)$POST['availableQuantity']; | |
| $result = $b2w->request('sku/' . $sku->b2w_sku . '/stock', 'PUT', $toB2W, 'json'); | |
| if ($result['status']['http_code'] == '204') { | |
| $sku->quantity = $toB2W['quantity']; | |
| $sku->share_quantity = 0; | |
| $sku->push(); | |
| } elseif($result['status']['http_code'] == '422') { | |
| $toB2W = array(); | |
| $toB2W['quantity'] = (int)$POST['availableQuantity']; | |
| $result = $b2w->request('sku/' . strtoupper($sku->b2w_sku) . '/stock', 'PUT', $toB2W, 'json'); | |
| if ($result['status']['http_code'] == '204') { | |
| $sku->quantity = $toB2W['quantity']; | |
| $sku->share_quantity = 0; | |
| $sku->push(); | |
| } else { | |
| if (isset($result['body']['message'])) { | |
| $error[] = $result['body']['message']; | |
| } elseif ($result['body']) { | |
| $error[] = $result; | |
| } else { | |
| $error[] = 'Ocorreu um erro ao atualizar a quantidade do produto.'; | |
| } | |
| } | |
| } else { | |
| if (isset($result['body']['message'])) { | |
| $error[] = $result['body']['message']; | |
| } elseif ($result['body']) { | |
| $error[] = $result; | |
| } else { | |
| $error[] = 'Ocorreu um erro ao atualizar a quantidade do produto.'; | |
| } | |
| } | |
| } | |
| if (isset($POST['status'])) { | |
| $toB2W = array(); | |
| $toB2W['enable'] = (bool)$POST['status']; | |
| $result = $b2w->request('/sku/' . $sku->b2w_sku . '/status', 'PUT', $toB2W, 'json'); | |
| if ($result['status']['http_code'] == '204') { | |
| $sku->status = $POST['status']; | |
| $sku->push(); | |
| } elseif ($result['status']['http_code'] == '422') { | |
| $toB2W = array(); | |
| $toB2W['enable'] = (bool)$POST['status']; | |
| $result = $b2w->request('/sku/' . strtoupper($sku->b2w_sku) . '/status', 'PUT', $toB2W, 'json'); | |
| if ($result['status']['http_code'] == '204') { | |
| $sku->status = $POST['status']; | |
| $sku->push(); | |
| $sku->push(); | |
| } else { | |
| if (isset($result['body']['message'])) { | |
| $error[] = $result['body']['message']; | |
| } elseif ($result['body']) { | |
| $error[] = $result; | |
| } else { | |
| $error[] = 'Ocorreu um erro ao alterar o status do Sku.'; | |
| } | |
| } | |
| } else { | |
| if (isset($result['body']['message'])) { | |
| $error[] = $result['body']['message']; | |
| } elseif ($result['body']) { | |
| $error[] = $result; | |
| } else { | |
| $error[] = 'Ocorreu um erro ao alterar o status do Sku.'; | |
| } | |
| } | |
| if (!empty($error)) { | |
| $retorno['status'] = 'fail'; | |
| $retorno['response'] = implode('<br>', $error); | |
| } else { | |
| $retorno['status'] = 'success'; | |
| } | |
| } | |
| return $retorno; | |
| } | |
| public function updateFromPluggTo($resource, $user) | |
| { | |
| $this->product = $resource['Product']; | |
| if (is_array($resource['Product']['variations']) && count($resource['Product']['variations']) > 0) { | |
| foreach ($resource['Product']['variations'] as $variation) { | |
| $this->updateOneFromPluggTo($variation, $user); | |
| } | |
| } else { | |
| $this->updateOneFromPluggTo($resource['Product'], $user); | |
| } | |
| } | |
| public function updateOneFromPluggTo($resource, $user) | |
| { | |
| try { | |
| if(!empty($user->id)){ | |
| $user_id = $user->id; | |
| } else { | |
| $user_id = $user->plugg_id; | |
| } | |
| $item = Sku::where('sku',$resource['sku'])->where('user_id',$user_id)->firstOrFail(); | |
| $updatePrice = false; | |
| $updateQuantity = false; | |
| $toB2W = array(); | |
| $toB2WQtd = array(); | |
| if (!empty($resource['price'])) { | |
| $price = $resource['price']; | |
| } else { | |
| $price = $this->product['price']; | |
| } | |
| if (!empty($resource['special_price'])) { | |
| $specialprice = $resource['special_price']; | |
| } else if(!empty($this->product['special_price'])) { | |
| $specialprice = $this->product['special_price']; | |
| } else { | |
| $specialprice = $this->product['price']; | |
| } | |
| if ($item->share_price && | |
| !empty($specialprice) && | |
| ($specialprice < $price) | |
| ) { | |
| $toB2W['listPrice'] = $this->checkPrice($price,$user,'price',$this->product,$resource); | |
| $toB2W['sellPrice'] = $this->checkPrice($specialprice,$user,'special_price',$this->product,$resource); | |
| $updatePrice = true; | |
| } else if ($item->share_price) { | |
| $toB2W['listPrice'] = $this->checkPrice($price,$user,'price',$this->product,$resource); | |
| $toB2W['sellPrice'] = $this->checkPrice($price,$user,'price',$this->product,$resource); | |
| $updatePrice = true; | |
| } | |
| if ($item->share_quantity) { | |
| $updateQuantity = true; | |
| if($resource['quantity'] < 0){ | |
| $resource['quantity'] = 0; | |
| } | |
| $toB2WQtd['quantity'] = $resource['quantity']; | |
| } | |
| $b2w = new B2w($item->user_id); | |
| if ($updatePrice) { | |
| $result = $b2w->request('sku/' . rawurlencode($item->b2w_sku) . '/price', 'PUT', $toB2W, 'json'); | |
| if ($result['status']['http_code'] == '204') { | |
| $item->price = $toB2W['listPrice']; | |
| $item->special_price = $toB2W['sellPrice']; | |
| $item->push(); | |
| } else if($result['status']['http_code'] == '422'){ | |
| $result = $b2w->request('sku/' . rawurlencode(strtoupper($item->b2w_sku)) . '/price', 'PUT', $toB2W, 'json'); | |
| if ($result['status']['http_code'] == '204') { | |
| $item->price = $toB2W['listPrice']; | |
| $item->special_price = $toB2W['sellPrice']; | |
| $item->push(); | |
| } else { | |
| if(isset($result['body']['message']) && strripos('not found',$result['body']['message'])){ | |
| } else { | |
| $this->loadPlugg($item->user_id); | |
| $erro = ['user_id'=>$item->user_id,'message'=>'Não foi possível atualizar o preço do produto '.$item->b2w_sku ,'application'=>'B2W','type'=>'products','description'=>print_r($result,1)]; | |
| $this->plugg->request('logs','POST',$erro,'json',true); | |
| } | |
| } | |
| } | |
| } | |
| if ($updateQuantity) { | |
| $result = $b2w->request('sku/' . rawurlencode($item->b2w_sku) . '/stock', 'PUT', $toB2WQtd, 'json'); | |
| if ($result['status']['http_code'] == '204') { | |
| $item->quantity = $toB2WQtd['quantity']; | |
| $item->push(); | |
| } else if($result['status']['http_code'] == '422'){ | |
| $result = $b2w->request('sku/' . rawurlencode(strtoupper($item->b2w_sku)) . '/stock', 'PUT', $toB2WQtd, 'json'); | |
| if ($result['status']['http_code'] == '204') { | |
| $item->price = $toB2W['listPrice']; | |
| $item->special_price = $toB2W['sellPrice']; | |
| $item->push(); | |
| } else { | |
| if(isset($result['body']['message']) && strripos('not found',$result['body']['message'])){ | |
| } else { | |
| $this->loadPlugg($item->user_id); | |
| $erro = ['user_id'=>$item->user_id,'message'=>'Não foi possível atualizar a quantidade do produto '.$item->b2w_sku ,'application'=>'B2W','type'=>'products','description'=>print_r($result,1)]; | |
| $this->plugg->request('logs','POST',$erro,'json',true); | |
| } | |
| } | |
| } | |
| } | |
| $brandsPrices = $this->getBrandPrice($this->product,$resource); | |
| if(!empty($brandsPrices)){ | |
| foreach($brandsPrices as $brandsPrices){ | |
| $result = $b2w->request('sku/' . rawurlencode($item->b2w_sku) . '/price', 'PUT', $brandsPrices, 'json'); | |
| if ($result['status']['http_code'] != '204') { | |
| $item->warning = $item->warning .= '<br>Data:'.date('Y-m-d H:m:s').' erro: Preço não atualizado para bandeira' . $brandsPrices['store']; | |
| $item->push(); | |
| } else if($result['status']['http_code'] == '422'){ | |
| $result = $b2w->request('sku/' . rawurlencode(strtoupper($item->b2w_sku)) . '/price', 'PUT', $brandsPrices, 'json'); | |
| if ($result['status']['http_code'] == '204') { | |
| $item->price = $toB2W['listPrice']; | |
| $item->special_price = $toB2W['sellPrice']; | |
| $item->push(); | |
| } | |
| } | |
| } | |
| } | |
| // unset to see if necessary sent a new variation | |
| if (isset($varis[$item->pluggto_var_id])) { | |
| unset($varis[$item->pluggto_var_id]); | |
| } | |
| } catch (exception $e){ | |
| // TODO -- AUTO CREATE | |
| // $this->createNewSku($bdproduct[0],$this->product,$resource); | |
| //$this->createNewSku($bdproduct[0], $resource['Product'], $vari); | |
| } | |
| } | |
| public function inactive($sku){ | |
| $b2w = new B2w($sku->user_id); | |
| $result = $b2w->request('sku/' . strtoupper($sku->b2w_sku) . '/status', 'PUT', array('enable'=>false), 'json'); | |
| if ($result['status']['http_code'] == 200 || $result['status']['http_code'] == 204) { | |
| $sku->enable = false; | |
| $sku->push(); | |
| } else { | |
| throw new exception ('Not possible to update sku'); | |
| } | |
| } | |
| protected function createNewSku($bdproduct, $pluggProduct, $vari) | |
| { | |
| $this->loadPlugg($bdproduct->user_id); | |
| $sku = $this->createSku($bdproduct->id, $pluggProduct, null, $vari, false); | |
| if (!empty($this->error)) { | |
| return; | |
| } | |
| $b2w = new B2w($bdproduct->user_id); | |
| if (!empty($bdproduct)) { | |
| $result = $b2w->request('product/' . $bdproduct->sku . '/sku', 'POST', $sku, 'jsonCreate'); | |
| } | |
| if ($result['status']['http_code'] == 201) { | |
| if (isset($result['header']['location'])) { | |
| $skusOks = Sku::where('b2w_sku', $sku['id'])->get(); | |
| // seta o status do sku sem erro | |
| foreach ($skusOks as $skusOk) { | |
| $skusOk->status = null; | |
| $skusOk->error_mensage = null; | |
| $skusOk->save(); | |
| } | |
| return; | |
| } else { | |
| return; | |
| } | |
| } else { | |
| $skusErros = Sku::where('b2w_sku', $sku['id'])->get(); | |
| foreach ($skusErros as $skerror) { | |
| if (isset($result['body']['message'])) { | |
| // $skerror->error_mensage = $result['body']['message']; | |
| } else { | |
| // $skerror->error_mensage = 'Erro não informado pela B2W'; | |
| } | |
| // $skerror->status = 'error'; | |
| $skerror->delete(); | |
| } | |
| if (isset($result['body']['message'])) { | |
| if (!empty($result['body']['message'])) { | |
| $this->error[] = $result['body']['message']; | |
| } | |
| } else { | |
| $this->error[] = 'Ocorreu um problema interno na B2W, tente novamente mais tarde'; | |
| } | |
| if (isset($result['body']['validationErrors'])) { | |
| $this->generateB2wError($result['body']['validationErrors']); | |
| } | |
| return; | |
| } | |
| } | |
| public function getOneTableDataFromPluggTo($page,$limit){ | |
| $data = array('page'=>$page,'limit'=>$limit); | |
| $result = $this->plugg->request('products/tabledata', 'GET',$data, 'query'); | |
| if(isset($result['body']['Products'])){ | |
| return $result['body']['Products']; | |
| } else { | |
| return false; | |
| } | |
| } | |
| public function gellTableDataFromPluggTo(){ | |
| $products = $this->getOneTableDataFromPluggTo(1,100); | |
| if (!$products){ | |
| $products = array(); | |
| } | |
| $page = 1; | |
| $_limit = 100; | |
| if (count($products) == 100) { | |
| $lastResult = $products; | |
| while (count($lastResult) == $_limit) { | |
| $page += 1; | |
| $_limit = 100; | |
| // try to get more | |
| $result = $this->getOneTableDataFromPluggTo($page, $_limit); | |
| $lastResult = $result; | |
| if (is_array($lastResult)) { | |
| $products = array_merge($lastResult,$products); | |
| } | |
| } | |
| } | |
| return $products; | |
| } | |
| public function syncAllProducts($user_id) | |
| { | |
| // GET All Products from Plugg.To | |
| $this->result['total_b2w'] = 0; | |
| $this->result['total_pluggto'] = 0; | |
| $this->result['total_connector'] = 0; | |
| $this->result['total_found_in_both'] = 0; | |
| $this->result['total_create_in_connector'] = 0; | |
| $this->result['total_not_in_pluggto'] = 0; | |
| $this->result['total_sync_necessary'] = 0; | |
| try { | |
| $user = User::where('plugg_id', $user_id)->firstOrFail(); | |
| } catch (exception $e) { | |
| echo 'user not found'; | |
| return; | |
| } | |
| $relatorio = array(); | |
| $plugg = new Plugg($user_id); | |
| $this->plugg = $plugg; | |
| $allPluggProductsTableData = $this->gellTableDataFromPluggTo(); | |
| $pluggProductsIdArray = array(); | |
| $pluggProductsSkuArray = array(); | |
| $allSkusinCnovaConnector = Sku::where('user_id', '=', $user_id)->get(); | |
| $allInConnector = array(); | |
| foreach ($allSkusinCnovaConnector as $connector) { | |
| $allInConnector[$connector->b2w_sku] = $connector; | |
| $this->result['total_connector'] ++; | |
| } | |
| foreach ($allPluggProductsTableData as $pluggProducts) { | |
| $pluggProductsIdArray[$pluggProducts['id']] = $pluggProducts; | |
| $pluggProductsSkuArray[trim($pluggProducts['sku'])] = $pluggProducts; | |
| // alternative sku | |
| $sku = $this->formateSkuToB2w($pluggProducts['sku']); | |
| $pluggProductsSkuArray[strtoupper(trim($sku))] = $pluggProducts; | |
| $this->result['total_pluggto'] ++; | |
| if (isset($pluggProducts['variations']) && is_array($pluggProducts['variations'])) { | |
| foreach ($pluggProducts['variations'] as $varis) { | |
| if (!isset($varis['id']) || !isset($varis['sku'])) { | |
| continue; | |
| } | |
| $variProduct = $varis; | |
| if (!empty($varis['sku'])) { | |
| $pluggProductsSkuArray[trim($varis['sku'])] = $variProduct; | |
| $pluggProductsSkuArray[trim($varis['sku'])]['pluggto_parent_id'] = $pluggProducts['id']; | |
| $pluggProductsSkuArray[trim($varis['sku'])]['parent'] = $pluggProducts; | |
| // alternative sku | |
| $sku = $this->formateSkuToB2w($varis['sku']); | |
| $pluggProductsSkuArray[strtoupper(trim($sku))] = $variProduct; | |
| $pluggProductsSkuArray[strtoupper(trim($sku))]['pluggto_parent_id'] = $pluggProducts['id']; | |
| $pluggProductsSkuArray[strtoupper(trim($sku))]['parent'] = $pluggProducts; | |
| } | |
| $this->result['total_pluggto'] ++; | |
| $variProduct['pluggto_parent_id'] = $pluggProducts['id']; | |
| $pluggProductsIdArray[$varis['id']] = $variProduct; | |
| } | |
| } | |
| } | |
| $B2WProduts = $this->joinAllProduct($user_id); | |
| // $b2w = new B2w($user_id); | |
| //$B2WProduts = $resource = $b2w->request('/sku/79413','GET',array(),'query'); | |
| // $B2WProduts = array($B2WProduts['body']); | |
| // debug($B2WProduts);die; | |
| if (is_array($B2WProduts) && !empty($B2WProduts)): | |
| foreach ($B2WProduts as $B2WProdut) { | |
| $this->result['total_b2w'] ++; | |
| try { | |
| if ($user->origin) { | |
| $findItem = Sku::where('b2w_sku',$B2WProdut['id'])->where('user_id',$user_id)->firstOrFail();; | |
| } else { | |
| $findItem = Sku::where('b2w_sku',$B2WProdut['id'])->where('user_id',$user_id)->firstOrFail();; | |
| } | |
| } catch (exception $e) { | |
| $findItem = false; | |
| } | |
| if ($findItem) { | |
| unset($allInConnector[$findItem->sku]); | |
| } | |
| if ($user->origin) { | |
| $cleanSku = $this->formateSkuToB2w($B2WProdut['id']); | |
| } else if (isset($findItem->sku) && !empty($findItem->sku)) { | |
| $cleanSku = $this->formateSkuToB2w($findItem->sku); | |
| } else { | |
| $cleanSku = $B2WProdut['id']; | |
| } | |
| $alternativeSku = strtoupper($cleanSku); | |
| if ($findItem && isset($pluggProductsSkuArray[$cleanSku])) { | |
| $plProduct = $pluggProductsSkuArray[$cleanSku]; | |
| unset($pluggProductsSkuArray[$cleanSku]); | |
| unset($pluggProductsIdArray[$plProduct['id']]); | |
| } else if (isset($pluggProductsSkuArray[$cleanSku])) { | |
| // Found by PluggTo Sku | |
| $plProduct = $pluggProductsSkuArray[$cleanSku]; | |
| unset($pluggProductsSkuArray[$cleanSku]); | |
| unset($pluggProductsIdArray[$plProduct['id']]); | |
| // check to see if not sku is not a pluggto id | |
| } else if (isset($pluggProductsIdArray[$cleanSku])) { | |
| $plProduct = $pluggProductsIdArray[$cleanSku]; | |
| unset($pluggProductsIdArray[$cleanSku]); | |
| if (isset($plProduct['sku'])) unset($pluggProductsSkuArray[$plProduct['sku']]); | |
| } else if (isset($pluggProductsSkuArray[$alternativeSku])) { | |
| // product not found in Plugg.To | |
| $plProduct = $pluggProductsSkuArray[$alternativeSku]; | |
| unset($pluggProductsSkuArray[$alternativeSku]); | |
| } else { | |
| $plProduct = false; | |
| } | |
| // item find in pluggto and cnova connector | |
| if ($plProduct && $findItem) { | |
| $this->result['total_found_in_both'] ++; | |
| $needupdate = false; | |
| if (!isset($plProduct['price'])) { | |
| continue; | |
| } | |
| if (isset($B2WProdut['situation'])) $findItem->situation = $B2WProdut['situation']; | |
| if (isset($B2WProdut['B2WLinks']['americanas'])) $findItem->link_americana = $B2WProdut['B2WLinks']['americanas']; | |
| if (isset($B2WProdut['B2WLinks']['submarino'])) $findItem->link_submarino = $B2WProdut['B2WLinks']['submarino']; | |
| if (isset($B2WProdut['B2WLinks']['shoptime'])) $findItem->link_shoptime = $B2WProdut['B2WLinks']['shoptime']; | |
| $findItem->push(); | |
| try { | |
| if(isset($plProduct['parent'])){ | |
| if (isset($plProduct['price'])) $price = $this->checkPrice($plProduct['price'],$user,'price',$plProduct['parent'],$plProduct); | |
| if (isset($plProduct['special_price'])) $specialprice = $this->checkPrice($plProduct['special_price'],$user,'special_price',$plProduct['parent'],$plProduct); | |
| } else { | |
| if (isset($plProduct['price'])) $price = $this->checkPrice($plProduct['price'],$user,'price',$plProduct); | |
| if (isset($plProduct['special_price'])) $specialprice = $this->checkPrice($plProduct['special_price'],$user,'special_price',$plProduct); | |
| } | |
| } catch (exception $e) { | |
| } | |
| if (isset($plProduct['pluggto_parent_id'])) { | |
| $findItem->pluggto_id = $plProduct['pluggto_parent_id']; | |
| $findItem->pluggto_var_id = $plProduct['id']; | |
| } else { | |
| $findItem->pluggto_id = $plProduct['id']; | |
| } | |
| if ($findItem->share_quantity && $plProduct['quantity'] != $B2WProdut['stockQuantity']) { | |
| $findItem->quantity = $plProduct['quantity']; | |
| $needupdate = true; | |
| } | |
| if (!isset($B2WProdut['price']['listPrice']) || ($findItem->share_price && isset($price) && !empty($price) && (isset($B2WProdut['price']['listPrice']) && $price != $B2WProdut['price']['listPrice']))) { | |
| $findItem->price = $price; | |
| $needupdate = true; | |
| } | |
| if ((!isset($B2WProdut['price']['sellPrice']) || $findItem->share_price && isset($specialprice) && !empty($specialprice) && isset($B2WProdut['price']['sellPrice']) && $specialprice != $B2WProdut['price']['sellPrice'])) { | |
| $findItem->special_price = $specialprice; | |
| $needupdate = true; | |
| } | |
| if (isset($B2WProdut['enable'])) { | |
| $findItem->enable = $B2WProdut['enable']; | |
| } | |
| if (isset($B2WProdut['situation'])) { | |
| $findItem->situation = $B2WProdut['situation']; | |
| } | |
| $findItem->push(); | |
| if ($needupdate) { | |
| $this->result['total_sync_necessary'] ++; | |
| $relatorio[$findItem->sku]['price'] = $findItem->price; | |
| $relatorio[$findItem->skuIdOrigin]['availableQuantity'] = $findItem->quantity; | |
| $relatorio[$findItem->skuIdOrigin]['what'] = 'Sincronização necessária'; | |
| $plugg->tries = 0; | |
| $resource = $plugg->request('skus/' . $findItem->sku, 'GET', array(), 'query'); | |
| if (isset($resource['body']['Product'])) { | |
| $this->updateFromPluggTo($resource['body'], $user); | |
| } | |
| } | |
| $findItem->push(); | |
| // item find in pluggto, but not find item create, need to create a item | |
| } else if ($plProduct && !$findItem) { | |
| $this->result['total_create_in_connector'] ++; | |
| $findItem = new Sku(); | |
| if(isset($plProduct['parent'])){ | |
| if (isset($plProduct['price'])) $price = $this->checkPrice($plProduct['price'],$user,'price',$plProduct['parent'],$plProduct); | |
| if (isset($plProduct['special_price'])) $specialprice = $this->checkPrice($plProduct['special_price'],$user,'special_price',$plProduct['parent'],$plProduct); | |
| } else { | |
| if (isset($plProduct['price'])) $price = $this->checkPrice($plProduct['price'],$user,'price',$plProduct); | |
| if (isset($plProduct['special_price'])) $specialprice = $this->checkPrice($plProduct['special_price'],$user,'special_price',$plProduct); | |
| } | |
| if (isset($plProduct['pluggto_parent_id'])) { | |
| $findItem->pluggto_id = $plProduct['pluggto_parent_id']; | |
| $findItem->pluggto_var_id = $plProduct['id']; | |
| } else { | |
| $findItem->pluggto_id = $plProduct['id']; | |
| } | |
| $findItem->name = $B2WProdut['name']; | |
| if (isset($B2WProdut['situation'])) $findItem->situation = $B2WProdut['situation']; | |
| if (isset($B2WProdut['B2WLinks']['americanas'])) $findItem->link_americana = $B2WProdut['B2WLinks']['americanas']; | |
| if (isset($B2WProdut['B2WLinks']['submarino'])) $findItem->link_submarino = $B2WProdut['B2WLinks']['submarino']; | |
| if (isset($B2WProdut['B2WLinks']['shoptime'])) $findItem->link_shoptime = $B2WProdut['B2WLinks']['shoptime']; | |
| $findItem->b2w_sku = $B2WProdut['id']; | |
| if (isset($B2WProduts['enable'])) { | |
| $findItem->enable = $B2WProduts['enable']; | |
| } else { | |
| $findItem->enable = 0; | |
| } | |
| $findItem->sku = $plProduct['sku']; | |
| $findItem->user_id = $user_id; | |
| if (isset($specialprice) && isset($price)) { | |
| if (!empty($plProduct['special_price'])) { | |
| $findItem->special_price = $specialprice; | |
| } else { | |
| $findItem->special_price = $price; | |
| } | |
| } | |
| if (isset($price)) { | |
| $findItem->price = $price; | |
| } | |
| if (isset($plProduct['quantity'])) { | |
| $findItem->quantity = $plProduct['quantity']; | |
| } | |
| $findItem->push(); | |
| // Verificar se necessita enviar atualização para Cnova | |
| if (isset( $plProduct['quantity']) && $plProduct['quantity'] != $B2WProdut['stockQuantity'] || | |
| $specialprice != $B2WProdut['price']['sellPrice'] || | |
| $price != $B2WProdut['price']['listPrice'] | |
| ) { | |
| $resource = $plugg->request('products/' . $findItem->pluggto_id, 'GET', array(), 'query'); | |
| if (isset($resource['body']['Product'])) { | |
| $this->updateFromPluggTo($resource['body'], $user); | |
| } | |
| } | |
| $relatorio[$B2WProdut['id']] = $B2WProdut; | |
| $relatorio[$B2WProdut['id']]['sku'] = $B2WProdut['id']; | |
| $relatorio[$B2WProdut['id']]['what'] = 'Importação para o connector Cnova'; | |
| $findItem->save(); | |
| // item not find in pluggto, but not find product in pluggto, should be reset the stock in cnova because is not linked | |
| } else if (!$plProduct && $findItem) { | |
| $fbody = array(); | |
| if ($user->origin) { | |
| $fbody['bysku'] = $findItem->b2w_sku; | |
| } else if (!empty($findItem->sku)) { | |
| $fbody['bysku'] = $findItem->sku; | |
| } else { | |
| $findItem->pluggto_id = ''; | |
| $findItem->pluggto_var_id = ''; | |
| $findItem->status = 'error'; | |
| $findItem->push(); | |
| $relatorio[$findItem->sku] = $findItem[$findItem->sku]; | |
| $relatorio[$findItem->sku]['what'] = 'Não encontrado no Pluggto'; | |
| continue; | |
| } | |
| $nresource = $plugg->request('products', 'GET', $fbody, 'query'); | |
| if (isset($nresource['body']['result'][0]['Product']['id'])) { | |
| $nPluggToProduct = $nresource['body']['result'][0]['Product']; | |
| if (isset($nPluggToProduct['variations']) && is_array($nPluggToProduct['variations'])) { | |
| $foundVari = false; | |
| foreach ($nPluggToProduct['variations'] as $variations) { | |
| if ($variations['sku'] == $fbody['bysku']) { | |
| $findItem->sku = $variations['sku']; | |
| $findItem->b2w_sku = $B2WProdut['id']; | |
| $findItem->pluggto_id = $nPluggToProduct['id']; | |
| $findItem->pluggto_var_id = $variations['id']; | |
| $findItem->quantity = $variations['quantity']; | |
| if (isset($B2WProdut['enable'])) { | |
| $findItem->enable = $B2WProdut['enable']; | |
| } | |
| if (isset($B2WProdut['situation'])) { | |
| $findItem->situation = $B2WProdut['situation']; | |
| } | |
| if (isset($B2WProduts['enable'])) { | |
| $findItem->enable = $B2WProduts['enable']; | |
| } else { | |
| $findItem->enable = 0; | |
| } | |
| $findItem->price = $variations['price']; | |
| $findItem->special_price = $variations['special_price']; | |
| $findItem->push(); | |
| $resource = $plugg->request('products/' . $findItem->pluggto_id, 'GET', array(), 'query'); | |
| if (isset($resource['body']['Product'])) { | |
| $this->updateFromPluggTo($resource['body'], $plugg); | |
| } | |
| } | |
| if (!$foundVari) { | |
| $findItem->status = 'error'; | |
| } | |
| } | |
| } else { | |
| $findItem->sku = $nPluggToProduct['sku']; | |
| $findItem->b2w_sku = $B2WProdut['id']; | |
| $findItem->pluggto_id = $nPluggToProduct['id']; | |
| $findItem->quantity = $nPluggToProduct['quantity']; | |
| $findItem->price = $nPluggToProduct['price']; | |
| $findItem->special_price = $nPluggToProduct['special_price']; | |
| if (isset($B2WProdut['enable'])) { | |
| $findItem->enable = $B2WProdut['enable']; | |
| } | |
| if (isset($B2WProdut['situation'])) { | |
| $findItem->situation = $B2WProdut['situation']; | |
| } | |
| if (isset($B2WProduts['enable'])) { | |
| $findItem->enable = $B2WProduts['enable']; | |
| } else { | |
| $findItem->enable = 0; | |
| } | |
| $findItem->push(); | |
| $resource = $plugg->request('products/' . $findItem->pluggto_id, 'GET', array(), 'query'); | |
| if (isset($resource['body']['Product'])) { | |
| $this->updateFromPluggTo($resource['body'], $user); | |
| } | |
| } | |
| } else { | |
| $this->result['total_not_in_pluggto'] ++; | |
| $findItem->pluggto_id = ''; | |
| $findItem->pluggto_var_id = ''; | |
| $findItem->status = 'error'; | |
| $findItem->push(); | |
| } | |
| $relatorio[$findItem->sku] = $findItem[$findItem->sku]; | |
| $relatorio[$findItem->sku]['what'] = 'Não encontrado no Pluggto'; | |
| // not find in plugg.to and in cnova | |
| } | |
| } | |
| endif; | |
| return $this->result; | |
| // debug($relatorio); | |
| } | |
| public static function formatPriceBd($number) | |
| { | |
| $source = array('.', ','); | |
| $replace = array('', '.'); | |
| $valor = str_replace($source, $replace, $number); //remove os pontos e substitui a virgula pelo ponto | |
| return self::numberFormat($valor, 2, '.', ''); //retorna o valor formatado para gravar no banco | |
| return (float)str_replace(',', '.', $number); | |
| } | |
| public static function formatData($dataHora) | |
| { | |
| $timestamp = strtotime($dataHora); | |
| return date('d/m/Y H:i', $timestamp); | |
| } | |
| public static function formatPrice($number) | |
| { | |
| $number = (float)$number; | |
| return "R$ " . number_format($number, 2, ',', '.'); | |
| } | |
| public static function situationFlag($value){ | |
| switch ($value): | |
| case 'INCLUDED': | |
| return '<span class="label label-success">Incluído</span>'; | |
| break; | |
| case 'NOT_INDEXED': | |
| return '<span class="label label-danger">Não incluido</span>'; | |
| break; | |
| case 'PENDING_MATCH': | |
| return '<span class="label label-info">Pendente de match</span>'; | |
| break; | |
| case 'RELEASED_MATCH': | |
| return '<span class="label label-info">Liberado de match</span>'; | |
| break; | |
| case 'PENDING_FIRST_PRICE_BLOCK': | |
| return '<span class="label label-info">Trava de primeiro preço</span>'; | |
| break; | |
| case 'PENDING_PRICE_BLOCK': | |
| return '<span class="label label-info">Trava de primeiro preço</span>'; | |
| break; | |
| case 'PENDING_PRICE_BLOCK_ANALYSIS': | |
| return '<span class="label label-info">Trava de variação de preço</span>'; | |
| break; | |
| case 'RELEASED_PRICE_BLOCK': | |
| return '<span class="label label-info">Liberado de trava de preço</span>'; | |
| break; | |
| case 'PENDING_EXCLUSIVITY_ANALYSIS': | |
| return '<span class="label label-info">Pendência de exclusividade</span>'; | |
| break; | |
| case 'RELEASED_EXCLUSIVITY': | |
| return '<span class="label label-info">Liberação de pendência de exclusividade</span>'; | |
| break; | |
| case 'INACTIVE': | |
| return '<span class="label label-danger">Inativo</span>'; | |
| break; | |
| case 'REACTIVATED': | |
| return '<span class="label label-success">Reativado</span>'; | |
| break; | |
| case 'EXCLUDED': | |
| return '<span class="label label-danger">Excluido</span>'; | |
| break; | |
| endswitch; | |
| } | |
| public static function statusFlag($value) | |
| { | |
| switch ($value): | |
| case 'new': | |
| return '<span class="label label-primary">' . self::changeValues($value) . '</span>'; | |
| break; | |
| case 'Produto indexado': | |
| return '<span class="label label-success">' . self::changeValues($value) . '</span>'; | |
| break; | |
| case 'Não importado': | |
| return '<span class="label label-danger">' . self::changeValues($value) . '</span>'; | |
| break; | |
| case 'active': | |
| return '<span class="label label-success">' . self::changeValues($value) . '</span>'; | |
| break; | |
| case 'inactive': | |
| return '<span class="label label-danger">' . self::changeValues($value) . '</span>'; | |
| break; | |
| case 'under_review': | |
| return '<span class="label label-warning">' . self::changeValues($value) . '</span>'; | |
| break; | |
| case 'not_yet_active': | |
| return '<span class="label label-primary">' . self::changeValues($value) . '</span>'; | |
| break; | |
| case 'payment_required': | |
| return '<span class="label label-warning">' . self::changeValues($value) . '</span>'; | |
| break; | |
| case 'confirmed': | |
| return '<span class="label label-primary">' . self::changeValues($value) . '</span>'; | |
| break; | |
| case 'payment_in_process': | |
| return '<span class="label label-warning">' . self::changeValues($value) . '</span>'; | |
| break; | |
| case 'paid': | |
| return '<span class="label label-success">' . self::changeValues($value) . '</span>'; | |
| break; | |
| case 'approved': | |
| return '<span class="label label-success">' . self::changeValues($value) . '</span>'; | |
| break; | |
| case 'canceled': | |
| case 'cancelled': | |
| return '<span class="label label-danger">' . self::changeValues($value) . '</span>'; | |
| break; | |
| case 'invalid': | |
| return '<span class="label label-danger">' . self::changeValues($value) . '</span>'; | |
| break; | |
| case 'handling': | |
| return '<span class="label label-warning">' . self::changeValues($value) . '</span>'; | |
| break; | |
| case 'shipped': | |
| return '<span class="label label-primary">' . self::changeValues($value) . '</span>'; | |
| break; | |
| case 'delivered': | |
| return '<span class="label label-success">' . self::changeValues($value) . '</span>'; | |
| break; | |
| case 'Not_delivered': | |
| return '<span class="label label-danger">' . self::changeValues($value) . '</span>'; | |
| break; | |
| case 'active': | |
| case '1': | |
| return '<span class="label label-success">' . self::changeValues('active') . '</span>'; | |
| break; | |
| case 'inactive': | |
| case '0': | |
| return '<span class="label label-danger">' . self::changeValues('inactive') . '</span>'; | |
| break; | |
| case 'to_be_agreed': | |
| return '<span class="label label-info">' . self::changeValues($value) . '</span>'; | |
| break; | |
| case 'ready_to_ship': | |
| return '<span class="label label-warning">' . self::changeValues($value) . '</span>'; | |
| break; | |
| default: | |
| default: | |
| return '<span class="label label-info">' . self::changeValues($value) . '</span>'; | |
| endswitch; | |
| } | |
| // from extra | |
| public static function changeValues($value) | |
| { | |
| switch ($value): | |
| case '0': | |
| return Lang::get('status.inactive'); | |
| break; | |
| case 'new': | |
| return Lang::get('status.Pending'); | |
| break; | |
| case 'pending': | |
| return Lang::get('status.Pending'); | |
| break; | |
| case 'active': | |
| return Lang::get('status.Active'); | |
| break; | |
| case 'paused': | |
| return Lang::get('status.Paused'); | |
| break; | |
| case 'closed': | |
| return Lang::get('status.Closed'); | |
| break; | |
| case 'under_review': | |
| return Lang::get('status.UnderReview'); | |
| break; | |
| case 'not_yet_active': | |
| return Lang::get('status.Activing'); | |
| break; | |
| case 'inactive': | |
| return Lang::get('status.inactive'); | |
| break; | |
| case 'payment_required': | |
| return Lang::get('status.PaymentRequired'); | |
| break; | |
| case 'confirmed': | |
| return Lang::get('status.Confirmed'); | |
| break; | |
| case 'paid': | |
| return Lang::get('status.Paid'); | |
| break; | |
| case 'approved': | |
| return Lang::get('status.Approved'); | |
| break; | |
| case 'payment_in_process': | |
| return Lang::get('status.Payment_in_process'); | |
| break; | |
| case 'cancelled': | |
| case 'canceled': | |
| return Lang::get('status.Cancelled'); | |
| break; | |
| case 'Invalid': | |
| return Lang::get('status.invalid'); | |
| break; | |
| case 'handling': | |
| return Lang::get('status.Handling'); | |
| break; | |
| case 'shipped': | |
| case 'sent': | |
| return Lang::get('status.Shipped'); | |
| break; | |
| case 'delivered': | |
| return Lang::get('status.Delivered'); | |
| break; | |
| case 'not_delivered': | |
| return Lang::get('status.Not_delivered'); | |
| break; | |
| case 'to_be_agreed': | |
| return Lang::get('status.ToAgree'); | |
| case 'ready_to_ship': | |
| return Lang::get('status.Ready'); | |
| break; | |
| case 'ANSWERED': | |
| return Lang::get('status.ANSWERED'); | |
| break; | |
| case 'UNANSWERED': | |
| return Lang::get('status.UNANSWERED'); | |
| break; | |
| default: | |
| return $value; | |
| break; | |
| endswitch; | |
| } | |
| // from extra | |
| public static function listStatuses() | |
| { | |
| return array( | |
| 'active' => Lang::get('status.Active'), | |
| 'paused' => Lang::get('status.Paused'), | |
| 'closed' => Lang::get('status.Closed'), | |
| 'under_review' => Lang::get('status.UnderReview'), | |
| 'not_yet_active' => Lang::get('status.Activing'), | |
| 'inactive' => Lang::get('status.Inactive'), | |
| 'payment_required' => Lang::get('status.PaymentRequired')); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment