DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`duaTaxBooking`(vDuaFk INT)
BEGIN
	DECLARE vBookNumber INT;
	DECLARE vBookDated DATE;
	DECLARE vDiff DECIMAL(10,2);
	DECLARE vApunte BIGINT;
	
	SELECT ASIEN, IFNULL(bookEntried, util.VN_CURDATE())
			INTO vBookNumber, vBookDated
		FROM dua
		WHERE id = vDuaFk;

	IF vBookNumber IS NULL OR NOT vBookNumber THEN
		CALL ledger_next(YEAR(vBookDated), vBookNumber);
	END IF;

	-- 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(dt.base * dt.rate / 100) EUROHABER,
				'R',
				d.companyFk,
				vDuaFk,
				vDuaFk
			FROM duaTax dt
				JOIN dua d ON d.id = dt.duaFk
				WHERE dt.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(c.code = 'ES', 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
								LIMIT 10000000000000000000 
							) tba
						GROUP BY rate
					) tr ON tr.rate = dt.rate 
				JOIN supplier s ON s.id = d.companyFk
				JOIN country c ON c.id = s.countryFk
			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 ;
