DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`duaInvoiceInBooking`(vDuaFk INT)
BEGIN
/**
 * Genera el asiento de un DUA y marca las entradas como confirmadas
 *
 * @param vDuaFk Id del dua a recalcular
 */
	DECLARE done BOOL DEFAULT FALSE;
	DECLARE vInvoiceFk INT;
	DECLARE vASIEN BIGINT DEFAULT 0;
	DECLARE vCounter INT DEFAULT 0;

	DECLARE rs CURSOR FOR
		SELECT DISTINCT e.invoiceInFk
			FROM entry e
				JOIN duaEntry de ON de.entryFk = e.id
				JOIN invoiceIn ii ON ii.id = e.invoiceInFk
			WHERE de.duaFk = vDuaFk
				AND de.customsValue
				AND ii.isBooked = FALSE;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

	OPEN rs;

	UPDATE invoiceIn ii
			JOIN entry e ON e.invoiceInFk = ii.id
			JOIN duaEntry de ON de.entryFk = e.id
			JOIN dua d ON d.id = de.duaFk
		SET ii.booked = IFNULL(ii.booked, d.booked),
			ii.operated = IFNULL(ii.operated, d.operated),
			ii.issued = IFNULL(ii.issued, d.issued),
			ii.bookEntried = IFNULL(ii.bookEntried, d.bookEntried),
			e.isBooked = TRUE,
			e.isConfirmed = TRUE
		WHERE d.id = vDuaFk;

	SELECT IFNULL(ASIEN,0) INTO vASIEN
		FROM dua
			WHERE id = vDuaFk;

	FETCH rs INTO vInvoiceFk;

	WHILE NOT done DO

		CALL invoiceIn_booking(vInvoiceFk);

		IF vCounter > 0 OR vASIEN > 0 THEN

			UPDATE XDiario x
				JOIN ledgerConfig lc ON lc.lastBookEntry = x.ASIEN
				SET x.ASIEN = vASIEN;

		ELSE

			SELECT lastBookEntry INTO vASIEN FROM ledgerConfig;

		END IF;

		SET vCounter = vCounter + 1;

		FETCH rs INTO vInvoiceFk;

	END WHILE;

	CLOSE rs;

	UPDATE dua
		SET ASIEN = vASIEN
		WHERE id = vDuaFk;

	UPDATE invoiceIn ii
			JOIN duaInvoiceIn dii ON dii.invoiceInFk = ii.id
		SET ii.isBooked = TRUE
		WHERE dii.duaFk = vDuaFk;
END$$
DELIMITER ;
