Advertisement
Guest User

relojes

a guest
Jan 18th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 16.58 KB | None | 0 0
  1. <?php
  2.  
  3. require_once('/home/nginx/lib/scm/scm.php');
  4. require_once(__DIR__ . '/../../app/Mage.php');
  5. require_once('/home/nginx/lib/script_utils.php');
  6.  
  7. error_reporting(E_ALL);
  8. ini_set('display_errors', '1');
  9. ini_set("auto_detect_line_endings", true);
  10.  
  11. $margen = 2;
  12. $i = 1;
  13. if (($gestor1 = fopen("/home/nginx/www/proveedores/italjapan/CSV_TIENDAELECTROPOLISSL48784plus.csv", "r")) === FALSE) exit("Error en CSV1");
  14.  
  15. $cabecera = fgetcsv($gestor1,0,',');
  16.  
  17. Mage::app('admin');
  18.  
  19. $idIva21 = obtenerIdImpuesto('IVA21');
  20. $iditaljapan = obtenerIdOpcionAtributo('proveedor', 'ItalJapan');
  21. $idEntregaEn35Dias = obtenerIdOpcionAtributo('custom_stock_status', 'Entrega en 3 - 5 días');
  22. $idFueraDeExistencia = obtenerIdOpcionAtributo('custom_stock_status', 'Fuera de existencia');
  23. $idTodos = obtenerIdOpcionAtributo('excluir_feed', 'Todos');
  24.  
  25. while (($csv = fgetcsv($gestor1,0,"\t")) !== FALSE)
  26. {
  27. /*    
  28.      0 NO SE USA
  29.      1 EAN
  30.      2 MARCA
  31.      3 SKU
  32.      4 DESCRIPCION
  33.      5 IMAGENES
  34.      6 QTY
  35.      8 COSTE
  36.      9 CAT
  37.      11 COLOR DE CORREA
  38.      12 COLOR DIAL
  39.      14 DIAMETRO DE CARCASA
  40.      16 GENERO ( HOMBRE / MUJER
  41.      17 RESISTENTE AL AGUA METROS
  42.      18 ANCHO DE CORREA
  43.      19 LARGO DE CORREA
  44.      20 MATERIAL DE LA CARCASA
  45.      21 MATERIAL DE LA CORREA
  46.      23 PESO DEL RELOJ
  47.      24 GROSOR DE LA CAJA
  48.      25 TIPO DE CALENDARIO
  49.      26 TIPO DE CIERRE HEBILLA
  50.      27 TIPO DE DISPLAY
  51.      28 TIPO DE MOVIMIENTO ( CUARZO / AUTOMATICO )
  52.      29 PIEDRAS PRECIOSAS
  53.      30 TIPO DE CRISTAL
  54. */
  55.  
  56.     $data['sku'] = "IJ-".utf8_encode(strval(trim($csv[3])));
  57.  
  58.     if($csv[8] == 0)
  59.     {
  60.         // El producto no tiene precio, nos lo saltamos
  61.         continue;
  62.     }
  63.  
  64.     $data['marcas'] = $csv[2];
  65.     if($data['marcas'])
  66.     {
  67.         $data['marcas'] = BrandUtil::getNormalizedBrandName($data['marcas']);
  68.     }
  69.    
  70.     $data['ean'] = $csv[1];
  71.     //$data['name'] =." Reloj ".$data['marcas']." ".$data['nombre1-2']" ".$data['nombre2']" correa color: ".$data['nombre3']." Dial: ".$data['nombre4']." ".$data['nombre5']." ".$data['nombre6'];//Nombre producto
  72.     $data['name'] = sprintf('Reloj %s %s %s correa color: %s Dial %s %s %s',$data['marcas'],$data['nombre1-2'],$data['nombre2'],$data['nombre3'],$data['nombre4'],$data['nombre5'],$data['nombre6']);
  73.     $data['name'] = str_replace("Ñ", "ñ", $data["name"]); //Hay problemas con la Ñ
  74.     $data['name'] = str_replace("  "," ",$data['name']);
  75.     $data['description'] = $csv[4];
  76.     $data['description'] = str_replace("  "," ",$data['description']);
  77.     $data['short_description'] = $data['name']." de la marca: ".$data['marcas']." con ean: ".$data['ean'];
  78.     $data['cat'] = str_replace("\n"," > ",trim($csv[9]));
  79.     $data['cat'] = str_replace("/"," > ",$data['cat']);
  80.     $idMarca = BrandUtil::getBrandId($data['marcas']);
  81.     $data['stock'] = $csv[6];
  82.     $data['is_in_stock'] = 1;
  83.     $special_price = getPrecio($data['cost']);
  84.     $price = $special_price*1.5;
  85.     $data['coleccion_reloj'] = $csv[9];
  86.     $data['color_correa'] = $csv[11];
  87.     $data['color_dial'] = $csv[12];
  88.     $data['diametro_caja'] = $csv[14];
  89.     $data['genero_reloj'] = $csv[15];
  90.     $data['resistente_agua'] = $csv[16];
  91.     $data['material_carcasa'] = $csv[19];
  92.  
  93.  
  94.    
  95.     $id = Mage::getResourceSingleton('catalog/product')->getIdBySku($data['sku']);
  96.    
  97.     if(!$id) // INSERTAMOS - NO EXISTE
  98.     {
  99.         //continue;
  100.         $data['status'] = 1; // 2 - desactivado, 1 - activado
  101.         $data['tax_class_id'] = $idIva21;
  102.         $data['visibility'] = 4; // 1 - Not Visible Indivieeedually, 2 - Catalog, 3 - Search, 4 - Catalog, Search
  103.         $data['weight'] = 1;
  104.        
  105.         $data['special_price'] = number_format($special_price, 2);
  106.         $data['precio_marketplace'] = number_format($precio_marketplace, 2);
  107.         $data['price'] = number_format($price, 2);
  108.        
  109.         $product = Mage::getModel('catalog/product');
  110.         $product->setSku($data['sku']);
  111.         $product->setSpecialPrice($data['special_price']);
  112.         $product->setPrice($data['price']);
  113.         $product->setPrecioMarketplace($data['precio_marketplace']);
  114.         $product->setAttributeSetId(4);  //4 es la Default
  115.         $product->setTypeId('simple');
  116.         $product->setName($data['name']);
  117.         $product->setDescription($data['description']);
  118.         $product->setShortDescription($data['short_description']);
  119.         $product->setStatus($data['status']); // 2 - desactivado, 1 - activado
  120.         $product->setCustomStockStatusQtyBased(1);
  121.         $product->setHideDefaultStockStatus(0);
  122.         $product->setProveedor($iditaljapan);
  123.         $product->setTaxClassId($data['tax_class_id']);
  124.         $product->setVisibility($data['visibility']); // 1 - Not Visible Individually, 2 - Catalog, 3 - Search, 4 - Catalog, Search
  125.         $product->setWeight($data['weight']);
  126.         $product->setCreatedAt(date('Y-m-d H:i:s'));
  127.         $product->setWebsiteIds(array(1));
  128.         $product->setCat($data["cat"]);
  129.         $product->setMarcas($idMarca);
  130.         $product->setCustomStockStatus($idEntregaEn35Dias);
  131.         //$product->setExcluirFeed($idTodos); //Todos
  132.        
  133.         //IMAGENES
  134.        
  135.         $images = explode(",",$csv[5]);
  136.  
  137.         $mediaAttribute = array (
  138.                 'image',
  139.                 'thumbnail',
  140.                 'small_image'                  
  141.             );
  142.         $contaImage = 0;   
  143.            
  144.         foreach($images as $image)
  145.         {
  146.             $rfullpath = $image;
  147.            
  148.             if(!substr_count($rfullpath, 'http')) continue;
  149.            
  150.             $fullpath = '/tmp/'.basename($rfullpath);
  151.            
  152.             $rfullpath = str_replace(' ', '%20', $rfullpath);
  153.             $rfullpath = rtrim($rfullpath, '%20');
  154.                
  155.             $meta_title = $data['name']; //titulo de las imagenes
  156.             $rimagen = file_get_contents($rfullpath);
  157.             file_put_contents($fullpath, $rimagen);
  158.            
  159.             try {
  160.                 if($contaImage == 0){
  161.                     $product->addImageToMediaGallery($fullpath ,$mediaAttribute, false, false);
  162.                 }else{
  163.                     $product->addImageToMediaGallery($fullpath ,null, false, false);
  164.                 }
  165.                 $contaImage++;
  166.             } catch (Exception $e) {
  167.                 //echo " FAIL imagen $i $rfullpath\n";
  168.                 file_put_contents('fallos.txt', $data['sku']." imagen $i $rfullpath\n", FILE_APPEND | LOCK_EX);
  169.             }
  170.         }
  171.  
  172.        
  173.         //Stock    
  174.         $stockData = [];
  175.         $stockData['manage_stock'] = 1; //manejar el stock
  176.         $stockData['use_config_manage_stock'] = 1; //usar configuracion global de manage stock
  177.         $stockData['qty'] = $data['stock'];
  178.         $stockData['is_in_stock'] = $data['is_in_stock'];
  179.        
  180.         $product->setStockData($stockData);
  181.        
  182.         //metemos todo en la categoria root electropolis
  183.         $categorias[] = 2;
  184.         $product->setCategoryIds($categorias);
  185.         //creamos array e insertamos(esto es para cetegorizar en nuestra web cuando tenemos los ids pre-establecidos)
  186.         /*$categorias = array();
  187.         $categoriaFinal = trim($csv[3]);
  188.         if(isset($categoriaFinal) && $categoriaFinal != ''){
  189.             $category = Mage::getModel('catalog/category')->load($categoriaFinal);
  190.  
  191.             foreach ($category->getParentCategories() as $parent) {
  192.                 $categorias[] = $parent->getId();
  193.             }
  194.             $categorias[] = $categoriaFinal;
  195.         }else{
  196.             $categorias[] = 2;
  197.             $categorias[] = 59856; //Id repuestos padre
  198.         }
  199.         $product->setCategoryIds($categorias);
  200.         */
  201.         $product->setC2cEan($data['ean']);
  202.         createOrAssignId('proveedor', 'ItalJapan', $product);
  203.          
  204.         try {
  205.             //$product->save($product);
  206.             ScmProvider::get('ItalJapan')->notifyNewProduct($product);
  207.             $product->save();
  208.             echo $data['sku']." OK (".$i++.") \n";
  209.             //exit();
  210.  
  211.         } catch (Exception $e) {
  212.             echo $data['sku']." FAIL (".$i++.") ".$e->getMessage()."\n";
  213.             file_put_contents('fallos.txt', $data['sku']." -> ".$e->getMessage()."\n", FILE_APPEND | LOCK_EX);
  214.        
  215.         }
  216.         //die;
  217.         //ACTUALIZAMOS
  218.     }
  219.     else
  220.     {
  221.        
  222.         $productoMagento = Mage::getModel('catalog/product')->getCollection()
  223.             ->addAttributeToSelect([
  224.                 'sku', 'name', 'name2', 'description', 'description_en', 'type_id', 'proveedor', 'c2c_ean', 'cat',
  225.                 'short_description', 'custom_stock_status', 'cost', 'price', 'special_price', 'tax_class_id', 'marcas',
  226.                 'hide_default_stock_status', 'cod_fabricante','precio_marketplace'], 'left')
  227.             ->joinField('qty',
  228.                         'cataloginventory/stock_item',
  229.                         'qty',
  230.                         'product_id=entity_id',
  231.                         '{{table}}.stock_id=1',
  232.                         'left')
  233.             ->addAttributeToFilter([['attribute' => 'entity_id', 'eq' => $id]])
  234.             ->getSelect()
  235.             ->query()
  236.             ->fetch();
  237.            
  238.         $modificaciones = array();
  239.        
  240.         /*$catids = array();
  241.         $categoriaFinal = trim($csv[3]);
  242.         if(isset($categoriaFinal) && $categoriaFinal != ''){
  243.             $category = Mage::getModel('catalog/category')->load($categoriaFinal);
  244.  
  245.             $catnames = array();
  246.             foreach ($category->getParentCategories() as $parent) {
  247.                 $catids[] = $parent->getId();
  248.             }
  249.             $product = Mage::getModel('catalog/product')->load($id);
  250.             $product->setCategoryIds($catids);
  251.             $product->save();
  252.         }*/
  253.        
  254.         //if($productoMagento["proveedor"] != $idSuelme) continue;
  255.         if($productoMagento["proveedor"] != $iditaljapan){
  256.             $modificaciones["proveedor"] = $iditaljapan;
  257.         }
  258.  
  259.         if($productoMagento["type_id"] != 'simple') continue;
  260.        
  261.         if($productoMagento["hide_default_stock_status"] != 0){
  262.             $modificaciones["hide_default_stock_status"] = 0;
  263.         }
  264.        
  265.         if($productoMagento["special_price"] != $special_price){
  266.             $modificaciones["special_price"] = $special_price;
  267.         }
  268.        
  269.         if($productoMagento["precio_marketplace"] != $precio_marketplace){
  270.             $modificaciones["precio_marketplace"] = $precio_marketplace;
  271.         }
  272.        
  273.         if($productoMagento["price"] != $price){
  274.             $modificaciones["price"] = $price;
  275.         }
  276.        
  277.         if(strlen($data['ean'])==13){
  278.             if($productoMagento["c2c_ean"] != $data["ean"]){
  279.                 $modificaciones["c2c_ean"] = $data["ean"];
  280.             }
  281.         }
  282.        
  283.         if($productoMagento["description"] == ""){ //No hay desc. en epolis pero si en ItalJapan
  284.             if($data["description"] != ""){
  285.                 $modificaciones["description"] = $data["description"];
  286.             }
  287.         }
  288.        
  289.         if($productoMagento["short_description"] == ""){ //No hay short_desc. en epolis pero si en ItalJapan
  290.             if($data["short_description"] != ""){
  291.                 $modificaciones["short_description"] = $data["short_description"];
  292.             }
  293.         }
  294.        
  295.         if($productoMagento["cat"] == ""){ //No hay desc. en epolis pero si en ItalJapan
  296.             if($data["cat"] != ""){
  297.                 $modificaciones["cat"] = $data["cat"];
  298.             }
  299.         }
  300.        
  301.         //Comprobamos si su fabricante es correcto
  302.         if($productoMagento["marcas"] != $idMarca){
  303.             $modificaciones["marcas"] = $idMarca;
  304.         }
  305.        
  306.         echo $data['sku']." OK (".$i++.") \n";
  307.  
  308.         if(count($modificaciones) > 0)    
  309.         {
  310.             echo '> Los atributos han sido modificados' . PHP_EOL;
  311.             foreach($modificaciones as $key => $value)
  312.             {
  313.                 echo sprintf('>> %s => %s', $key, $value) . PHP_EOL;
  314.             }
  315.             try{
  316.                 Mage::getSingleton('catalog/product_action')->updateAttributes([$id],$modificaciones,0);
  317.                 ScmProvider::get('ItalJapan')->notifyProductDataChanges($productoMagento["sku"], $modificaciones);
  318.             }catch(Exception $e){
  319.                 echo $data['sku']." FAIL (".$i."): ".$e->getMessage()."\n";
  320.                 file_put_contents('fallos.txt', $data['sku']."\n", FILE_APPEND | LOCK_EX);
  321.             }
  322.         }
  323.        
  324.         if($productoMagento["qty"] != $data['stock']){
  325.  
  326.             $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($id);
  327.  
  328.             if($stockItem->isObjectNew())
  329.             {
  330.                 // No existe el StockItem, lo creamos nuevo
  331.                 $stockData = $product->getStockData();
  332.                 $stockData['manage_stock'] = 1; //manejar el stock
  333.                 $stockData['use_config_manage_stock'] = 1; //usar configuracion global de manage stock
  334.                 $stockData['qty'] = $data['stock'];
  335.                 $stockData['is_in_stock'] = $data['is_in_stock'];
  336.                 $product->setStockData($stockData);
  337.                 $product->save();
  338.                 ScmProvider::get('italjapan')->notifyStockChange($productoMagento['sku'], $stockItem['qty']);
  339.             }
  340.             else
  341.             {
  342.                 // Ya existe el StockItem, lo actualizamos
  343.                 $stockItem->setData('qty', $data['stock']);
  344.                 $stockItem->setData('is_in_stock', $data['is_in_stock']);
  345.                 $stockItem->save();
  346.                 ScmProvider::get('italjapan')->notifyStockChange($productoMagento['sku'], $stockItem['qty']);
  347.             }
  348.         }
  349.         //die;
  350.         //exit();
  351.     }
  352. }
  353.  
  354. file_put_contents('/home/nginx/www/proveedores/ItalJapan/completado.txt', "Relojes.php completado a fecha ".date('d/m/Y H:i:s')."\n", FILE_APPEND | LOCK_EX);
  355.  
  356. function getPrecio($p)
  357. {
  358.     if($p > 0 && $p <= 3) return $p*3;
  359.     elseif($p > 3 && $p <= 6) return $p*2.2;
  360.     elseif($p > 6 && $p <= 10) return $p*2.1;
  361.     elseif($p > 10 && $p <= 20) return $p*2;
  362.     elseif($p > 20 && $p <= 50) return $p*1.8;
  363.     elseif($p > 50 && $p <= 100) return $p*1.6;
  364.     elseif($p > 100 && $p <= 300) return $p*1.5;
  365.     elseif($p > 300 && $p <= 600) return $p*1.4;
  366.     elseif($p > 600) return $p*1.35;
  367.     else return 10000;
  368. }
  369.  
  370. function createOrAssignId($string, $value, $product)
  371.     {
  372.     //  echo $string.'-'.$value;
  373.     $variable_id = attributeValueExists($string, $value);
  374.    
  375.     if(!$variable_id && $value != NULL)
  376.     {
  377.     //TODO
  378.     /*
  379.     PONER COMPROBACIÓN CON IF
  380.     */
  381.     try{
  382.         $variable_id = addAttributeValue($string, $value);
  383.     }
  384.     catch(PDOException $e)
  385.     {
  386.     }
  387.     }
  388.     $variable_id = attributeValueExists($string, $value);
  389.     $func ='set'.to_camel_case($string);
  390.     $product->$func($variable_id);
  391.     }
  392.    
  393.     function createOrGetId($string, $value)
  394.     {
  395.     //  echo $string.'-'.$value;
  396.     $variable_id = attributeValueExists($string, $value);
  397.    
  398.     if(!$variable_id && $value != NULL)
  399.     {
  400.     //TODO
  401.     /*
  402.     PONER COMPROBACIÓN CON IF
  403.     */
  404.     try{
  405.         $variable_id = addAttributeValue($string, $value);
  406.     }
  407.     catch(PDOException $e)
  408.     {
  409.     }
  410.     }
  411.     $variable_id = attributeValueExists($string, $value);
  412.  
  413.     return $variable_id;
  414.     }
  415.  
  416.     function attributeValueExists($arg_attribute, $arg_value)
  417.     {
  418.         $attribute_model        = Mage::getModel('eav/entity_attribute');
  419.         $attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
  420.  
  421.         $attribute_code         = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
  422.         $attribute              = $attribute_model->load($attribute_code);
  423.        
  424.         $attribute_table        = $attribute_options_model->setAttribute($attribute);
  425.         $options                = $attribute_options_model->getAllOptions(false);
  426.        
  427.         foreach($options as $option)
  428.         {
  429.             if ($option['label'] == $arg_value)
  430.             {
  431.                 return $option['value'];
  432.             }
  433.         }
  434.        
  435.         return false;
  436.     }
  437.    
  438.     function addAttributeValue($arg_attribute, $arg_value)
  439.     {
  440.         $attribute_model        = Mage::getModel('eav/entity_attribute');
  441.         $attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
  442.  
  443.         $attribute_code         = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
  444.         $attribute              = $attribute_model->load($attribute_code);
  445.        
  446.         $attribute_table        = $attribute_options_model->setAttribute($attribute);
  447.         $options                = $attribute_options_model->getAllOptions(false);
  448.        
  449.         if(!attributeValueExists($arg_attribute, $arg_value))
  450.         {
  451.             $value['option'] = array($arg_value,$arg_value);
  452.             $result = array('value' => $value);
  453.             $attribute->setData('option',$result);
  454.             $attribute->save();
  455.         }
  456.        
  457.         foreach($options as $option)
  458.         {
  459.             if ($option['label'] == $arg_value)
  460.             {
  461.                 return $option['value'];
  462.             }
  463.         }
  464.         return true;
  465.     }
  466.    
  467.     function getAttributeValue($arg_attribute, $arg_option_id)
  468.     {
  469.         $attribute_model        = Mage::getModel('eav/entity_attribute');
  470.         $attribute_table        = Mage::getModel('eav/entity_attribute_source_table');
  471.        
  472.         $attribute_code         = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
  473.         $attribute              = $attribute_model->load($attribute_code);
  474.        
  475.                                   $attribute_table->setAttribute($attribute);
  476.                                  
  477.         $option                 = $attribute_table->getOptionText($arg_option_id);
  478.        
  479.         return $option;
  480.     }
  481.    
  482.     function to_camel_case($str, $capitalise_first_char = true) {
  483.     if($capitalise_first_char) {
  484.         $str[2] = strtoupper($str[0]);
  485.     }
  486.     $func = create_function('$c', 'return strtoupper($c[1]);');
  487.     return preg_replace_callback('/_([a-z])/', $func, $str);
  488.     }
  489.  
  490. function stringToStream($string)
  491. {
  492.     $stream = fopen('php://memory', 'r+');
  493.     fwrite($stream, $string);
  494.     rewind($stream);
  495.     return $stream;
  496. }
  497.  
  498. function UR_exists($url){
  499.    $headers=get_headers($url);
  500.    return stripos($headers[0],"200 OK")?true:false;
  501. }
  502.  
  503. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement