Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- require_once('/home/nginx/lib/scm/scm.php');
- require_once(__DIR__ . '/../../app/Mage.php');
- require_once('/home/nginx/lib/script_utils.php');
- error_reporting(E_ALL);
- ini_set('display_errors', '1');
- ini_set("auto_detect_line_endings", true);
- $margen = 2;
- $i = 1;
- if (($gestor1 = fopen("/home/nginx/www/proveedores/italjapan/CSV_TIENDAELECTROPOLISSL48784plus.csv", "r")) === FALSE) exit("Error en CSV1");
- $cabecera = fgetcsv($gestor1,0,',');
- Mage::app('admin');
- $idIva21 = obtenerIdImpuesto('IVA21');
- $iditaljapan = obtenerIdOpcionAtributo('proveedor', 'ItalJapan');
- $idEntregaEn35Dias = obtenerIdOpcionAtributo('custom_stock_status', 'Entrega en 3 - 5 días');
- $idFueraDeExistencia = obtenerIdOpcionAtributo('custom_stock_status', 'Fuera de existencia');
- $idTodos = obtenerIdOpcionAtributo('excluir_feed', 'Todos');
- while (($csv = fgetcsv($gestor1,0,"\t")) !== FALSE)
- {
- /*
- 0 NO SE USA
- 1 EAN
- 2 MARCA
- 3 SKU
- 4 DESCRIPCION
- 5 IMAGENES
- 6 QTY
- 8 COSTE
- 9 CAT
- 11 COLOR DE CORREA
- 12 COLOR DIAL
- 14 DIAMETRO DE CARCASA
- 16 GENERO ( HOMBRE / MUJER
- 17 RESISTENTE AL AGUA METROS
- 18 ANCHO DE CORREA
- 19 LARGO DE CORREA
- 20 MATERIAL DE LA CARCASA
- 21 MATERIAL DE LA CORREA
- 23 PESO DEL RELOJ
- 24 GROSOR DE LA CAJA
- 25 TIPO DE CALENDARIO
- 26 TIPO DE CIERRE HEBILLA
- 27 TIPO DE DISPLAY
- 28 TIPO DE MOVIMIENTO ( CUARZO / AUTOMATICO )
- 29 PIEDRAS PRECIOSAS
- 30 TIPO DE CRISTAL
- */
- $data['sku'] = "IJ-".utf8_encode(strval(trim($csv[3])));
- if($csv[8] == 0)
- {
- // El producto no tiene precio, nos lo saltamos
- continue;
- }
- $data['marcas'] = $csv[2];
- if($data['marcas'])
- {
- $data['marcas'] = BrandUtil::getNormalizedBrandName($data['marcas']);
- }
- $data['ean'] = $csv[1];
- //$data['name'] =." Reloj ".$data['marcas']." ".$data['nombre1-2']" ".$data['nombre2']" correa color: ".$data['nombre3']." Dial: ".$data['nombre4']." ".$data['nombre5']." ".$data['nombre6'];//Nombre producto
- $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']);
- $data['name'] = str_replace("Ñ", "ñ", $data["name"]); //Hay problemas con la Ñ
- $data['name'] = str_replace(" "," ",$data['name']);
- $data['description'] = $csv[4];
- $data['description'] = str_replace(" "," ",$data['description']);
- $data['short_description'] = $data['name']." de la marca: ".$data['marcas']." con ean: ".$data['ean'];
- $data['cat'] = str_replace("\n"," > ",trim($csv[9]));
- $data['cat'] = str_replace("/"," > ",$data['cat']);
- $idMarca = BrandUtil::getBrandId($data['marcas']);
- $data['stock'] = $csv[6];
- $data['is_in_stock'] = 1;
- $special_price = getPrecio($data['cost']);
- $price = $special_price*1.5;
- $data['coleccion_reloj'] = $csv[9];
- $data['color_correa'] = $csv[11];
- $data['color_dial'] = $csv[12];
- $data['diametro_caja'] = $csv[14];
- $data['genero_reloj'] = $csv[15];
- $data['resistente_agua'] = $csv[16];
- $data['material_carcasa'] = $csv[19];
- $id = Mage::getResourceSingleton('catalog/product')->getIdBySku($data['sku']);
- if(!$id) // INSERTAMOS - NO EXISTE
- {
- //continue;
- $data['status'] = 1; // 2 - desactivado, 1 - activado
- $data['tax_class_id'] = $idIva21;
- $data['visibility'] = 4; // 1 - Not Visible Indivieeedually, 2 - Catalog, 3 - Search, 4 - Catalog, Search
- $data['weight'] = 1;
- $data['special_price'] = number_format($special_price, 2);
- $data['precio_marketplace'] = number_format($precio_marketplace, 2);
- $data['price'] = number_format($price, 2);
- $product = Mage::getModel('catalog/product');
- $product->setSku($data['sku']);
- $product->setSpecialPrice($data['special_price']);
- $product->setPrice($data['price']);
- $product->setPrecioMarketplace($data['precio_marketplace']);
- $product->setAttributeSetId(4); //4 es la Default
- $product->setTypeId('simple');
- $product->setName($data['name']);
- $product->setDescription($data['description']);
- $product->setShortDescription($data['short_description']);
- $product->setStatus($data['status']); // 2 - desactivado, 1 - activado
- $product->setCustomStockStatusQtyBased(1);
- $product->setHideDefaultStockStatus(0);
- $product->setProveedor($iditaljapan);
- $product->setTaxClassId($data['tax_class_id']);
- $product->setVisibility($data['visibility']); // 1 - Not Visible Individually, 2 - Catalog, 3 - Search, 4 - Catalog, Search
- $product->setWeight($data['weight']);
- $product->setCreatedAt(date('Y-m-d H:i:s'));
- $product->setWebsiteIds(array(1));
- $product->setCat($data["cat"]);
- $product->setMarcas($idMarca);
- $product->setCustomStockStatus($idEntregaEn35Dias);
- //$product->setExcluirFeed($idTodos); //Todos
- //IMAGENES
- $images = explode(",",$csv[5]);
- $mediaAttribute = array (
- 'image',
- 'thumbnail',
- 'small_image'
- );
- $contaImage = 0;
- foreach($images as $image)
- {
- $rfullpath = $image;
- if(!substr_count($rfullpath, 'http')) continue;
- $fullpath = '/tmp/'.basename($rfullpath);
- $rfullpath = str_replace(' ', '%20', $rfullpath);
- $rfullpath = rtrim($rfullpath, '%20');
- $meta_title = $data['name']; //titulo de las imagenes
- $rimagen = file_get_contents($rfullpath);
- file_put_contents($fullpath, $rimagen);
- try {
- if($contaImage == 0){
- $product->addImageToMediaGallery($fullpath ,$mediaAttribute, false, false);
- }else{
- $product->addImageToMediaGallery($fullpath ,null, false, false);
- }
- $contaImage++;
- } catch (Exception $e) {
- //echo " FAIL imagen $i $rfullpath\n";
- file_put_contents('fallos.txt', $data['sku']." imagen $i $rfullpath\n", FILE_APPEND | LOCK_EX);
- }
- }
- //Stock
- $stockData = [];
- $stockData['manage_stock'] = 1; //manejar el stock
- $stockData['use_config_manage_stock'] = 1; //usar configuracion global de manage stock
- $stockData['qty'] = $data['stock'];
- $stockData['is_in_stock'] = $data['is_in_stock'];
- $product->setStockData($stockData);
- //metemos todo en la categoria root electropolis
- $categorias[] = 2;
- $product->setCategoryIds($categorias);
- //creamos array e insertamos(esto es para cetegorizar en nuestra web cuando tenemos los ids pre-establecidos)
- /*$categorias = array();
- $categoriaFinal = trim($csv[3]);
- if(isset($categoriaFinal) && $categoriaFinal != ''){
- $category = Mage::getModel('catalog/category')->load($categoriaFinal);
- foreach ($category->getParentCategories() as $parent) {
- $categorias[] = $parent->getId();
- }
- $categorias[] = $categoriaFinal;
- }else{
- $categorias[] = 2;
- $categorias[] = 59856; //Id repuestos padre
- }
- $product->setCategoryIds($categorias);
- */
- $product->setC2cEan($data['ean']);
- createOrAssignId('proveedor', 'ItalJapan', $product);
- try {
- //$product->save($product);
- ScmProvider::get('ItalJapan')->notifyNewProduct($product);
- $product->save();
- echo $data['sku']." OK (".$i++.") \n";
- //exit();
- } catch (Exception $e) {
- echo $data['sku']." FAIL (".$i++.") ".$e->getMessage()."\n";
- file_put_contents('fallos.txt', $data['sku']." -> ".$e->getMessage()."\n", FILE_APPEND | LOCK_EX);
- }
- //die;
- //ACTUALIZAMOS
- }
- else
- {
- $productoMagento = Mage::getModel('catalog/product')->getCollection()
- ->addAttributeToSelect([
- 'sku', 'name', 'name2', 'description', 'description_en', 'type_id', 'proveedor', 'c2c_ean', 'cat',
- 'short_description', 'custom_stock_status', 'cost', 'price', 'special_price', 'tax_class_id', 'marcas',
- 'hide_default_stock_status', 'cod_fabricante','precio_marketplace'], 'left')
- ->joinField('qty',
- 'cataloginventory/stock_item',
- 'qty',
- 'product_id=entity_id',
- '{{table}}.stock_id=1',
- 'left')
- ->addAttributeToFilter([['attribute' => 'entity_id', 'eq' => $id]])
- ->getSelect()
- ->query()
- ->fetch();
- $modificaciones = array();
- /*$catids = array();
- $categoriaFinal = trim($csv[3]);
- if(isset($categoriaFinal) && $categoriaFinal != ''){
- $category = Mage::getModel('catalog/category')->load($categoriaFinal);
- $catnames = array();
- foreach ($category->getParentCategories() as $parent) {
- $catids[] = $parent->getId();
- }
- $product = Mage::getModel('catalog/product')->load($id);
- $product->setCategoryIds($catids);
- $product->save();
- }*/
- //if($productoMagento["proveedor"] != $idSuelme) continue;
- if($productoMagento["proveedor"] != $iditaljapan){
- $modificaciones["proveedor"] = $iditaljapan;
- }
- if($productoMagento["type_id"] != 'simple') continue;
- if($productoMagento["hide_default_stock_status"] != 0){
- $modificaciones["hide_default_stock_status"] = 0;
- }
- if($productoMagento["special_price"] != $special_price){
- $modificaciones["special_price"] = $special_price;
- }
- if($productoMagento["precio_marketplace"] != $precio_marketplace){
- $modificaciones["precio_marketplace"] = $precio_marketplace;
- }
- if($productoMagento["price"] != $price){
- $modificaciones["price"] = $price;
- }
- if(strlen($data['ean'])==13){
- if($productoMagento["c2c_ean"] != $data["ean"]){
- $modificaciones["c2c_ean"] = $data["ean"];
- }
- }
- if($productoMagento["description"] == ""){ //No hay desc. en epolis pero si en ItalJapan
- if($data["description"] != ""){
- $modificaciones["description"] = $data["description"];
- }
- }
- if($productoMagento["short_description"] == ""){ //No hay short_desc. en epolis pero si en ItalJapan
- if($data["short_description"] != ""){
- $modificaciones["short_description"] = $data["short_description"];
- }
- }
- if($productoMagento["cat"] == ""){ //No hay desc. en epolis pero si en ItalJapan
- if($data["cat"] != ""){
- $modificaciones["cat"] = $data["cat"];
- }
- }
- //Comprobamos si su fabricante es correcto
- if($productoMagento["marcas"] != $idMarca){
- $modificaciones["marcas"] = $idMarca;
- }
- echo $data['sku']." OK (".$i++.") \n";
- if(count($modificaciones) > 0)
- {
- echo '> Los atributos han sido modificados' . PHP_EOL;
- foreach($modificaciones as $key => $value)
- {
- echo sprintf('>> %s => %s', $key, $value) . PHP_EOL;
- }
- try{
- Mage::getSingleton('catalog/product_action')->updateAttributes([$id],$modificaciones,0);
- ScmProvider::get('ItalJapan')->notifyProductDataChanges($productoMagento["sku"], $modificaciones);
- }catch(Exception $e){
- echo $data['sku']." FAIL (".$i."): ".$e->getMessage()."\n";
- file_put_contents('fallos.txt', $data['sku']."\n", FILE_APPEND | LOCK_EX);
- }
- }
- if($productoMagento["qty"] != $data['stock']){
- $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($id);
- if($stockItem->isObjectNew())
- {
- // No existe el StockItem, lo creamos nuevo
- $stockData = $product->getStockData();
- $stockData['manage_stock'] = 1; //manejar el stock
- $stockData['use_config_manage_stock'] = 1; //usar configuracion global de manage stock
- $stockData['qty'] = $data['stock'];
- $stockData['is_in_stock'] = $data['is_in_stock'];
- $product->setStockData($stockData);
- $product->save();
- ScmProvider::get('italjapan')->notifyStockChange($productoMagento['sku'], $stockItem['qty']);
- }
- else
- {
- // Ya existe el StockItem, lo actualizamos
- $stockItem->setData('qty', $data['stock']);
- $stockItem->setData('is_in_stock', $data['is_in_stock']);
- $stockItem->save();
- ScmProvider::get('italjapan')->notifyStockChange($productoMagento['sku'], $stockItem['qty']);
- }
- }
- //die;
- //exit();
- }
- }
- 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);
- function getPrecio($p)
- {
- if($p > 0 && $p <= 3) return $p*3;
- elseif($p > 3 && $p <= 6) return $p*2.2;
- elseif($p > 6 && $p <= 10) return $p*2.1;
- elseif($p > 10 && $p <= 20) return $p*2;
- elseif($p > 20 && $p <= 50) return $p*1.8;
- elseif($p > 50 && $p <= 100) return $p*1.6;
- elseif($p > 100 && $p <= 300) return $p*1.5;
- elseif($p > 300 && $p <= 600) return $p*1.4;
- elseif($p > 600) return $p*1.35;
- else return 10000;
- }
- function createOrAssignId($string, $value, $product)
- {
- // echo $string.'-'.$value;
- $variable_id = attributeValueExists($string, $value);
- if(!$variable_id && $value != NULL)
- {
- //TODO
- /*
- PONER COMPROBACIÓN CON IF
- */
- try{
- $variable_id = addAttributeValue($string, $value);
- }
- catch(PDOException $e)
- {
- }
- }
- $variable_id = attributeValueExists($string, $value);
- $func ='set'.to_camel_case($string);
- $product->$func($variable_id);
- }
- function createOrGetId($string, $value)
- {
- // echo $string.'-'.$value;
- $variable_id = attributeValueExists($string, $value);
- if(!$variable_id && $value != NULL)
- {
- //TODO
- /*
- PONER COMPROBACIÓN CON IF
- */
- try{
- $variable_id = addAttributeValue($string, $value);
- }
- catch(PDOException $e)
- {
- }
- }
- $variable_id = attributeValueExists($string, $value);
- return $variable_id;
- }
- function attributeValueExists($arg_attribute, $arg_value)
- {
- $attribute_model = Mage::getModel('eav/entity_attribute');
- $attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
- $attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
- $attribute = $attribute_model->load($attribute_code);
- $attribute_table = $attribute_options_model->setAttribute($attribute);
- $options = $attribute_options_model->getAllOptions(false);
- foreach($options as $option)
- {
- if ($option['label'] == $arg_value)
- {
- return $option['value'];
- }
- }
- return false;
- }
- function addAttributeValue($arg_attribute, $arg_value)
- {
- $attribute_model = Mage::getModel('eav/entity_attribute');
- $attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
- $attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
- $attribute = $attribute_model->load($attribute_code);
- $attribute_table = $attribute_options_model->setAttribute($attribute);
- $options = $attribute_options_model->getAllOptions(false);
- if(!attributeValueExists($arg_attribute, $arg_value))
- {
- $value['option'] = array($arg_value,$arg_value);
- $result = array('value' => $value);
- $attribute->setData('option',$result);
- $attribute->save();
- }
- foreach($options as $option)
- {
- if ($option['label'] == $arg_value)
- {
- return $option['value'];
- }
- }
- return true;
- }
- function getAttributeValue($arg_attribute, $arg_option_id)
- {
- $attribute_model = Mage::getModel('eav/entity_attribute');
- $attribute_table = Mage::getModel('eav/entity_attribute_source_table');
- $attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
- $attribute = $attribute_model->load($attribute_code);
- $attribute_table->setAttribute($attribute);
- $option = $attribute_table->getOptionText($arg_option_id);
- return $option;
- }
- function to_camel_case($str, $capitalise_first_char = true) {
- if($capitalise_first_char) {
- $str[2] = strtoupper($str[0]);
- }
- $func = create_function('$c', 'return strtoupper($c[1]);');
- return preg_replace_callback('/_([a-z])/', $func, $str);
- }
- function stringToStream($string)
- {
- $stream = fopen('php://memory', 'r+');
- fwrite($stream, $string);
- rewind($stream);
- return $stream;
- }
- function UR_exists($url){
- $headers=get_headers($url);
- return stripos($headers[0],"200 OK")?true:false;
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement