DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ledger_doCompensation`(
	vDated DATE, 
	vCompensationAccount VARCHAR(10), 
	vBankFk VARCHAR(10), 
	vConcept VARCHAR(255), 
	vAmount DECIMAL(10,2), 
	vCompanyFk INT, 
	vOriginalAccount VARCHAR(10)
)
BEGIN
/**
 * Compensa un pago o un recibo insertando en contabilidad
 *
 * @param vDated fecha en la cual se anota
 * @param vCompensationAccount cuenta contable contra la que se compensa
 * @param vBankFk banco de la compensacion
 * @param vConcept descripcion
 * @param vAmount cantidad que se compensa
 * @param vCompanyFk empresa
 * @param vOriginalAccount cuenta contable desde la cual se compensa 
 * 
 */ 
	DECLARE vNewBookEntry INT;
	DECLARE vIsClientCompensation INT;
	DECLARE vClientFk INT;
	DECLARE vSupplierFk INT;
	DECLARE vIsOriginalAClient BOOL;
	DECLARE vPayMethodCompensation INT;

	CALL ledger_next(YEAR(vDated), FALSE, vNewBookEntry);

	SELECT COUNT(id) INTO vIsOriginalAClient 
		FROM client 
		WHERE accountingAccount LIKE vOriginalAccount COLLATE utf8_general_ci;

	SELECT id, COUNT(id) INTO vClientFk, vIsClientCompensation 
		FROM client 
		WHERE accountingAccount LIKE vCompensationAccount COLLATE utf8_general_ci;

	SET @vAmount1:= 0.0;
	SET @vAmount2:= 0.0;

	INSERT INTO XDiario (ASIEN, FECHA, SUBCTA, CONTRA, CONCEPTO, EURODEBE, EUROHABER, empresa_id) 
		VALUES ( 	vNewBookEntry, 
					vDated, 
					vOriginalAccount, 
					vCompensationAccount, 
					vConcept, 
					@vAmount1:= IF(
						(vIsOriginalAClient AND vAmount > 0) OR 
						(NOT vIsOriginalAClient AND vAmount < 0), 
						0, 
						ABS(vAmount)
					),
					@vAmount2:= IF(@vAmount1,
						0,
						ABS(vAmount)
					),
					vCompanyFk
				),
				(	vNewBookEntry, 
					vDated, 
					vCompensationAccount, 
					vOriginalAccount, 
					vConcept, 
					@vAmount2,
					@vAmount1,
					vCompanyFk);

	IF vIsClientCompensation THEN
		IF vIsOriginalAClient THEN
			SET vAmount = -vAmount;
		END IF;
		
		INSERT INTO receipt
			SET invoiceFk = vConcept, 
				amountPaid = vAmount, 
				payed = vDated, 
				bankFk = vBankFk, 
				companyFk = vCompanyFk, 
				clientFk = vClientFk, 
				isConciliate = TRUE;
	ELSE
		IF NOT vIsOriginalAClient THEN
			SET vAmount = -vAmount;
		END IF;

		SELECT id INTO vSupplierFk 
			FROM supplier 
			WHERE `account` LIKE vCompensationAccount COLLATE utf8_general_ci;

		SELECT id INTO vPayMethodCompensation 
			FROM payMethod 
			WHERE `code` = 'compensation';

		INSERT INTO payment 
			SET received = vDated, 
				dueDated = vDated, 
				supplierFk = vSupplierFk,
				amount = vAmount,
				bankFk = vBankFk,
				payMethodFk = vPayMethodCompensation, 
				concept = vConcept,
				companyFk = vCompanyFk,
				isConciliated = TRUE;
	END IF;
END$$
DELIMITER ;
