Senza categoria

Aggiornamento EdiSES prodotti/categorie

Prima di tutto si esegue l’import sulla macchina virtuale 192.168.220.136/wordpress, a lei è demandato il compito di gestire l’import fin dal giorno 0.

Va copiata la tabella catalog_product_entity sul database edises_import
Si esporta il file csv tramite url: http://192.168.220.136/wordpress/export-attr.php
Si importa il file su un database a caso online, di seguito la stuttura di default in base all’esportazione (potrebbe variare)

I prodotti vanno esportati con l’ultimo template, poi si fa girare uno script che modifica il file csv e si carica quello perché contiene già colonne extra.

Bisogna esportare le categorie WooCommerce, solo dopo fare l’import dei prodotti, prendere CAT-3 come riferimento, va modificato anche woo-custom-menu-link.php come segue

// Aggiungi il campo personalizzato al form di modifica della categoria
add_action('product_cat_edit_form_fields', 'aggiungi_campo_personalizzato_categoria');

function aggiungi_campo_personalizzato_categoria($term) {
    ?>
    <tr class="form-field">
        <th scope="row" valign="top"><label for="_id_categoria_magento">ID Categoria Magento</label></th>
        <td>
            <input type="text" name="_id_categoria_magento" id="_id_categoria_magento" value="<?php echo get_term_meta($term->term_id, '_id_categoria_magento', true ); ?>">
            <p class="description">Inserisci qui l'ID Categoria Magento.</p>
        </td>
    </tr>
    <?php
}

// Salva il valore del campo personalizzato quando si modifica la categoria
add_action('edited_product_cat', 'salva_campo_personalizzato_categoria');

function salva_campo_personalizzato_categoria($term_id) {
    if (isset($_POST['_id_categoria_magento'])) {
        update_term_meta($term_id, '_id_categoria_magento', sanitize_text_field($_POST['_id_categoria_magento']));
    }
}


// Aggiungi il campo personalizzato al form di modifica della categoria
add_action('product_cat_edit_form_fields', 'aggiungi_campo_personalizzato_categoria_woocommerce');

function aggiungi_campo_personalizzato_categoria_woocommerce($term) {
    ?>
    <tr class="form-field">
        <th scope="row" valign="top"><label for="_id_categoria_woocommerce">ID Categoria WooCommerce</label></th>
        <td>
            <input type="text" name="_id_categoria_woocommerce" id="_id_categoria_woocommerce" value="<?php echo get_term_meta($term->term_id, '_id_categoria_woocommerce', true ); ?>">
            <p class="description">Inserisci qui l'ID Categoria WooCommerce.</p>
        </td>
    </tr>
    <?php
}

// Salva il valore del campo personalizzato quando si modifica la categoria
add_action('edited_product_cat', 'salva_campo_personalizzato_categoria_woocommerce');

function salva_campo_personalizzato_categoria_woocommerce($term_id) {
    if (isset($_POST['_id_categoria_woocommerce'])) {
        update_term_meta($term_id, '_id_categoria_woocommerce', sanitize_text_field($_POST['_id_categoria_woocommerce']));
    }
}

CREATE TABLE `magento_export_beta` (
  `id_prodotto` varchar(255) DEFAULT NULL,
  `nome_prodotto` varchar(255) DEFAULT NULL,
  `slug_prodotto` varchar(255) DEFAULT NULL,
  `MAGENTO_ID` varchar(20) DEFAULT NULL,
  `Autori` longtext,
  `Indice` text,
  `pa_has_cd` varchar(255) DEFAULT NULL,
  `pa_has_gift` varchar(255) DEFAULT NULL,
  `Estensioni_Web` text,
  `Autore` varchar(255) DEFAULT NULL,
  `Isbn` varchar(50) DEFAULT NULL,
  `pa_is_ebook` varchar(255) DEFAULT NULL,
  `pa_edizione` varchar(50) DEFAULT NULL,
  `Numero_pagine` varchar(255) DEFAULT NULL,
  `pa_stampa` varchar(50) DEFAULT NULL,
  `pa_is_novita` varchar(255) DEFAULT NULL,
  `pa_sfoglia_volume` varchar(255) DEFAULT NULL,
  `pa_is_disponible` varchar(255) DEFAULT NULL,
  `pa_is_prenotabile` varchar(255) DEFAULT NULL,
  `Ricerca_Ebook` text,
  `pa_has_software` varchar(255) DEFAULT NULL,
  `Sottotitolo` varchar(255) DEFAULT NULL,
  `pa_manuale_compet_sost_anief` varchar(255) DEFAULT NULL,
  `pa_eb_eserc_sost_anief` varchar(255) DEFAULT NULL,
  `pa_in_evidenza` varchar(255) DEFAULT NULL,
  `pa_nopromo` varchar(255) DEFAULT NULL,
  `pa_coupon` varchar(255) DEFAULT NULL,
  `pa_promo20_facebook` varchar(255) DEFAULT NULL,
  `pa_is_vst_ebook` varchar(255) DEFAULT NULL,
  `pa_maestrena` varchar(255) DEFAULT NULL,
  `pa_ripamcoesione` varchar(255) DEFAULT NULL,
  `pa_agenziaentratefb` varchar(255) DEFAULT NULL,
  `pa_man40` varchar(255) DEFAULT NULL,
  `pa_specializzazionimediche` varchar(255) DEFAULT NULL,
  `pa_collanads` varchar(255) DEFAULT NULL,
  `pa_prometheus` varchar(255) DEFAULT NULL,
  `pa_ammissioni` varchar(255) DEFAULT NULL,
  `pa_feedlibrerie` varchar(255) DEFAULT NULL,
  `pa_itastranieri` varchar(255) DEFAULT NULL,
  `pa_mibact` varchar(255) DEFAULT NULL,
  `pa_formato` varchar(50) DEFAULT NULL,
  `pa_scontostanfield` varchar(255) DEFAULT NULL,
  `pa_scontovigili` varchar(255) DEFAULT NULL,
  `pa_in_ebook_search` varchar(255) DEFAULT NULL,
  `pa_has_vst_ppe_ebook` varchar(255) DEFAULT NULL,
  `pa_affiliati_infermieri` varchar(255) DEFAULT NULL,
  `pa_profsanitarielavoro` varchar(255) DEFAULT NULL,
  `pa_infante` varchar(255) DEFAULT NULL,
  `pa_omaggioebook` varchar(255) DEFAULT NULL,
  `pa_kitinfante` varchar(255) DEFAULT NULL,
  `pa_specmedichevito` varchar(255) DEFAULT NULL,
  `pa_cgiltorino` varchar(255) DEFAULT NULL,
  `pa_medprofammissioni` varchar(255) DEFAULT NULL,
  `pa_sconto_aprile_2020` varchar(255) DEFAULT NULL,
  `pa_concorsocattedra100sconto` varchar(255) DEFAULT NULL,
  `pa_verdolina` varchar(255) DEFAULT NULL,
  `pa_codiceds` varchar(255) DEFAULT NULL,
  `pa_sibioc` varchar(255) DEFAULT NULL,
  `pa_escludi_pdf_catalogo` varchar(255) DEFAULT NULL,
  `pa_scontodisal` varchar(255) DEFAULT NULL,
  `pa_disalsingoli` varchar(255) DEFAULT NULL,
  `pa_is_edigita_ebook` varchar(255) DEFAULT NULL,
  `pa_is_edigita_ebook_ppe` varchar(255) DEFAULT NULL,
  `Errata_Corrige` text,
  `pa_url_sistema_verifica` varchar(255) DEFAULT NULL,
  `pa_vst_ppe_resource_id_prefix` varchar(255) DEFAULT NULL,
  `lista_sotto_img` text,
  `URL_ebook` text,
  `ID_Prodotto_nuova_versione` varchar(255) DEFAULT NULL,
  `Data_disponibilita` varchar(255) DEFAULT NULL,
  `Codice_Prodotto` varchar(50) DEFAULT NULL,
  `VST_resource_id_VBID` varchar(255) DEFAULT NULL,
  `Tag` text,
  `URL_cartaceo` text,
  `pa_acs_resource_id` varchar(255) DEFAULT NULL,
  `pa_lingua` varchar(50) DEFAULT NULL,
  `pa_versione` varchar(50) DEFAULT NULL,
  `pa_apple_store` varchar(255) DEFAULT NULL,
  `Brevi_Info` text,
  `pa_dispositivi_supportati` text,
  `Specifiche` text,
  `Struttura` text,
  `pa_demo` varchar(255) DEFAULT NULL,
  `pa_docebo_info` text,
  `pa_elearning` varchar(255) DEFAULT NULL,
  `pa_docebo_course` text,
  `Descrizione_per_widget` text,
  `Country_of_Manufacture` varchar(255) DEFAULT NULL,
  `Edizione` varchar(255) DEFAULT NULL,
  `id_riferimento_Edigita` varchar(255) DEFAULT NULL,
  `pa_market_android` varchar(255) DEFAULT NULL,
  `pa_printable_book_cover_url` text,
  `pa_edigita_ppe_resource_id` varchar(255) DEFAULT NULL,
  `pa_cost` varchar(255) DEFAULT NULL,
  `sottotitolo2` varchar(255) DEFAULT NULL,
  `isbn2` varchar(50) DEFAULT NULL,
  `numero_pagine2` varchar(255) DEFAULT NULL,
  `tag2` text,
  `codice_prodotto2` varchar(50) DEFAULT NULL,
  `ricerca_ebook2` text,
  `pa_simulazione_studenti` varchar(255) DEFAULT NULL,
  `Formato` varchar(50) DEFAULT NULL,
  `pa_ean` varchar(50) DEFAULT NULL,
  `Relatori` text,
  `pa_demo_link` varchar(255) DEFAULT NULL,
  `pa_featured` varchar(255) DEFAULT NULL,
  `pa_nome_landing` varchar(255) DEFAULT NULL,
  `pa_course_plans` text,
  `Programma` text,
  `product_cat` varchar(255) DEFAULT NULL,
  `product_type` varchar(255) DEFAULT NULL,
  `product_visibility` varchar(255) DEFAULT NULL,
  `product_tag` text,
  PRIMARY KEY (`id_prodotto`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Dopo aver importato il csv estratto, va aggiornata la tabella aggiungendo i campi mancanti

ALTER TABLE magento_export_beta
ADD COLUMN `contiene_ebook` varchar(100) NOT NULL AFTER `MAGENTO_ID`,
ADD COLUMN `isbn_ebook` varchar(100) NOT NULL AFTER `contiene_ebook`,
ADD COLUMN `contiene_cartaceo` varchar(100) NOT NULL AFTER `isbn_ebook`,
ADD COLUMN `isbn_cartaceo` longtext NOT NULL AFTER `contiene_cartaceo`,
ADD COLUMN `volume_kit` longtext NOT NULL AFTER `isbn_cartaceo`,
ADD COLUMN `isbn_volume_kit` longtext NOT NULL AFTER `volume_kit`,
ADD COLUMN `serialized_isbn_kit` longtext NOT NULL AFTER `isbn_volume_kit`;


Prima di mettere mano alla tabella definitiva creiamo una di test

CREATE TABLE magento_export_beta_2
SELECT * FROM magento_export_beta

Isoliamo i prodotti già presenti nel database finale rispetto a quelli nell’ambiente di sviluppo, lo facciamo andando ad esportare i valori ISBN e creando due tabelle definite:

CREATE TABLE `prodotti_destinazione` (
  `SKU` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8

CREATE TABLE `prodotti_origine` (
  `SKU` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8

-- da tabella magento_export_beta prendiamo la lista di isbn che caricheremo nella tabella prodotti_origine

SELECT Isbn from magento_export_beta

-- preleviamo anche i prodotti attualmente disponibili su woocommerce

SELECT pm.meta_value AS ISBN
FROM wpcv_postmeta pm
JOIN wpcv_posts p ON pm.post_id = p.ID
WHERE pm.meta_key = 'isbn'
AND p.post_type = 'product'
AND pm.meta_value IS NOT NULL
AND pm.meta_value != '';

-- a questo punto compariamo i risultati ottenuti, la lista di ISBN estratta equivale ai prodotti non ancora presenti

SELECT p1.SKU
FROM prodotti_origine p1
LEFT JOIN prodotti_destinazione p2 ON p1.SKU = p2.SKU
WHERE p2.SKU IS NULL
AND p1.SKU IS NOT NULL
AND p1.SKU != '';

-- creiamo una nuova tabella temporanea dove andiamo a prendere tutti i prodotti nuovi

INSERT INTO nuovi_prodotti (SKU)
SELECT p1.SKU
FROM prodotti_origine p1
LEFT JOIN prodotti_destinazione p2 ON p1.SKU = p2.SKU
WHERE p2.SKU IS NULL
AND p1.SKU IS NOT NULL
AND p1.SKU != '';

-- lavoriamo solo sui nuovi prodotti e lasciamo il mondo come sta

CREATE TABLE magento_export_new
SELECT * FROM magento_export_beta_2 where Isbn IN (Select * from nuovi_prodotti); 

Si esegue l’import di prodotti e categorie, per farlo correttamente bisogna esportare come Migrate Prodotti (nel caso possiamo affinare, ma resta il nodo delle categorie prodotti che vengono cambiate a pioggia)


Contiene eBook
campo tabella URL_ebook se è pieno, il valore del campo contiene_ebook deve essere settato su yes

UPDATE magento_export_beta
SET contiene_ebook = CASE WHEN URL_ebook IS NOT NULL AND URL_ebook != '' THEN 'yes' ELSE contiene_ebook END;

ISBN eBook
Logica e script creati sul file http://script/isbn_ebook.php
Script successivo: /ebook-fix.php
Script successivo: /ebook-postmeta-fix.php

Contiene Cartaceo
si utilizza la stessa identica logica utilizzata per “contiene ebook”

UPDATE magento_export_beta
SET contiene_cartaceo = CASE WHEN URL_cartaceo IS NOT NULL AND URL_cartaceo != '' THEN 'yes' ELSE contiene_cartaceo END;


ISBN cartaceo
Logica e script creati sul file http://script/isbn_cartaceo.php

Volume Kit

UPDATE magento_export_beta
SET volume_kit = 'yes'
WHERE nome_prodotto LIKE '%kit%';

ISBN Volume Kit

eseguire lo scritp in /tool/volumi_kit_update.php. Ricordarsi di esportare la tabella aggiornata catalog_product_bundle_selection dal database Magento

-- creo una tabella con dentro tutti i dati solo dei nuovi prodotti
CREATE TABLE nuovi_prodotti_dati AS
SELECT magento.*
FROM magento_export_beta AS magento
INNER JOIN nuovi_prodotti AS nuovi ON magento.Isbn = nuovi.SKU;

Devo poi esportale le tabelle magento_export_beta e nuovi_prodotti verso il database definitivo

uso questa query per fare il match tra isbn della tabella magento con tutti i valori esportati e aggiornare il campo id_prodotto con il post_id di woocommerce

UPDATE magento_export_beta_2 AS m
JOIN wpcv_postmeta AS n ON m.Isbn = n.meta_value AND n.meta_key = 'isbn'
SET m.id_prodotto = n.post_id;
-- nel caso serva aggiornare gli id prodotto woocommerce rispetto a quelli attuali

UPDATE magento_export_new AS m
JOIN wpcv_postmeta AS w ON m.Isbn = w.meta_value
SET m.id_prodotto = w.post_id
WHERE w.meta_key = '_sku';

6. serialized_isbn_kit => script preposto

-- estrae in una tabella il corrispondente ID categoria Magento (funzionalità Legacy)
 
SELECT tm.meta_value AS ID_CAT_MAGENTO, 
tm.term_id AS ID_CAT_WOOCOMMERCE,
t.name AS NOME,
t.slug AS SLUG
FROM wpcv_termmeta as tm
JOIN wpcv_terms as t ON tm.term_id = t.term_id
WHERE tm.meta_key = '_id_categoria_magento';



Si esegue l’import di prodotti e categorie, per farlo correttamente bisogna esportare come Migrate Prodotti (nel caso possiamo affinare, ma resta il nodo delle categorie prodotti che vengono cambiate a pioggia)

Il nodo primario resta quello di sistemare solo i prodotti con differenze sostanziali per gli attributi extra, ad esempio: copertina, pagine, kit etc etc. Esistono già script che si occupano di sistemare tutti i dettagli, ma vengono fatti su tutti i prodotti, non vorrei andare ad intaccare quelli già sistemati, vanno rivisti tutti gli script.

-- questa pontentissima query estrae tutti i prodotti e relative categorie da magento

SELECT 
    cpe.entity_id AS 'Product_ID', 
    cpev.value AS 'Product_Name', 
    GROUP_CONCAT(DISTINCT ccv.value) AS 'Category_Names',
    GROUP_CONCAT(DISTINCT ccp.category_id) AS 'Category_IDs',
    MAX(ur.request_path) AS 'Product_URL'
FROM 
    catalog_product_entity AS cpe
JOIN 
    catalog_product_entity_varchar AS cpev ON cpe.entity_id = cpev.entity_id AND cpev.attribute_id = (SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'name' AND entity_type_id = (SELECT entity_type_id FROM eav_entity_type WHERE entity_type_code = 'catalog_product'))
LEFT JOIN 
    catalog_category_product AS ccp ON cpe.entity_id = ccp.product_id
LEFT JOIN 
    catalog_category_entity_varchar AS ccv ON ccp.category_id = ccv.entity_id AND ccv.attribute_id = (SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'name' AND entity_type_id = (SELECT entity_type_id FROM eav_entity_type WHERE entity_type_code = 'catalog_category'))
LEFT JOIN 
    url_rewrite AS ur ON ur.entity_id = cpe.entity_id AND ur.entity_type = 'product' AND ur.redirect_type = 0 AND ur.store_id = 1
GROUP BY 
    cpe.entity_id, cpev.value;

-- Creazione della nuova tabella per i risultati, accoppiamo le categorie magento a quelle woocommerce

CREATE TABLE `cat-magento-woocommerce` (
    category_id INT,
    category_name VARCHAR(255),
    magento_category_id INT
);

-- Inserimento dei risultati della query nella nuova tabella
INSERT INTO `cat-magento-woocommerce` (category_id, category_name, magento_category_id)
SELECT t.term_id AS category_id, t.name AS category_name, meta.meta_value AS magento_category_id
FROM wpcv_terms t
INNER JOIN wpcv_term_taxonomy tt ON t.term_id = tt.term_id
LEFT JOIN wpcv_termmeta meta ON t.term_id = meta.term_id AND meta.meta_key = '_id_categoria_magento'
WHERE tt.taxonomy = 'product_cat';

script per far combaciare prodotti e categorie: /cat_magento_woo.php

<?php
// Registra il tempo all'inizio dello script
$time_start = microtime(true);

$servername = "localhost";
$username = "yqmkgwhd_fabios";
$password = "persolino83";
$dbname = "yqmkgwhd_eddef";

$record_count = 0;
$association_count = 0;

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connessione fallita: " . $conn->connect_error);
}

// Query per recuperare i post_id presenti nella tabella cat-prod-magento
$post_ids_query = "SELECT DISTINCT post_id FROM wpcv_postmeta WHERE meta_key = '_magento_id'";
$post_ids_result = $conn->query($post_ids_query);

if ($post_ids_result->num_rows > 0) {
    $post_ids = [];
    while ($row = $post_ids_result->fetch_assoc()) {
        $post_ids[] = $row['post_id'];
    }
    $post_ids_string = implode(',', $post_ids);

    // Query per eliminare i legami relativi ai post_id presenti nella tabella cat-prod-magento
    $delete_existing_query = "DELETE FROM wpcv_term_relationships WHERE object_id IN ($post_ids_string)";
    $conn->query($delete_existing_query);
    echo "Legami esistenti cancellati per i post_id presenti nella tabella cat-prod-magento<br>";
} else {
    echo "Nessun post_id trovato nella tabella cat-prod-magento<br>";
}

// Query per recuperare i dati dalla tabella cat-prod-magento
$sql = "SELECT ID_Magento, Category_ID FROM `cat-prod-magento`";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $product_id_query = "SELECT post_id FROM wpcv_postmeta WHERE meta_key = '_magento_id' AND meta_value = '{$row['ID_Magento']}'";
        $product_id_result = $conn->query($product_id_query);
        if ($product_id_result->num_rows > 0) {
            $product_id_row = $product_id_result->fetch_assoc();
            $product_id = $product_id_row['post_id'];
            $category_ids = explode(',', $row['Category_ID']);
            foreach ($category_ids as $category_id) {
                $query = "SELECT woocommerce_cat FROM `cat-magento-woocommerce` WHERE magento_cat = '$category_id'";
                $woocommerce_result = $conn->query($query);
                if ($woocommerce_result->num_rows > 0) {
                    $woocommerce_row = $woocommerce_result->fetch_assoc();
                    $woocommerce_category_id = $woocommerce_row['woocommerce_cat'];

                    $check_query = "SELECT 1 FROM wpcv_term_relationships WHERE object_id = '$product_id' AND term_taxonomy_id = '$woocommerce_category_id'";
                    $check_result = $conn->query($check_query);
                    if ($check_result->num_rows == 0) {
                        $insert_query = "INSERT INTO wpcv_term_relationships (object_id, term_taxonomy_id) VALUES ('$product_id', '$woocommerce_category_id')";
                        $conn->query($insert_query);
                        echo "Prodotto $product_id associato con successo alla categoria WooCommerce $woocommerce_category_id<br>";
                        $association_count++;
                    } else {
                        echo "Relazione già esistente tra prodotto $product_id e categoria WooCommerce $woocommerce_category_id, non inserita per evitare duplicati<br>";
                    }
                } else {
                    echo "Nessuna corrispondenza trovata per il Magento category ID: $category_id<br>";
                }
            }
        } else {
            echo "Nessun post_id trovato per Magento ID: {$row['ID_Magento']}<br>";
        }
        $record_count++;
    }
} else {
    echo "0 risultati";
}

$conn->close();

// Registra il tempo alla fine dello script
$time_end = microtime(true);
$execution_time = ($time_end - $time_start);
$execution_minutes = floor($execution_time / 60);
$execution_seconds = round($execution_time % 60, 2);

echo "Numero totale di record processati: $record_count<br>";
echo "Numero di associazioni create con successo: $association_count<br>";
echo "Tempo totale di esecuzione dello script: $execution_minutes minuti e $execution_seconds secondi";

?>

-- categorie disabilitate su magento

SELECT entity_id
FROM catalog_category_entity
WHERE entity_id NOT IN (
    SELECT entity_id
    FROM catalog_category_entity_int
    WHERE attribute_id = (
        SELECT attribute_id
        FROM eav_attribute
        WHERE attribute_code = 'is_active'
        AND entity_type_id = (
            SELECT entity_type_id
            FROM eav_entity_type
            WHERE entity_type_code = 'catalog_category'
        )
    )
    AND value = 1
);