DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `hedera`.`tpvTransaction_confirm`(
	 vAmount INT
	,vOrder INT
	,vMerchant INT
	,vCurrency INT
	,vResponse INT
    ,vErrorCode VARCHAR(10)
)
BEGIN
/**
 * Confirma una transacción previamente iniciada, reescribiendo
 * sus datos por los confirmados por el banco (solo si estos difieren).
 * Genera el recibo y su correspondiente entrada en caja.
 *
 * @param vAmount Cantidad confirmada
 * @param vOrder Identificador de transacción
 * @param vMerchant Identificador de comercio
 * @param vCurrency Identificador de moneda
 * @param vResponse Identificador de respuesta del banco
 * @param vErrorCode Código de error del banco, si lo hubiera
 */
	DECLARE vReceipt INT;
	DECLARE vStatus VARCHAR(10);
	DECLARE vCustomer INT;
	DECLARE vBank INT;
	DECLARE vCompany INT;
	DECLARE vEmployee INT;
	DECLARE vIsDuplicated BOOLEAN;
	DECLARE vDate DATE;
	DECLARE vConcept VARCHAR(25) DEFAULT 'Cobro Web';

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

	START TRANSACTION;

	SELECT COUNT(*) > 0 INTO vIsDuplicated
		FROM tpvTransaction
		WHERE id = vOrder AND response IS NOT NULL
		FOR UPDATE;

	IF vIsDuplicated THEN
		CALL util.throw('Transaction already confirmed');
	END IF;

	IF vResponse BETWEEN 0 AND 99 THEN
		SELECT
			 t.clientFk
			,m.bankFk
			,m.companyFk
			,c.employeeFk
			,DATE(t.created)
		INTO
			 vCustomer
			,vBank
			,vCompany
			,vEmployee
			,vDate
			FROM tpvMerchant m
				JOIN tpvConfig c
				LEFT JOIN tpvTransaction t ON t.id = vOrder
			WHERE m.id = vMerchant;

		INSERT INTO vn.receipt
		SET
			 amountPaid = vAmount / 100
			,payed = vDate
			,workerFk = vEmployee
			,bankFk = vBank
			,clientFk = vCustomer
			,companyFk = vCompany
			,invoiceFk = vConcept
            ,isConciliate = TRUE;

		SET vReceipt = LAST_INSERT_ID();
		SET vStatus = 'ok';

		-- Código redundante

		DO vn.till_new(
			 vCustomer
			,vBank
			,vAmount / 100
			,vConcept
			,vDate
			,'A'
			,TRUE
			,vCustomer
			,vCompany
			,vEmployee
		);
	ELSE
		SET vReceipt = NULL;
		SET vStatus = 'ko';
	END IF;

	UPDATE tpvTransaction
		SET merchantFk = vMerchant
			,receiptFk = vReceipt
			,amount = vAmount
			,response = vResponse
	        ,errorCode = vErrorCode
			,status = vStatus
		WHERE id = vOrder;

	COMMIT;
END$$
DELIMITER ;
