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

DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`invoiceOutBooking`(IN vInvoice INT)
BEGIN
/* Asienta la factura emitida
*
* param vInvoice factura_id
*/
	DECLARE vBookNumber INT;
    DECLARE vExpenceConcept VARCHAR(50);
    DECLARE vIsUeeMember BOOL DEFAULT TRUE;
    DECLARE vSpainCountryFk INT;
    DECLARE vOldBookNumber 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 AS clientBookingAccount,
				io.amount as totalAmount,
				CONCAT('n/fra ', io.ref) as simpleConcept,
				CONCAT('n/fra ', io.ref, ' ', c.name) as Concept,
				io.serial AS SERIE,
				io.issued AS FECHA_EX,
				opDate.FECHA_OP,
				io.issued AS FECHA,
				1 AS NFACTICK,
				IF(ic.correctingFk,'D','') AS  TIPOOPE,
				io.cplusTrascendency477Fk AS TIPOCLAVE,
				io.cplusTaxBreakFk AS TIPOEXENCI,
				io.cplusSubjectOpFk AS TIPONOSUJE,
				io.cplusInvoiceType477Fk AS TIPOFACT,
				ic.cplusRectificationTypeFk AS TIPORECTIF,
				io.companyFk,
				RIGHT(io.ref, LENGTH(io.ref) - 1) AS invoiceNum,
                IF(ct.politicalCountryFk = vSpainCountryFk, vSpainCountryFk, IF(ct.isUeeMember = vIsUeeMember,2,4)) AS TERIDNIF,
				CONCAT(IF(ct.isUeeMember = vIsUeeMember,ct.code,''),c.fi) AS TERNIF,
				c.socialName AS TERNOM,
                ior.serial AS SERIE_RT,
                RIGHT(ior.ref, LENGTH(ior.ref) - 1) AS FACTU_RT,
                ior.issued AS FECHA_RT,
                IF(ior.id,TRUE,FALSE) AS RECTIFICA
		FROM invoiceOut io
			JOIN (	
					SELECT GREATEST(MAX(shipped), TIMESTAMPADD(DAY,-15,io.issued)) as FECHA_OP 
						FROM ticket t
							JOIN invoiceOut io ON io.ref = t.refFk
						WHERE io.id = vInvoice ) opDate
			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 MAX(ASIEN) + 1 
			INTO vBookNumber
		FROM XDiario;
    
	-- Linea del cliente
	INSERT INTO XDiario(
								ASIEN,
								FECHA,
								SUBCTA,              
								EURODEBE,
								CONCEPTO, 
								FECHA_EX,
								FECHA_OP,
								empresa_id
								)
		SELECT 
				vBookNumber AS ASIEN,
				rs.FECHA,
				rs.clientBookingAccount AS SUBCTA,
				rs.totalAmount AS EURODEBE,
				rs.simpleConcept AS CONCEPTO,
				rs.FECHA_EX,
				rs.FECHA_OP,
				rs.companyFk AS empresa_id
			FROM rs;

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

    SELECT GROUP_CONCAT(`name` SEPARATOR ',') 
            INTO vExpenceConcept 
        FROM expence e
            JOIN invoiceOutExpence ioe ON ioe.expenceFk = 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 AS ASIEN,
				rs.FECHA,
				iot.pgcFk AS SUBCTA,
				rs.clientBookingAccount AS CONTRA,
				iot.vat AS EUROHABER,
				iot.taxableBase AS BASEEURO,
				CONCAT(vExpenceConcept,' : ',rs.Concept) AS CONCEPTO,
				rs.invoiceNum AS FACTURA,
                IF(pe2.equFk,0,pgc.rate) AS IVA,
				IF(pe2.equFk,0,pgce.rate) AS RECEQUIV,
				IF(pgc.mod347,'','*') AS 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 AS L340,   
				pgc.cplusTrascendency477Fk AS TIPOCLAVE,
				pgc.cplusTaxBreakFk as TIPOEXENCI,
				rs.TIPONOSUJE,
				rs.TIPOFACT,
				rs.TIPORECTIF,
				rs.companyFk AS empresa_id
			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 = CURDATE()
                WHERE id = vInvoice;
END$$
DELIMITER ;

