DROP procedure IF EXISTS `vn`.`duaTaxBooking`;

DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`duaTaxBooking`(vDuaFk INT)
BEGIN
	DECLARE vBookNumber INT;
    DECLARE vBookDated DATE;
    DECLARE vDiff DECIMAL(10,2);
    DECLARE vApunte BIGINT;
    
	SELECT IFNULL(d.ASIEN,MAX(x.ASIEN) + 1 )
		INTO vBookNumber
		FROM XDiario x
			LEFT JOIN dua d ON d.id = vDuaFk ;
    
    SELECT IFNULL(bookEntried, CURDATE()) INTO vBookDated
		FROM dua
        WHERE id = vDuaFk;
    
	-- Apunte de la aduana

	INSERT INTO XDiario(
		ASIEN,
		FECHA,
		SUBCTA,
		CONCEPTO, 
		EUROHABER,
        SERIE,
		empresa_id,
        CLAVE,
        FACTURA)

	SELECT 
			vBookNumber,
			d.bookEntried,
			'4700000999',
			CONCAT('DUA ',d.code),
			sum(di.amount * tr.rate / 100) EUROHABER,
            'R',
			d.companyFk,
            vDuaFk,
            vDuaFk
		FROM duaIntrastat di
			JOIN intrastat ist ON ist.id = di.intrastatFk
            JOIN (SELECT rate, taxClassFk
					FROM
						(SELECT rate, taxClassFk
							FROM invoiceInTaxBookingAccount ta
                            WHERE ta.effectived <= vBookDated
                            ORDER BY ta.effectived DESC
						) tba
					GROUP BY taxClassFk
                  ) tr ON tr.taxClassFk = ist.taxClassFk          
			JOIN dua d ON d.id = di.duaFk
            WHERE di.duaFk = vDuaFk;
            
        -- Apuntes por tipo de IVA y proveedor
        
		INSERT INTO XDiario(
		ASIEN,
		FECHA,
		SUBCTA,
		CONTRA, 
		EURODEBE,
		BASEEURO,
		CONCEPTO, 
		FACTURA, 
		IVA,
		AUXILIAR, 
		SERIE,
		FECHA_EX,
		FECHA_OP,
		FACTURAEX,
		NFACTICK,
		L340,
		LDIFADUAN,
		TIPOCLAVE,
		TIPOEXENCI,
		TIPONOSUJE,
		TIPOFACT,
		TIPORECTIF,
		TERIDNIF,
		TERNIF,
		TERNOM,
		empresa_id,
		FECREGCON
	)

	SELECT 
			vBookNumber ASIEN,
			vBookDated FECHA,
			tr.account SUBCTA,
			'4330002067' CONTRA,
			sum(dt.tax) EURODEBE,
			sum(dt.base) BASEEURO, 
			CONCAT('DUA nº',d.code) CONCEPTO,
			d.id FACTURA,
			dt.rate IVA,
			'*' AUXILIAR, 
			'D' SERIE,
			d.issued FECHA_EX,
			d.operated FECHA_OP,
			d.code FACTURAEX,
			1 NFACTICK,
			1 L340,
			TRUE LDIFADUAN,
			1 TIPOCLAVE,
			1 TIPOEXENCI,
			1 TIPONOSUJE,
			5 TIPOFACT,
			1 TIPORECTIF,
			IF(s.countryFk IN (30, 1), 1, 4) TERIDNIF,
			s.nif TERNIF,
			s.name TERNOM,
			d.companyFk,
			d.booked FECREGCON
		FROM duaTax dt
			JOIN dua d ON dt.duaFk = d.id
            JOIN (SELECT account, rate
					FROM
						(SELECT rate, account
							FROM invoiceInTaxBookingAccount ta
                            WHERE ta.effectived <= vBookDated
                            AND taxAreaFk = 'WORLD'
                            ORDER BY ta.effectived DESC
						) tba
					GROUP BY rate
                  ) tr ON tr.rate = dt.rate 
			JOIN supplier s ON s.id = d.companyFk
		WHERE d.id = vDuaFk
        GROUP BY dt.rate;

	SELECT SUM(EURODEBE) -SUM(EUROHABER), MAX(id) INTO vDiff, vApunte
		FROM XDiario
		WHERE ASIEN = vBookNumber;
     
	UPDATE XDiario
		SET BASEEURO = 100 * (EURODEBE - vDiff) / IVA,
			EURODEBE = EURODEBE - vDiff			
		WHERE id = vApunte;
    
    UPDATE dua
		SET ASIEN = vBookNumber
        WHERE id = vDuaFk;
            
END$$

DELIMITER ;

