Senza categoria

Coupon – Edises

crea tabella con tutti i dati necessari

CREATE TABLE sconti_by_percent AS
SELECT
    sr.rule_id,
    sr.name AS rule_name,
    sr.description AS rule_description,
    sr.is_active AS rule_is_active,
    sr.simple_action,
    sr.conditions_serialized,
    sr.actions_serialized AS ACTION,
    sr.from_date,
    sr.to_date,
    sr.discount_amount,
    sr.uses_per_coupon,
    sr.uses_per_customer,
    src.coupon_id,
    src.code AS coupon_code,
    src.times_used AS coupon_times_used,
    src.expiration_date AS coupon_expiration_date
FROM
    salesrule sr
JOIN
    salesrule_coupon src ON sr.rule_id = src.rule_id
WHERE
    sr.simple_action = 'by_percent'
ORDER BY
    sr.rule_id;

sr.simple_action = by_percent, by_fixed, cart_fixed, ampromo_items

ALTER TABLE sconti_by_percent
ADD COLUMN attribute_value VARCHAR(255),
ADD COLUMN category_value TEXT;

--

UPDATE sconti_by_percent
SET attribute_value = JSON_UNQUOTE(JSON_EXTRACT(ACTION, '$.conditions[0].attribute')),
    category_value = JSON_UNQUOTE(JSON_EXTRACT(ACTION, '$.conditions[0].value'));

Per capire quanti coupon esistono per tipologia

SELECT
    simple_action,
    COUNT(*) AS rule_count
FROM
    salesrule
GROUP BY
    simple_action
ORDER BY
    rule_count DESC;

visualizzare la lista coupon, usare la clausula WHERE sr.simple_action = ” in combinazione con i risultati forniti dalla query precedente

SELECT
    sr.rule_id,
    sr.name AS rule_name,
    sr.description AS rule_description,
    sr.is_active AS rule_is_active,
    sr.simple_action,
    sr.conditions_serialized,
    src.coupon_id,
    src.code AS coupon_code,
    src.times_used AS coupon_times_used,
    src.expiration_date AS coupon_expiration_date
FROM
    salesrule sr
JOIN
    salesrule_coupon src ON sr.rule_id = src.rule_id
WHERE
    sr.simple_action = 'by_percent'
ORDER BY
    sr.rule_id;

Risorsa utile: https://chatgpt.com/c/bc009109-4fdc-4636-b64d-aa73a0796b9e

Estrarre entity_id dei vari attributi

SELECT attribute_value, COUNT(*) AS count
FROM sconti_by_percent
GROUP BY attribute_value;

In base alla regola che troviamo, ad esempio se hanno attributi, bisogna estrarli e trovare l’entity_id

SELECT entity_id 
FROM catalog_product_entity_int 
WHERE attribute_id = (SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'disalsingoli' AND entity_type_id = (SELECT entity_type_id FROM eav_entity_type WHERE entity_type_code = 'catalog_product'))
AND value = 1;

trovato l’entity_id bisogna importare la regola, in caso di eb_eserc_sost_anief  sappiamo che c’è uno sconto del 100% uso per coupon 1 su entity_id 1358, quindi vanno presi tutti i codici coupon nella tabella sconti_by_percent nel campo_coupon_code

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;

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

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 = 0 /* Gestione inventario non disponibile */
AND cpev_name.attribute_id = (SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'name' AND entity_type_id = 4)

vanno eliminati gli ebook