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' );


?>