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

DELIMITER $$
$$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`invoiceOutMake`(
	vSerial VARCHAR(255),
	vInvoiceDate DATETIME,
	OUT vNewInvoiceId INT)
BEGIN

/* Creación de facturas emitidas. 
* REQUIERE previamente tabla ticketToInvoice.
*
* @param vSerial, vInvoiceDate, vCompany, vClient
*
* @return vNewInvoiceId
*/
	
    DECLARE vSpainCountryCode INT DEFAULT 1;
	DECLARE vIsAnySaleToInvoice BOOL;
	DECLARE vCountry TINYINT DEFAULT 1;
	DECLARE vNewRef VARCHAR(255);
	DECLARE vWorker INT DEFAULT vn.getWorker();
    DECLARE vCompany INT;
	DECLARE vClient INT;
	DECLARE vCplusStandardInvoiceTypeFk INT DEFAULT 1;
    DECLARE vCplusCorrectingInvoiceTypeFk INT DEFAULT 6;
	DECLARE vCplusSimplifiedInvoiceTypeFk INT DEFAULT 2;
    DECLARE vCorrectingSerial VARCHAR(1) DEFAULT 'R';
	DECLARE vSimplifiedSerial VARCHAR(1) DEFAULT 'S';
    
	SET vInvoiceDate = IFNULL(vInvoiceDate,CURDATE());

	SELECT t.clientFk, t.companyFk
			INTO vClient, vCompany
		FROM ticketToInvoice tt
			JOIN ticket t ON t.id = tt.id
            LIMIT 1;
	
	-- Elimina tickets sense moviments
/*	UPDATE ticket t 
            JOIN ticketToInvoice ti ON ti.id = t.id 
            LEFT JOIN sale s ON s.ticketFk = ti.id
            LEFT JOIN expedition e ON e.ticketFk = t.id
            LEFT JOIN ticketPackaging tp ON tp.ticketFk = t.id
        SET t.shipped = '2000-02-01 00:00:00'
        WHERE s.ticketFk IS NULL AND e.ticketFk IS NULL AND e.ticketFk IS NULL;
*/
    -- Eliminem de ticketToInvoice els tickets que no han de ser facturats
	DELETE ti.* 
        FROM ticketToInvoice ti 
            JOIN ticket t ON t.id = ti.id
            JOIN client c ON c.id = t.clientFk
        WHERE YEAR(t.shipped) < 2001
			OR c.isTaxDataChecked = FALSE;

    SELECT SUM(quantity * price * (100 - discount)/100)
            INTO vIsAnySaleToInvoice
        FROM sale s 
            JOIN ticketToInvoice t on t.id = s.ticketFk;

	IF vIsAnySaleToInvoice THEN
		
        -- el trigger añade el siguiente Id_Factura correspondiente a la vSerial
		   -- el trigger añade el siguiente Id_Factura correspondiente a la vSerial
		INSERT INTO invoiceOut
		(
			ref,
			serial,
			issued,
			clientFk,
			dued,
			companyFk,
            cplusInvoiceType477Fk
		)
		SELECT 
				1,
				vSerial,
				vInvoiceDate,
				vClient,
				getDueDate(vInvoiceDate, dueDay),
				vCompany,
                IF(vSerial = vCorrectingSerial, 
					vCplusCorrectingInvoiceTypeFk, 
					IF(vSerial = vSimplifiedSerial,
						vCplusSimplifiedInvoiceTypeFk,
						vCplusStandardInvoiceTypeFk))
            FROM client
            WHERE id = vClient;


		SET vNewInvoiceId = LAST_INSERT_ID();
        
		SELECT ref
				INTO vNewRef 
			FROM invoiceOut
			WHERE id = vNewInvoiceId;

		UPDATE ticket t
    			JOIN ticketToInvoice ti ON ti.id = t.id
        	SET t.refFk = vNewRef;

		DROP TEMPORARY TABLE IF EXISTS tmp.updateInter;
        CREATE TEMPORARY TABLE tmp.updateInter ENGINE = MEMORY
			SELECT s.id,ti.id ticket_id,vWorker Id_Trabajador 
				FROM ticketToInvoice ti
					LEFT JOIN vn.ticketState ts ON ti.id = ts.ticket
                    JOIN state s 
				WHERE IFNULL(ts.alertLevel,0) < 3 and s.`code` = vn.getAlert3State(ti.id);
	
		INSERT INTO vncontrol.inter(state_id,Id_Ticket,Id_Trabajador)
			SELECT * FROM tmp.updateInter;
            

		INSERT INTO ticketLog (action, userFk,originFk, description) 
			SELECT 'UPDATE',account.userGetId(),ti.id, CONCAT('Crea factura ',vNewRef)
				FROM ticketToInvoice ti;

		CALL invoiceExpenceMake(vNewInvoiceId);
		CALL invoiceTaxMake(vNewInvoiceId,vCountry);
		
		UPDATE invoiceOut io
				JOIN (
					SELECT SUM(amount) AS total
						FROM invoiceOutExpence 
						WHERE invoiceOutFk = vNewInvoiceId
					) base
				JOIN (
					SELECT SUM(vat) AS total
						FROM invoiceOutTax 
						WHERE invoiceOutFk = vNewInvoiceId
					) vat
			SET io.amount = base.total + vat.total
			WHERE io.id = vNewInvoiceId;
		
	END IF;
    
	DROP TEMPORARY TABLE `ticketToInvoice`;
END$$

DELIMITER ;
