DELIMITER $$
CREATE OR REPLACE DEFINER=`vn-admin`@`localhost` PROCEDURE `vn`.`invoiceOutBooking`(IN vInvoice INT)
BEGIN
/**
 * Asienta una factura emitida
 *
 * @param vInvoice Id invoiceOut
 */
	DECLARE vBookNumber INT;
	DECLARE vExpenseConcept VARCHAR(50);
	DECLARE vSpainCountryFk INT;
	DECLARE vOldBookNumber INT;
	DECLARE vFiscalYear INT;

	SELECT id INTO vSpainCountryFk FROM country WHERE `code` = 'ES';

	SELECT ASIEN
			INTO vOldBookNumber
		FROM XDiario x
			JOIN invoiceOut io ON io.id = vInvoice
		WHERE x.SERIE = io.serial
			AND x.FACTURA = RIGHT(io.ref, LENGTH(io.ref) - 1)
		LIMIT 1;

	DELETE
		FROM XDiario
		WHERE ASIEN = vOldBookNumber;

	DROP TEMPORARY TABLE IF EXISTS rs;
	CREATE TEMPORARY TABLE rs
		SELECT c.accountingAccount clientBookingAccount,
				io.amount totalAmount,
				CONCAT('n/fra ', io.ref) simpleConcept,
				CONCAT('n/fra ', io.ref, ' ', c.name) Concept,
				io.serial SERIE,
				io.issued FECHA_EX,
				io.issued FECHA_OP,
				io.issued FECHA,
				1 NFACTICK,
				IF(ic.correctingFk,'D','') TIPOOPE,
				io.siiTrascendencyInvoiceOutFk TIPOCLAVE,
				io.cplusTaxBreakFk TIPOEXENCI,
				io.cplusSubjectOpFk TIPONOSUJE,
				io.siiTypeInvoiceOutFk TIPOFACT,
				ic.cplusRectificationTypeFk TIPORECTIF,
				io.companyFk,
				RIGHT(io.ref, LENGTH(io.ref) - 1) invoiceNum,
				IF(c.countryFk = vSpainCountryFk, vSpainCountryFk, IF(ct.isUeeMember,2,4)) TERIDNIF,
				CONCAT(IF(ct.isUeeMember AND c.countryFk <> vSpainCountryFk,ct.code,''),c.fi) TERNIF,
				c.socialName TERNOM,
				ior.serial SERIE_RT,
				RIGHT(ior.ref, LENGTH(ior.ref) - 1) FACTU_RT,
				ior.issued FECHA_RT,
				IF(ior.id,TRUE,FALSE) RECTIFICA
		FROM invoiceOut io
			JOIN invoiceOutSerial ios ON ios.code = io.serial
			JOIN client c ON c.id = io.clientFk
			JOIN country ct ON ct.id = c.countryFk
			LEFT JOIN invoiceCorrection ic ON ic.correctingFk = io.id
			LEFT JOIN invoiceOut ior ON ior.id = ic.correctedFk
			WHERE io.id = vInvoice;

	SELECT YEAR(FECHA) INTO vFiscalYear FROM rs LIMIT 1;
	CALL ledger_nextTx(vFiscalYear, vBookNumber);
	-- Linea del cliente
	INSERT INTO XDiario(
			ASIEN,
			FECHA,
			SUBCTA,
			EURODEBE,
			CONCEPTO,
			FECHA_EX,
			FECHA_OP,
			empresa_id)
		SELECT vBookNumber,
				rs.FECHA,
				rs.clientBookingAccount,
				rs.totalAmount,
				rs.simpleConcept,
				rs.FECHA_EX,
				rs.FECHA_OP,
				rs.companyFk
			FROM rs;

		-- Lineas de gasto
		INSERT INTO XDiario(
				ASIEN,
				FECHA,
				SUBCTA,
				CONTRA,
				EUROHABER,
				CONCEPTO, 
				FECHA_EX,
				FECHA_OP,
				empresa_id)
			SELECT vBookNumber,
					rs.FECHA,
					ioe.expenseFk,
					rs.clientBookingAccount,
					ioe.amount,
					rs.Concept,
					rs.FECHA_EX,
					rs.FECHA_OP,
					rs.companyFk
				FROM rs
					JOIN invoiceOutExpense ioe
				WHERE ioe.invoiceOutFk = vInvoice;

	SELECT GROUP_CONCAT(`name` SEPARATOR ',') 
			INTO vExpenseConcept 
		FROM expense e
			JOIN invoiceOutExpense ioe ON ioe.expenseFk = e.id
		WHERE ioe.invoiceOutFk = vInvoice;

	-- Lineas de IVA
	INSERT INTO XDiario(
			ASIEN,
			FECHA,
			SUBCTA,
			CONTRA,
			EUROHABER,
			BASEEURO,
			CONCEPTO,
			FACTURA,
			IVA,
			RECEQUIV,
			AUXILIAR,
			SERIE,
			SERIE_RT,
			FACTU_RT,
			RECTIFICA,
			FECHA_RT,
			FECHA_OP,
			FECHA_EX,
			TIPOOPE,
			NFACTICK,
			TERIDNIF,
			TERNIF,
			TERNOM,
			L340,
			TIPOCLAVE,
			TIPOEXENCI,
			TIPONOSUJE,
			TIPOFACT,
			TIPORECTIF,
			empresa_id)
		SELECT vBookNumber ASIEN,
				rs.FECHA,
				iot.pgcFk SUBCTA,
				rs.clientBookingAccount CONTRA,
				iot.vat EUROHABER,
				iot.taxableBase BASEEURO,
				CONCAT(vExpenseConcept,' : ',rs.Concept) CONCEPTO,
				rs.invoiceNum FACTURA,
				IF(pe2.equFk,0,pgc.rate) IVA,
				IF(pe2.equFk,0,pgce.rate) RECEQUIV,
				IF(pgc.mod347,'','*') AUXILIAR,
				rs.SERIE,
				rs.SERIE_RT,
				rs.FACTU_RT,
				rs.RECTIFICA,
				rs.FECHA_RT,
				rs.FECHA_OP,
				rs.FECHA_EX,
				rs.TIPOOPE,
				rs.NFACTICK,
				rs.TERIDNIF,
				rs.TERNIF,
				rs.TERNOM,
				pgc.mod340 L340,
				pgc.siiTrascendencyInvoiceOutFk TIPOCLAVE,
				pgc.cplusTaxBreakFk TIPOEXENCI,
				rs.TIPONOSUJE,
				rs.TIPOFACT,
				rs.TIPORECTIF,
				rs.companyFk
			FROM rs
				JOIN invoiceOutTax iot 
				JOIN pgc ON pgc.code = iot.pgcFk
				LEFT JOIN pgcEqu pe ON pe.vatFk = iot.pgcFk		-- --------------- Comprueba si la linea es de iva con rec.equiv. asociado
				LEFT JOIN pgc pgce ON pgce.code = pe.equFk 
				LEFT JOIN pgcEqu pe2 ON pe2.equFk = iot.pgcFk	-- --------------- Comprueba si la linea es de rec.equiv.
			WHERE iot.invoiceOutFk = vInvoice;
		
		UPDATE invoiceOut
			SET booked = util.VN_CURDATE()
			WHERE id = vInvoice;
END$$
DELIMITER ;
