ALTER PROCEDURE [dbo].[CP_Cbtes_Confirmar_Online] @LOTE VARCHAR(20)
AS 

DECLARE @Mensaje			VARCHAR(100)

BEGIN TRY
	DECLARE @trans_rec INTEGER,@trans_ND INT,@LoteND VARCHAR(20),@LoteRec VARCHAR(20),@Saldo DECIMAL(12,2)
	SET @LoteND = 'VW:' + @LOTE
	SET @LoteRec = 'CW:' + @LOTE


	BEGIN TRAN


	SET @trans_ND = ISNULL((SELECT MAX(Id_trans) FROM Cbtes WHERE LOTE = @LoteND AND Id_Estado_Cbte = 0),0)
	IF (@trans_ND = 0)
	BEGIN
	    SET @Mensaje = 'No hay trans de Factura'
		PRINT @Mensaje
	END
	ELSE
	BEGIN
		PRINT @trans_ND
		UPDATE Cbtes SET Id_Estado_Cbte = 2,Saldo = 0			WHERE Id_Trans = @trans_ND
		UPDATE Cbtes_Items SET Id_Estado_Cbte = 2				WHERE Id_Trans = @trans_ND
		UPDATE Clientes_CtaCte SET Id_Estado_Cbte = 2,Saldo = 0 WHERE Id_Trans = @trans_ND
	END

	SET @trans_rec = ISNULL((SELECT MAX(Id_trans) FROM Cbtes WHERE LOTE = @LoteRec AND Id_Estado_Cbte = 0),0)
	IF (@trans_rec = 0)
	BEGIN
	    SET @Mensaje = 'No hay trans de recibo'
		PRINT @Mensaje
	END
	ELSE
	BEGIN
	    DECLARE @Id_Estado_Cbte SMALLINT
		SET @Id_Estado_Cbte = 2
		SET @Saldo			= 0

		PRINT @trans_rec
		IF @trans_ND = 0
		BEGIN
			SET @Id_Estado_Cbte = 1
			SET @Saldo			= (SELECT Imp_Total FROM Cbtes WHERE Id_Trans = @trans_rec)
		END
		

		UPDATE Cbtes			SET Id_Estado_Cbte = @Id_Estado_Cbte,Saldo = @Saldo WHERE Id_Trans = @trans_rec
		UPDATE Cbtes_Items		SET Id_Estado_Cbte = @Id_Estado_Cbte WHERE Id_Trans = @trans_rec
		UPDATE Clientes_CtaCte	SET Id_Estado_Cbte = @Id_Estado_Cbte,Saldo = @Saldo * -1 WHERE Id_Trans = @trans_rec

		UPDATE Cajas_Mov		SET Id_Estado_Mov_Caja = 2 WHERE Id_Trans = @trans_rec  --en siempre va en completo.
	END

	COMMIT

	SELECT	 0					AS ErrorNumber 
			,0					AS ErrorSeverity  
			,0					AS ErrorState 
			,0					AS ErrorProcedure  
			,0					AS ErrorLine		
			,@Mensaje			AS ErrorMessage
			,@trans_ND			AS Id_Trans_Fac
			,@trans_rec			AS Id_Trans_Rec

END TRY  


BEGIN CATCH  
    EXECUTE usp_GetErrorInfo;  
	ROLLBACK
END CATCH;   
