DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `sage`.`importErrorNotification`()
BEGIN
/**
 * Inserta notificaciones con los errores detectados durante la importación
 * 
 */
	DECLARE vBookEntries TEXT;

	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
		RESIGNAL;
	END;

	SELECT GROUP_CONCAT(error SEPARATOR ' ') INTO vBookEntries
		FROM(
			SELECT CONCAT('- Importes: ', sub.Asiento) error
				FROM (SELECT mc.Asiento, SUM(mc.ImporteAsiento) amount
						FROM movConta mc
						WHERE mc.enlazadoSage = FALSE
						GROUP BY mc.Asiento)sub
					JOIN (SELECT x.ASIEN, SUM(IFNULL(x.EURODEBE,0) + IFNULL(x.EUROHABER,0)) amount
							FROM vn.XDiario x
								WHERE x.enlazadoSage = FALSE
							GROUP BY ASIEN)sub2 ON sub2.ASIEN = sub.Asiento
			WHERE sub.amount <> sub2.amount
			UNION ALL
			SELECT CONCAT('- Base imponible: ', sub.Asiento)
				FROM (SELECT Asiento, SUM(BaseIva1 + BaseIva2 + BaseIva3 + BaseIva4) amountTaxableBase
						FROM movConta
						WHERE TipoFactura <> 'I'
							AND enlazadoSage = FALSE
						GROUP BY Asiento) sub
					JOIN (SELECT ASIEN, SUM(BASEEURO) amountTaxableBase
							FROM (SELECT ASIEN, SUM(BASEEURO) BASEEURO
									FROM vn.XDiario
									WHERE FACTURA
										AND auxiliar <> '*'
										AND enlazadoSage = FALSE
									GROUP BY FACTURA, ASIEN)sub3
							GROUP BY ASIEN) sub2 ON sub2.ASIEN = sub.Asiento
				WHERE sub.amountTaxableBase<>sub2.amountTaxableBase
					AND sub.amountTaxableBase/2 <> sub2.amountTaxableBase
			UNION ALL
			SELECT CONCAT('- Factura Duplicada: ', accountingEntryFk)
				FROM accountingEntryError
		)sub;

	IF vBookEntries IS NOT NULL THEN
		START TRANSACTION;

		SELECT util.notification_send ("book-entries-imported-incorrectly", 
			CONCAT('{"bookEntries":"', vBookEntries,'"}'), 
			null);
		
		TRUNCATE accountingEntryError;
		
		COMMIT;
	END IF;
END$$
DELIMITER ;
