Senza categoria

URL – EdiSES

Andiamo ad esportare gli url tramite query

SELECT
    p.entity_id AS product_id,
    ur.request_path AS product_url
FROM
    catalog_product_entity AS p
JOIN
    (
        SELECT
            entity_id,
            MIN(request_path) AS request_path
        FROM
            url_rewrite
        WHERE
            entity_type = 'product'
            AND redirect_type = 0
            AND request_path LIKE '%.html'
            AND request_path NOT LIKE '%/%'
        GROUP BY
            entity_id
    ) AS ur ON p.entity_id = ur.entity_id;

puliamo il file sql dai .html e cambiamo l’intestazione di insert in

INSERT INTO `url_magento` (`entity_id`, `url`) VALUES (86,"abc-degli-occhi")

salviamo e svuotiamo la tabella url_magento e poi si passa alla query di match

UPDATE wpcv_posts
SET post_name = (
    SELECT um.url
    FROM url_magento um
    INNER JOIN wpcv_postmeta wpm ON um.entity_id = wpm.meta_value AND wpm.meta_key = '_magento_id'
    WHERE wpm.post_id = wpcv_posts.ID
)
WHERE ID IN (
    SELECT wpm.post_id
    FROM wpcv_postmeta wpm
    INNER JOIN url_magento um ON wpm.meta_value = um.entity_id AND wpm.meta_key = '_magento_id'
);

Senza categoria

Operazioni Online EdiSES

Di seguito un elenco di operazioni da effettuare per andare online

Partiamo dall’individuare i prodotti che verranno poi messi in bozza su WooCommerce, tabella prodotti-bozza

SELECT 
    p.entity_id AS product_id,
    p.sku AS product_sku,
    v.value AS product_name,
    s.qty AS quantity_available,
    s.is_in_stock AS stock_status,
    s.manage_stock AS manage_stock,
    stat.value AS status
FROM 
    catalog_product_entity AS p
JOIN 
    cataloginventory_stock_item AS s ON p.entity_id = s.product_id
JOIN 
    catalog_product_entity_varchar AS v ON p.entity_id = v.entity_id
JOIN 
    eav_attribute AS a ON v.attribute_id = a.attribute_id
JOIN 
    catalog_product_entity_int AS stat ON p.entity_id = stat.entity_id
JOIN 
    eav_attribute AS a_stat ON stat.attribute_id = a_stat.attribute_id
WHERE 
    a.attribute_code = 'name'
    AND v.store_id = 0
    AND a_stat.attribute_code = 'status'
    AND stat.value = 2; -- 2 indica che il prodotto è disabilitato

Per estrarre i volumi che dovranno avere il template Librerie – tabella prodotti-librerie

SELECT DISTINCT cpe.entity_id, cpe.sku, cpev_name.value AS product_name
FROM catalog_product_entity AS cpe
JOIN catalog_product_entity_int AS cpei_visibility ON cpe.entity_id = cpei_visibility.entity_id
JOIN catalog_product_entity_int AS cpei_status ON cpe.entity_id = cpei_status.entity_id
JOIN cataloginventory_stock_item AS csi ON cpe.entity_id = csi.product_id
JOIN catalog_product_entity_varchar AS cpev_name ON cpe.entity_id = cpev_name.entity_id
WHERE cpei_status.attribute_id = (SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'status' AND entity_type_id = 4)
AND cpei_status.value = 1 /* Stato abilitato */
AND cpei_visibility.attribute_id = (SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'visibility' AND entity_type_id = 4)
AND cpei_visibility.value = 2 /* Visibilità solo catalogo */
AND csi.manage_stock = 1 /* Gestione inventario non disponibile */
AND cpev_name.attribute_id = (SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'name' AND entity_type_id = 4)
AND cpe.type_id != 'virtual'; /* Escludi prodotti virtuali */

Va estrapolato il vecchia/nuova edizione

SELECT 
    p.entity_id AS product_id,
    p.sku AS product_sku,
    nva.value AS new_version_available
FROM 
    catalog_product_entity AS p
JOIN 
    catalog_product_entity_varchar AS nva ON p.entity_id = nva.entity_id
JOIN 
    eav_attribute AS a ON nva.attribute_id = a.attribute_id
WHERE 
    a.attribute_code = 'newVersionAvailable'
AND 
    a.entity_type_id = 4
AND 
    nva.value IS NOT NULL
AND 
    nva.value != '0';  -- Assicurati che l'entity_type_id sia corretto per i prodotti

Bisogna estrarre e sincronizzare la data di pubblicazione del prodotto

SELECT entity_id AS product_id, 
       sku, 
       created_at AS data_di_creazione, 
       updated_at AS data_di_modifica
FROM catalog_product_entity;

Vanno estratti e aggiornati tutti gli attributi SEO

SELECT 
    p.entity_id AS product_id,
    p.sku AS product_sku,
    name.value AS product_name,
    url_key.value AS url_key,
    meta_title.value AS meta_title,
    meta_description.value AS meta_description,
    meta_keyword.value AS meta_keyword
FROM 
    catalog_product_entity AS p
LEFT JOIN 
    catalog_product_entity_varchar AS name ON p.entity_id = name.entity_id 
    AND name.attribute_id = (SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'name' AND entity_type_id = 4)
LEFT JOIN 
    catalog_product_entity_varchar AS url_key ON p.entity_id = url_key.entity_id 
    AND url_key.attribute_id = (SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'url_key' AND entity_type_id = 4)
LEFT JOIN 
    catalog_product_entity_varchar AS meta_title ON p.entity_id = meta_title.entity_id 
    AND meta_title.attribute_id = (SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'meta_title' AND entity_type_id = 4)
LEFT JOIN 
    catalog_product_entity_text AS meta_description ON p.entity_id = meta_description.entity_id 
    AND meta_description.attribute_id = (SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'meta_description' AND entity_type_id = 4)
LEFT JOIN 
    catalog_product_entity_text AS meta_keyword ON p.entity_id = meta_keyword.entity_id 
    AND meta_keyword.attribute_id = (SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'meta_keyword' AND entity_type_id = 4)


posizione del prodotto all’interno della categoria

SELECT 
    c.entity_id AS category_id,
    cev.value AS category_name,
    p.entity_id AS product_id,
    p.sku AS product_sku,
    cp.position AS product_position
FROM
    catalog_category_product cp
INNER JOIN
    catalog_category_entity c ON cp.category_id = c.entity_id
INNER JOIN
    catalog_product_entity p ON cp.product_id = p.entity_id
LEFT JOIN
    catalog_category_entity_varchar cev ON c.entity_id = cev.entity_id
        AND cev.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'
            )
        )
ORDER BY
    c.entity_id ASC, cp.position ASC;

Lista dei prodotto e categorie di appartenenza

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;

Estrarre dettagli di un singolo prodotto

SELECT
    e.entity_id,
    e.sku,
    e.created_at,
    e.updated_at,
    ea.attribute_code,
    CASE ea.backend_type
        WHEN 'varchar' THEN ev.value
        WHEN 'int' THEN ei.value
        WHEN 'decimal' THEN ed.value
        WHEN 'text' THEN et.value
        WHEN 'datetime' THEN edate.value
        ELSE NULL
    END AS value
FROM catalog_product_entity AS e
JOIN eav_attribute AS ea ON ea.entity_type_id = 4 -- 4 is typically for products in Magento 2
LEFT JOIN catalog_product_entity_varchar AS ev ON ev.attribute_id = ea.attribute_id AND ev.entity_id = e.entity_id AND ea.backend_type = 'varchar'
LEFT JOIN catalog_product_entity_int AS ei ON ei.attribute_id = ea.attribute_id AND ei.entity_id = e.entity_id AND ea.backend_type = 'int'
LEFT JOIN catalog_product_entity_decimal AS ed ON ed.attribute_id = ea.attribute_id AND ed.entity_id = e.entity_id AND ea.backend_type = 'decimal'
LEFT JOIN catalog_product_entity_text AS et ON et.attribute_id = ea.attribute_id AND et.entity_id = e.entity_id AND ea.backend_type = 'text'
LEFT JOIN catalog_product_entity_datetime AS edate ON edate.attribute_id = ea.attribute_id AND edate.entity_id = e.entity_id AND ea.backend_type = 'datetime'
WHERE e.entity_id = 6018;  -- id prodotto magento

Estrazione url prodotto


Estrazione URL categorie

SELECT 
    c.entity_id AS category_id,
    ccev.value AS category_name,
    ur.request_path AS category_url
FROM 
    catalog_category_entity AS c
JOIN 
    catalog_category_entity_varchar AS ccev ON c.entity_id = ccev.entity_id
JOIN 
    eav_attribute AS a ON ccev.attribute_id = a.attribute_id
JOIN 
    url_rewrite AS ur ON c.entity_id = ur.entity_id
WHERE 
    ur.entity_type = 'category'
AND 
    a.attribute_code = 'name'
AND 
    ur.redirect_type = 0  -- Assicurati che non sia un redirect

Senza categoria

Pulizia database + Utility

operazione fondamentale, vengono eliminati tutti i record orfani

-- Identificare i valori orfani
SELECT * 
FROM wp_termmeta 
WHERE term_id NOT IN (SELECT term_id FROM wp_terms);

-- Eliminare i valori orfani
DELETE FROM wp_termmeta 
WHERE term_id NOT IN (SELECT term_id FROM wp_terms);

Andiamo a trovare le corrispondenze tra ID categoria Magento e ID categoria WooCommerce

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';
Senza categoria

infolib

<?php
/*
Plugin Name: Woo - INFOLIB
Description: Genera il documento XML necessario per infoliB
Version: 1.3.5
Author: FabioS - Digital Followers
Author URI: https://www.digitalfollowers.com
Text Domain: wc-generate-xml
*/

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

// Installazione: creazione della tabella SQL per memorizzare gli XML generati
register_activation_hook( __FILE__, 'wc_generate_xml_install' );
function wc_generate_xml_install() {
	global $wpdb;
	$table_name = $wpdb->prefix . 'generated_xml';

	$charset_collate = $wpdb->get_charset_collate();

	$sql = "CREATE TABLE $table_name (
		id mediumint(9) NOT NULL AUTO_INCREMENT,
		order_id bigint(20) NOT NULL,
		file_path varchar(255) NOT NULL,
		creation_datetime datetime NOT NULL,
		num_trasmissione int(11) NOT NULL,
		PRIMARY KEY  (id),
		UNIQUE KEY order_id (order_id)
	) $charset_collate;";

	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
	dbDelta( $sql );
}

// Aggiunge i box per la gestione del file XML nella pagina di dettaglio dell'ordine nel backend
add_action( 'add_meta_boxes', 'wc_add_generate_xml_metabox' );
function wc_add_generate_xml_metabox() {
	add_meta_box(
		'wc_generate_xml_metabox',
		__( 'Gestione XML INFOLIB', 'wc-generate-xml' ),
		'wc_generate_xml_metabox_content',
		'shop_order',
		'side',
		'default'
	);
}

function wc_generate_xml_metabox_content( $post ) {

	global $wpdb;
	$order_id = $post->ID;
	$file_info = wc_get_generated_xml_info( $order_id );

	$table_name_generated = $wpdb->prefix . 'generated_xml';

	$num_trasmissione = $wpdb->get_var($wpdb->prepare(
        "SELECT num_trasmissione FROM $table_name_generated WHERE order_id = %d",
        $order_id
    ));

	if ( $file_info ) {
		$file_path = esc_attr( $file_info->file_path );
		$creation_datetime = date( 'd/m/Y H:i:s', strtotime( $file_info->creation_datetime ) );

		echo '<p><strong>' . __( 'Nome File:', 'wc-generate-xml' ) . '</strong> ' . basename( $file_path ) . '</p>';
		echo '<p><strong>' . __( 'Data e Ora di creazione:', 'wc-generate-xml' ) . '</strong> ' . $creation_datetime . '</p>';
		echo '<p><strong>' . __( 'Numero Trasmissione:', 'wc-generate-xml' ) . '</strong> ' . $num_trasmissione . '</p>';
		echo '<button id="view_xml_button" class="button" data-file-path="' . $file_path . '">' . __( 'Visualizza XML', 'wc-generate-xml' ) . '</button>';
		echo '<button id="regenerate_xml_button" class="button" data-order-id="' . esc_attr( $order_id ) . '">' . __( 'Rigenera XML', 'wc-generate-xml' ) . '</button>';
	} else {
		echo '<button id="generate_xml_button" class="button" data-order-id="' . esc_attr( $order_id ) . '">' . __( 'Genera Fattura', 'wc-generate-xml' ) . '</button>';
	}
}

// AJAX per generare l'XML

add_action('wp_ajax_generate_xml', 'wc_generate_xml');
function wc_generate_xml() {
    check_ajax_referer('wc_generate_xml_nonce', 'security');

    if (!isset($_POST['order_id'])) {
        wp_send_json_error('Invalid Order ID');
    }

    $order_id = intval($_POST['order_id']);
    $order = wc_get_order($order_id);

    if (!$order) {
        wp_send_json_error('Order not found');
    }

    $xml_content = wc_create_xml($order);

    if ($xml_content) {
       // $numeroTrasmissione = get_numero_trasmissione($order_id); // Ottiene il numero di trasmissione
        $file_path = wc_save_generated_xml($order_id, $xml_content); // Usa il valore corrente
        wp_send_json_success(array('message' => 'XML Generated Successfully', 'file_path' => $file_path));
    } else {
        wp_send_json_error('Failed to generate XML');
    }
}


// refactor 
function get_numero_trasmissione($order_id) {
    global $wpdb;
    $date_today = date('Y-m-d');
    $table_name_counter = $wpdb->prefix . 'infolibexport_counter';
    $table_name_generated = $wpdb->prefix . 'generated_xml';

    // Controlla se l'ordine è già presente nella tabella generated_xml
    $num_trasmissione_existing = $wpdb->get_var($wpdb->prepare(
        "SELECT num_trasmissione FROM $table_name_generated WHERE order_id = %d",
        $order_id
    ));

    if ($num_trasmissione_existing !== null) {
        return array('current' => $num_trasmissione_existing, 'is_new' => false);
		error_log('RECORD INDIVIDUATO ORDINE: ' . $order_id);
    }

    // Ottieni il contatore per la data odierna
    $counter = $wpdb->get_var($wpdb->prepare(
        "SELECT counter FROM $table_name_counter WHERE date = %s",
        $date_today
    ));

    if ($counter === null) {
        // Nessun record per la data odierna, creane uno nuovo
        $current_counter = 1;
        $wpdb->insert($table_name_counter, array(
            'date' => $date_today,
            'counter' => $current_counter
        ), array('%s', '%d'));
		error_log('NESSUN RECORD PER LA DATA ODIERNA, INCREMENTO CONTATORE');
		error_log('Query insert: ' . $wpdb->last_query);
    } else {
        $current_counter = $counter + 1;
        $wpdb->update($table_name_counter, array(
            'counter' => $current_counter
        ), array('date' => $date_today), array('%d'), array('%s'));
		error_log('AUMENTO CONTATORE PER ORDINE' . $order_id);
		error_log('Query update: ' . $wpdb->last_query);

    }

    return array('current' => $current_counter, 'is_new' => true);
}



// Funzione per creare l'XML
function wc_create_xml( $order ) {
	global $wpdb;

	$dateOraTrasmissione = new DateTime('now', new DateTimeZone('Europe/Rome'));
	$dataOraTrasmissione = $dateOraTrasmissione->format('Y-m-d\TH:i:s');

	$dataImpegno = $order->get_date_created()->date( 'Y-m-d' );
	$numeroImpegno = $order->get_id();
	$scenario = 'C';
	$importoSpeseSpedizione = $order->get_shipping_total();
	$importoTotDoc = $order->get_total();
	$importoAbbuono = 0;

	$customer_id = $order->get_user_id();
	$user_info = get_userdata( $customer_id );
	$ragSoc1 = $user_info->first_name . ' ' . $user_info->last_name;
	$codiceFiscale = get_user_meta( $customer_id, 'billing_vat', true );
	$via = $order->get_billing_address_1();
	$cap = $order->get_billing_postcode();
	$localita = $order->get_billing_city();
	$provincia = $order->get_billing_state();
	$nazione = $order->get_billing_country();
	$telefono = $order->get_billing_phone();
	$email = $order->get_billing_email();

	$note_impegno = $order->get_customer_note();

	$xml = new SimpleXMLElement( '<Trasmissione></Trasmissione>' );
	$datiTrasmissione = $xml->addChild( 'DatiTrasmissione' );
	$datiTrasmissione->addChild( 'DataOraTrasmissione', $dataOraTrasmissione );
	$datiTrasmissione->addChild( 'NumeroTrasmissione', $numeroTrasmissione );
	$datiTrasmissione->addChild( 'IDSito', $idSito );

	$impegno = $xml->addChild( 'Impegno' );
	$impegno->addChild( 'DataImpegno', $dataImpegno );
	$impegno->addChild( 'NumeroImpegno', $numeroImpegno );
	$impegno->addChild( 'Scenario', $scenario );
	$impegno->addChild( 'ImportoSpeseSpedizione', $importoSpeseSpedizione );
	$impegno->addChild( 'ImportoTotDoc', $importoTotDoc );
	$impegno->addChild( 'ImportoAbbuono', $importoAbbuono );
	$impegno->addChild( 'CodicePagamento', 4 );  // Aggiungi il codice di pagamento
	$impegno->addChild( 'ImportoPagatoCodicePagamento', $importoTotDoc ); // Importo pagato
	$impegno->addChild( 'NoteImpegno', $note_impegno ); // Nota dell'impegno

	$utenteRegistrato = $impegno->addChild( 'UtenteRegistrato' );
	$utenteRegistrato->addChild( 'RagSoc1', $ragSoc1 );
	$utenteRegistrato->addChild( 'PersonaFisGiur', 'F' ); // F = Persona fisica
	$utenteRegistrato->addChild( 'Sesso', 'M' ); // Sesso
	$utenteRegistrato->addChild( 'Cognome', $user_info->last_name );
	$utenteRegistrato->addChild( 'Nome', $user_info->first_name );
	$utenteRegistrato->addChild( 'CodiceFiscale', $codiceFiscale );
	$utenteRegistrato->addChild( 'Via', $via );
	$utenteRegistrato->addChild( 'CAP', $cap );
	$utenteRegistrato->addChild( 'Localita', $localita );
	$utenteRegistrato->addChild( 'Provincia', $provincia );
	$utenteRegistrato->addChild( 'Nazione', $nazione );
	$utenteRegistrato->addChild( 'Telefono', $telefono );
	$utenteRegistrato->addChild( 'E-Mail', $email );
	$utenteRegistrato->addChild( 'Vettore', 1 ); // ID del vettore, placeholder

	$utenteDocumento = $impegno->addChild( 'UtenteDocumento' );
	$utenteDocumento->addChild( 'RagSoc1', $ragSoc1 );
	$utenteDocumento->addChild( 'PersonaFisGiur', 'F' ); // F = Persona fisica
	$utenteDocumento->addChild( 'Sesso', 'M' ); // Sesso
	$utenteDocumento->addChild( 'Cognome', $user_info->last_name );
	$utenteDocumento->addChild( 'Nome', $user_info->first_name );
	$utenteDocumento->addChild( 'CodiceFiscale', $codiceFiscale );
	$utenteDocumento->addChild( 'Via', $via );
	$utenteDocumento->addChild( 'CAP', $cap );
	$utenteDocumento->addChild( 'Localita', $localita );
	$utenteDocumento->addChild( 'Provincia', $provincia );
	$utenteDocumento->addChild( 'Nazione', $nazione );
	$utenteDocumento->addChild( 'Telefono', $telefono );
	$utenteDocumento->addChild( 'E-Mail', $email );
	$utenteDocumento->addChild( 'Vettore', 1 ); // ID del vettore, placeholder

	$shipping_first_name = $order->get_shipping_first_name();
	$shipping_last_name = $order->get_shipping_last_name();
	$shipping_company = $order->get_shipping_company();
	$shipping_address_1 = $order->get_shipping_address_1();
	$shipping_address_2 = $order->get_shipping_address_2();
	$shipping_city = $order->get_shipping_city();
	$shipping_state = $order->get_shipping_state();
	$shipping_postcode = $order->get_shipping_postcode();
	$shipping_country = $order->get_shipping_country();
	$shipping_phone = $order->get_shipping_phone(); // WooCommerce non ha un campo phone per l'indirizzo di spedizione
	$shipping_email = $order->get_billing_email(); // WooCommerce non ha un campo email per l'indirizzo di spedizione

	$datiSpedizione = $impegno->addChild( 'DatiSpedizione' );
	$datiSpedizione->addChild( 'RagSoc1', $shipping_first_name . ' ' . $shipping_last_name );
	$datiSpedizione->addChild( 'Via', $shipping_address_1 . ' ' . $shipping_address_2 );
	$datiSpedizione->addChild( 'CAP', $shipping_postcode );
	$datiSpedizione->addChild( 'Localita', $shipping_city );
	$datiSpedizione->addChild( 'Provincia', $shipping_state );
	$datiSpedizione->addChild( 'Nazione', $shipping_country );
	$datiSpedizione->addChild( 'Telefono', $shipping_phone );
	$datiSpedizione->addChild( 'E-Mail', $shipping_email );
	$datiSpedizione->addChild( 'Vettore', 1 ); // ID del vettore, placeholder

	$items = $order->get_items();
	foreach ( $items as $item_id => $item ) {
		$product = $item->get_product();
		$rigaTitolo = $impegno->addChild( 'RigaTitolo' );
		$rigaTitolo->addChild( 'NumeroRiga', $item_id );
		$rigaTitolo->addChild( 'CodiceTitolo', $product->get_sku() );
		$rigaTitolo->addChild( 'PrezzoCopertina', number_format( $item->get_total(), 4, '.', '' ) );
		$rigaTitolo->addChild( 'Quantita', number_format( $item->get_quantity(), 4, '.', '' ) );
		$rigaTitolo->addChild( 'Sconto1', number_format( $item->get_subtotal() - $item->get_total(), 2, '.', '' ) );
		$rigaTitolo->addChild( 'Sconto2', '0.00' );
		$rigaTitolo->addChild( 'TotaleNettoRiga', number_format( $item->get_total(), 2, '.', '' ) );
		$rigaTitolo->addChild( 'CodiceIVA', '74' );
	}

	$dom = dom_import_simplexml( $xml )->ownerDocument;
	$dom->formatOutput = true;
	$xml_string = $dom->saveXML();

	// Rimuove eventuali script aggiunti
	$xml_string = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', '', $xml_string);

	return $xml_string;
}


// Funzione per salvare l'XML generato nel file system e registrare il percorso nel databasefunction wc_save_generated_xml($order_id, $xml_content, $numero_trasmissione_data) {
	function wc_save_generated_xml($order_id, $xml_content) {
		$numero_trasmissione_data = get_numero_trasmissione($order_id);
		$num_trasmissione = $numero_trasmissione_data['current'];
		
		error_log('VALORE TRASMISSIONE: ' . $num_trasmissione);
		
		$date = date('Y-m-d');
		$data_doc = date('Ymd');
		$fatture_dir = ABSPATH . 'fatture/' . $date . '/';
		$fatture_dir_query = '../fatture/' . $date . '/';
	
		if (!file_exists($fatture_dir)) {
			if (!wp_mkdir_p($fatture_dir)) {
				error_log("Impossibile creare la directory: " . $fatture_dir);
				return false;  // Se la directory non può essere creata, ritorna false
			}
		}
	
		$file_name = 'IMP_edises_' . $data_doc . '_' . $order_id . '.xml';
		$file_path = $fatture_dir . $file_name;
		$file_path_query = $fatture_dir_query . $file_name;
	
		if (file_put_contents($file_path, $xml_content) === false) {
			error_log("Impossibile scrivere il file XML: " . $file_path);
			return false;  // Gestione errore se il file non può essere scritto
		}
	
		chmod($file_path, 0755);
	
		global $wpdb;
		$table_name = $wpdb->prefix . 'generated_xml';
	
		$result = $wpdb->replace($table_name, array(
			'order_id' => $order_id,
			'file_path' => $file_path_query,
			'creation_datetime' => current_time('mysql'),
			'num_trasmissione' => $num_trasmissione
		), array('%d', '%s', '%s', '%d'));
	
		if ($result === false) {
			error_log("Errore nella query SQL: " . $wpdb->last_error);
			return false;  // Gestione errore se la query fallisce
		}
	
		return $file_path;
	}
	

// Funzione per ottenere le informazioni del file XML generato dal database
function wc_get_generated_xml_info( $order_id ) {
	global $wpdb;
	$table_name = $wpdb->prefix . 'generated_xml';

	$file_info = $wpdb->get_row( $wpdb->prepare( "SELECT file_path, creation_datetime FROM $table_name WHERE order_id = %d", $order_id ) );

	return $file_info;
}

// JavaScript per gestire i pulsanti "Genera", "Visualizza" e "Rigenera"
add_action( 'admin_enqueue_scripts', 'wc_admin_enqueue_scripts' );
function wc_admin_enqueue_scripts( $hook ) {
	if ( 'post.php' === $hook && 'shop_order' === get_post_type() ) {
		wp_enqueue_script( 'wc-generate-xml', plugin_dir_url( __FILE__ ) . 'js/wc-generate-xml.js', array( 'jquery' ), '1.0', true );
		wp_localize_script( 'wc-generate-xml', 'wc_generate_xml_params', array(
			'ajax_url' => admin_url( 'admin-ajax.php' ),
			'security' => wp_create_nonce( 'wc_generate_xml_nonce' ),
		) );
	}
}

// Funzione per caricare il file CSS nell'area amministrativa
function infolib_css() {
    // Ottieni il percorso del plugin
    $plugin_url = plugin_dir_url( __FILE__ );

    // Enqueue il file CSS
    wp_enqueue_style( 'infolib-admin-css', $plugin_url . 'css/infolib.css' );
}

// Hook per caricare il CSS solo nell'area amministrativa
add_action( 'admin_enqueue_scripts', 'infolib_css' );


?> 
Senza categoria

Endpoin infoConcorsi API

https://edises-import.digitalfollowers.it/wp-json/custom/v1/products?id_prodotto=5047&amp;consumer_key=ck_20c8fe129a0d05d24decfcd29b4c64f7bc554832&amp;consumer_secret=cs_14993e71ea3ed574f620de2bfe30944d2470c3c4

chiave id_prodotto cerca prima su meta_key = _magento_id se questo non dovesse essere disponibile allora cerca su ID prodotto.
Funzione pensata appositamente per modalità legacy di transizione tra Magento e WooCommerce

ck_20c8fe129a0d05d24decfcd29b4c64f7bc554832
cs_14993e71ea3ed574f620de2bfe30944d2470c3c4

Senza categoria

EdiSES – Estrarre Prodotti e attributi

Prima si crea la tabella, se presente svuotala

CREATE TABLE `prodotti_attributi` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `entity_id` int(11) DEFAULT NULL,
  `sku` varchar(255) DEFAULT NULL,
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  `attribute_code` varchar(255) DEFAULT NULL,
  `value` text,
  PRIMARY KEY (`id`),
  KEY `idx_entity_id` (`entity_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1245674 DEFAULT CHARSET=utf8

si esegue la query, impiegherà circa 10 secondi su pc locale, il peso complessivo è di circa 155MB. Si esporta e iporta nel database in produzione. Svuota la tabella e ricaricala

INSERT INTO prodotti_attributi (entity_id, sku, created_at, updated_at, attribute_code, value)
SELECT
    e.entity_id,
    e.sku,
    e.created_at,
    e.updated_at,
    ea.attribute_code,
    CASE ea.backend_type
        WHEN 'varchar' THEN ev.value
        WHEN 'int' THEN ei.value
        WHEN 'decimal' THEN ed.value
        WHEN 'text' THEN et.value
        WHEN 'datetime' THEN edate.value
        ELSE NULL
    END AS value
FROM catalog_product_entity AS e
JOIN eav_attribute AS ea ON ea.entity_type_id = 4 -- 4 is typically for products in Magento 2
LEFT JOIN catalog_product_entity_varchar AS ev ON ev.attribute_id = ea.attribute_id AND ev.entity_id = e.entity_id AND ea.backend_type = 'varchar'
LEFT JOIN catalog_product_entity_int AS ei ON ei.attribute_id = ea.attribute_id AND ei.entity_id = e.entity_id AND ea.backend_type = 'int'
LEFT JOIN catalog_product_entity_decimal AS ed ON ed.attribute_id = ea.attribute_id AND ed.entity_id = e.entity_id AND ea.backend_type = 'decimal'
LEFT JOIN catalog_product_entity_text AS et ON et.attribute_id = ea.attribute_id AND et.entity_id = e.entity_id AND ea.backend_type = 'text'
LEFT JOIN catalog_product_entity_datetime AS edate ON edate.attribute_id = ea.attribute_id AND edate.entity_id = e.entity_id AND ea.backend_type = 'datetime';

CREATE INDEX idx_entity_id ON prodotti_attributi (entity_id);

La query sottostante estrae i prodotti e le relative categorie di appartenenza

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;
Senza categoria

EdiSES – Ordinamento Prodotti nelle categorie

SELECT 
    c.entity_id AS category_id,
    cev.value AS category_name,
    p.entity_id AS product_id,
    p.sku AS product_sku,
    cp.position AS product_position
FROM
    catalog_category_product cp
INNER JOIN
    catalog_category_entity c ON cp.category_id = c.entity_id
INNER JOIN
    catalog_product_entity p ON cp.product_id = p.entity_id
LEFT JOIN
    catalog_category_entity_varchar cev ON c.entity_id = cev.entity_id
        AND cev.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'
            )
        )
ORDER BY
    c.entity_id ASC, cp.position ASC;

PHP, WordPress

EdiSES – Prodotti Disabilitati

SELECT DISTINCT cpe.entity_id, cpe.sku, cpev_name.value AS product_name
FROM catalog_product_entity AS cpe
JOIN catalog_product_entity_int AS cpei_visibility ON cpe.entity_id = cpei_visibility.entity_id
JOIN catalog_product_entity_int AS cpei_status ON cpe.entity_id = cpei_status.entity_id
JOIN cataloginventory_stock_item AS csi ON cpe.entity_id = csi.product_id
JOIN catalog_product_entity_varchar AS cpev_name ON cpe.entity_id = cpev_name.entity_id
WHERE cpei_status.attribute_id = (SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'status' AND entity_type_id = 4)
AND cpei_status.value = 1 /* Stato abilitato */
AND cpei_visibility.attribute_id = (SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'visibility' AND entity_type_id = 4)
AND cpei_visibility.value = 2 /* Visibilità solo catalogo */
AND csi.manage_stock = 1 /* Gestione inventario non disponibile */
AND cpev_name.attribute_id = (SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'name' AND entity_type_id = 4);

fare riferimento allo script prodotti-disabilitati.php
// TODO
abilitare eliminazione record _rivolgiti_libreria se già esistente

PHP

Dea Salus – WooCommerce Print Invoice & Delivery Note/Templates

<?php
/**
 * Print order content. Copy this file to your themes
 * directory /woocommerce/print-order to customize it.
 *
 * @package WooCommerce Print Invoice & Delivery Note/Templates
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
?>

	<div class="order-branding">
		<div class="company-logo" style="display:inline-block;width:50%;">
			<?php
			if ( wcdn_get_company_logo_id() ) :
				?>
				<?php wcdn_company_logo(); ?><?php endif; ?>
				
		</div>

		<div class="order-notes" style="display:inline-block;margin:0px;">
		<?php if ( wcdn_has_customer_notes( $order ) ) : ?>
			<h4><?php esc_attr_e( 'Customer Note', 'woocommerce-delivery-notes' ); ?></h4>
			<?php wcdn_customer_notes( $order ); ?>
		<?php endif; ?>

		<?php do_action( 'wcdn_after_notes', $order ); ?>
	</div><!-- .order-notes -->

		<div class="company-info">
			<?php
			if ( ! wcdn_get_company_logo_id() ) :
				?>
				<h1 class="company-name"><?php wcdn_company_name(); ?></h1><?php endif; ?>
			<div class="company-address"><?php wcdn_company_info(); ?></div>
		</div>

		<?php do_action( 'wcdn_after_branding', $order ); ?>
	</div><!-- .order-branding -->

	<div class="order-addresses">
		<div class="billing-address">
			<h3><?php esc_attr_e( 'Billing Address', 'woocommerce-delivery-notes' ); ?></h3>
			<address>

				<?php
				if ( ! $order->get_formatted_billing_address() ) {
					esc_attr_e( 'N/A', 'woocommerce-delivery-notes' );
				} else {
					echo wp_kses_post( apply_filters( 'wcdn_address_billing', $order->get_formatted_billing_address(), $order ) );
				}
				?>

			</address>
		</div>

		<div class="shipping-address">						
			<h3><?php esc_attr_e( 'Shipping Address', 'woocommerce-delivery-notes' ); ?></h3>
			<address>

				<?php
				if ( ! $order->get_formatted_shipping_address() ) {
					esc_attr_e( 'N/A', 'woocommerce-delivery-notes' );
				} else {
					echo wp_kses_post( apply_filters( 'wcdn_address_shipping', $order->get_formatted_shipping_address(), $order ) );
				}
				?>

			</address>
		</div>

		<?php do_action( 'wcdn_after_addresses', $order ); ?>
	</div><!-- .order-addresses -->


	<div class="order-info">
		<h2><?php wcdn_document_title(); ?></h2>

		<ul class="info-list">
			<?php
			$fields = apply_filters( 'wcdn_order_info_fields', wcdn_get_order_info( $order ), $order );
			?>
			<?php foreach ( $fields as $field ) : ?>
				<li>
					<strong><?php echo wp_kses_post( apply_filters( 'wcdn_order_info_name', $field['label'], $field ) ); ?></strong>
					<span><?php echo wp_kses_post( apply_filters( 'wcdn_order_info_content', $field['value'], $field ) ); ?></span>
				</li>
			<?php endforeach; ?>

					<?php
			$spedizione = $order->get_shipping_method();
			
			if ($spedizione == 'Ritiro in Negozio (Padova, Via Guizza 215)'){
			?>
			<li>
			<strong>Spedizione</strong>
			<span style="font-weight:bold;">RITIRO IN NEGOZIO</span>
			</li>
			<?php
			}
			?>
			
			<?php
			$spedizione = $order->get_shipping_method();
			
			if ($spedizione == 'Ritiro in Negozio (Schiavonia - C/O Sanitaria Ospedale)'){
			?>
			<li>
			<strong>Spedizione</strong>
			<span style="font-weight:bold;">RITIRO SCHIAVONIA</span>
			</li>
			<?php
			}
			?>

			<?php
			$payment_method = $order->get_payment_method_title();
			
			if ($payment_method === 'Pay Later'){
			?>
			<li>
			<strong>Pagamento:</strong>
			<span style="font-weight:bold;">PayPal in 3 rate</span>
			</li>
			<?php
			}
			?>

				<?php
				// Ottenere lo stato della richiesta di fattura
				$fattura_ricevuta = get_post_meta( $order->get_id(), 'fattura_ricevuta', true );

				// Verificare se è stata richiesta la fattura
				if ( $fattura_ricevuta && $fattura_ricevuta === 'SI' ) :
					?>
					<li>
						<strong><?php esc_attr_e( 'Richiesta Fattura', 'woocommerce-delivery-notes' ); ?></strong>
						<span style="font-weight:bold;"><?php esc_html_e( 'Sì', 'woocommerce-delivery-notes' ); ?></span>
					</li>
				<?php endif; ?>


				<?php
				// Ottenere lo stato della richiesta di pacco regalo
				$pacco_regalo = get_post_meta( $order->get_id(), 'pacco_regalo', true );

				// Verificare se è stata richiesta la confezione regalo
				if ( $pacco_regalo && $pacco_regalo === 'Sì' ) :
					?>
					<li>
						<strong><?php esc_attr_e( 'Confezione Regalo', 'woocommerce-delivery-notes' ); ?></strong>
						<span style="font-weight:bold;"><?php esc_html_e( 'Sì', 'woocommerce-delivery-notes' ); ?></span>
					</li>
				<?php endif; ?>


			
		</ul>

		<?php do_action( 'wcdn_after_info', $order ); ?>
	</div><!-- .order-info -->


	<div class="order-items">
		<table>
			<thead>
				<tr>
					<th class="head-name"><span><?php esc_attr_e( 'Product', 'woocommerce-delivery-notes' ); ?></span></th>
					<th class="head-item-price"><span><?php esc_attr_e( 'Price', 'woocommerce-delivery-notes' ); ?></span></th>
					<th class="head-quantity"><span><?php esc_attr_e( 'Quantity', 'woocommerce-delivery-notes' ); ?></span></th>
					<th class="head-price"><span><?php esc_attr_e( 'Total', 'woocommerce-delivery-notes' ); ?></span></th>
				</tr>
			</thead>

			<tbody>
				<?php

				if ( count( $order->get_items() ) > 0 ) :
					?>
					<?php foreach ( $order->get_items() as $item_id => $item ) : ?>

						<?php

						$product = apply_filters( 'wcdn_order_item_product', $item->get_product(), $item );
						if ( ! $product ) {
							continue;
						}
						if ( version_compare( get_option( 'woocommerce_version' ), '3.0.0', '>=' ) ) {
							$item_meta = new WC_Order_Item_Product( $item['item_meta'], $product );
						} else {
							$item_meta = new WC_Order_Item_Meta( $item['item_meta'], $product );
						}
						?>
						<tr>
							<td class="product-name">
								<?php do_action( 'wcdn_order_item_before', $product, $order, $item ); ?>
								<span class="name">
								<?php

								$addon_name  = $item->get_meta( '_wc_pao_addon_name', true );
								$addon_value = $item->get_meta( '_wc_pao_addon_value', true );
								$is_addon    = ! empty( $addon_value );

								if ( $is_addon ) { // Displaying options of product addon.
									$addon_html = '<div class="wc-pao-order-item-name">' . esc_html( $addon_name ) . '</div><div class="wc-pao-order-item-value">' . esc_html( $addon_value ) . '</div></div>';

									echo wp_kses_post( $addon_html );
								} else {

									$product_id   = $item['product_id'];
									$prod_name    = get_post( $product_id );
									$product_name = $prod_name->post_title;

									echo wp_kses_post( apply_filters( 'wcdn_order_item_name', $product_name, $item ) );
									?>
									</span>

									<?php
									$item_meta_fields = apply_filters( 'wcdn_product_meta_data', $item['item_meta'], $item );

									$product_addons            = array();
									$woocommerce_product_addon = 'woocommerce-product-addons/woocommerce-product-addons.php';
									if ( in_array( $woocommerce_product_addon, apply_filters( 'active_plugins', get_option( 'active_plugins', array() ) ), true ) ) {
										$product_id     = $item['product_id'];
										$product_addons = WC_Product_Addons_Helper::get_product_addons( $product_id );
									}
									if ( version_compare( get_option( 'woocommerce_version' ), '3.0.0', '>=' ) ) {
										if ( isset( $item['variation_id'] ) && 0 !== $item['variation_id'] ) {
											$variation = wc_get_product( $item['product_id'] );
											foreach ( $item_meta_fields as $key => $value ) {
												if ( ! ( 0 === strpos( $key, '_' ) ) ) {
													if ( is_array( $value ) ) {
														continue;
													}
													$term_wp        = get_term_by( 'slug', $value, $key );
													$attribute_name = wc_attribute_label( $key, $variation );
													if ( ! empty( $product_addons ) ) {
														foreach ( $product_addons as $addon ) {
															if ( 'file_upload' === $addon['type'] ) {
																if ( $key === $addon['name'] ) {
																	$value = wp_basename( $value );
																}
															}
														}
													}
													if ( isset( $term_wp->name ) ) {
														echo '<br>' . wp_kses_post( $attribute_name . ':' . $term_wp->name );
													} else {
														echo '<br>' . wp_kses_post( $attribute_name . ':' . $value );
													}
												}
											}
										} else {
											foreach ( $item_meta_fields as $key => $value ) {
												if ( ! ( 0 === strpos( $key, '_' ) ) ) {
													if ( is_array( $value ) ) {
														continue;
													}
													if ( ! empty( $product_addons ) ) {
														foreach ( $product_addons as $addon ) {
															if ( 'file_upload' === $addon['type'] ) {
																if ( $key === $addon['name'] ) {
																	$value = wp_basename( $value );
																}
															}
														}
													}
													echo '<br>' . wp_kses_post( $key . ':' . $value );
												}
											}
										}
									} else {
										$item_meta_new = new WC_Order_Item_Meta( $item_meta_fields, $product );
										$item_meta_new->display();

									}
									?>
									<br>
									<dl class="extras">
										<?php if ( $product && $product->exists() && $product->is_downloadable() && $order->is_download_permitted() ) : ?>

											<dt><?php esc_attr_e( 'Download:', 'woocommerce-delivery-notes' ); ?></dt>
											<dd>
											<?php
											// translators: files count.
											printf( esc_attr__( '%s Files', 'woocommerce-delivery-notes' ), count( $item->get_item_downloads() ) );
											?>
											</dd>

										<?php endif; ?>

										<?php
										wcdn_print_extra_fields( $item );
										$fields = apply_filters( 'wcdn_order_item_fields', array(), $product, $order, $item );

										foreach ( $fields as $field ) :
											?>

											<dt><?php echo esc_html( $field['label'] ); ?></dt>
											<dd><?php echo esc_html( $field['value'] ); ?></dd>

										<?php endforeach; ?>
									</dl>
								<?php } ?>
								<?php do_action( 'wcdn_order_item_after', $product, $order, $item ); ?>
							</td>
							<td class="product-item-price">
								<span><?php echo wp_kses_post( wcdn_get_formatted_item_price( $order, $item ) ); ?></span>
							</td>
							<td class="product-quantity">
								<span><?php echo esc_attr( apply_filters( 'wcdn_order_item_quantity', $item['qty'], $item ) ); ?></span>
							</td>
							<td class="product-price">
								<span><?php echo wp_kses_post( $order->get_formatted_line_subtotal( $item ) ); ?></span>
							</td>
						</tr>
					<?php endforeach; ?>
				<?php endif; ?>
			</tbody>

			<tfoot>
				<?php
				$totals_arr = $order->get_order_item_totals();
				if ( $totals_arr ) :

					foreach ( $totals_arr as $total ) :
						?>
						<tr>
							<td class="total-name"><span><?php echo wp_kses_post( $total['label'] ); ?></span></td>
							<td class="total-item-price"></td>
							<?php if ( 'Total' === $total['label'] ) { ?>
							<td class="total-quantity"><?php echo wp_kses_post( $order->get_item_count() ); ?></td>
							<?php } else {  ?>
							<td class="total-quantity"></td>
							<?php } ?>
							<td class="total-price"><span><?php echo wp_kses_post( $total['value'] ); ?></span></td>
						</tr>
					<?php endforeach; ?>
				<?php endif; ?>
			</tfoot>
		</table>

		<?php do_action( 'wcdn_after_items', $order ); ?>
	</div><!-- .order-items -->

	<div class="order-thanks">
		<?php wcdn_personal_notes(); ?>

		<?php do_action( 'wcdn_after_thanks', $order ); ?>
	</div><!-- .order-thanks -->

	<div class="order-colophon">
		<div class="colophon-policies">
			<?php wcdn_policies_conditions(); ?>
		</div>

		<div class="colophon-imprint">
			<?php wcdn_imprint(); ?>
		</div>	

		<?php do_action( 'wcdn_after_colophon', $order ); ?>
	</div><!-- .order-colophon -->


Senza categoria

EdiSES – Lista categorie

SELECT
  cce.entity_id AS category_id,
  ccev.value AS category_name,
  cce.parent_id,
  CASE
    WHEN cce.parent_id = 1 THEN 'Principale'
    ELSE 'Sottocategoria'
  END AS tipo_categoria,
  ccei.value AS is_active
FROM
  catalog_category_entity AS cce
  JOIN catalog_category_entity_varchar AS ccev ON cce.entity_id = ccev.entity_id
  JOIN eav_attribute AS ea ON ccev.attribute_id = ea.attribute_id
  AND ea.attribute_code = 'name'
  JOIN catalog_category_entity_int AS ccei ON cce.entity_id = ccei.entity_id
  JOIN eav_attribute AS eai ON ccei.attribute_id = eai.attribute_id
  AND eai.attribute_code = 'is_active'
WHERE
  ccev.store_id = 0
  AND ccei.value = 1
GROUP by
  category_id;