USE [FastMoneyPro_Remit]
GO
/****** Object:  StoredProcedure [dbo].[EXCHANGE_PROC_CURRENCYRATE_SETUP]    Script Date: 7/4/2019 11:35:48 AM ******/
DROP PROCEDURE [dbo].[EXCHANGE_PROC_CURRENCYRATE_SETUP]
GO
/****** Object:  StoredProcedure [dbo].[EXCHANGE_PROC_CURRENCYRATE_SETUP]    Script Date: 7/4/2019 11:35:48 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[EXCHANGE_PROC_CURRENCYRATE_SETUP]
      @flag                             VARCHAR(50)  = NULL
     ,@user                             VARCHAR(30)  = NULL
     ,@currencyRateId                   VARCHAR(30)  = NULL
     ,@baseCurrency                     CHAR(3)      = NULL
     ,@quoteCurrency                    CHAR(3)      = NULL
     ,@fixedCurUnit                     MONEY        = NULL
     ,@revRate                          FLOAT        = NULL
     ,@buyRate                          FLOAT        = NULL
     ,@buyTolerancePlus                 FLOAT        = NULL
     ,@buyToleranceMinus                FLOAT        = NULL
     ,@saleRate                         FLOAT        = NULL
     ,@saleTolerancePlus                FLOAT        = NULL
     ,@saleToleranceMinus               FLOAT        = NULL
     ,@active							CHAR(1)		 = NULL
     ,@agentId							VARCHAR(30)	 = NULL
     ,@sortBy							VARCHAR(50)	 = NULL
	 ,@sortOrder						VARCHAR(5)	 = NULL
	 ,@pageSize							INT			 = NULL
	 ,@pageNumber						INT			 = NULL


AS
SET NOCOUNT ON
SET XACT_ABORT ON 
BEGIN TRY
	
    IF @flag = 'i'
     BEGIN	 
	
	 IF EXISTS(select 'A' from currencyMaster (NOLOCK) where (isnull(rateMin,0) =0 or isnull(rateMax,0)=0 )AND currencyCode = @baseCurrency)
	 BEGIN
		SELECT  '1' errorCode,'MIN and MAX rate not defined for currency :' + @quoteCurrency MSG ,null id
		RETURN
	 END	 
	 
	 IF @buyToleranceMinus IS NULL
		SET @buyToleranceMinus = 0
	IF @buyTolerancePlus IS NULL
		SET @buyTolerancePlus = 0
	
	IF @saleToleranceMinus IS NULL
		SET @saleToleranceMinus = 0
	IF @saleTolerancePlus IS NULL
		SET @saleTolerancePlus = 0
	    

     IF EXISTS(SELECT 'A' FROM EXCHANGE_CURRENCYRATE_SETUP WHERE currencyRateId = @currencyRateId AND baseCurrency=@baseCurrency)
     BEGIN     
		IF NOT EXISTS(
			SELECT 'A' FROM currencyMaster C WITH(NOLOCK) 
			INNER JOIN  EXCHANGE_CURRENCYRATE_SETUP E WITH(NOLOCK) ON C.currencyCode = E.baseCurrency
			WHERE E.currencyrateId = @currencyRateId
			AND  (@buyRate + ISNULL(@buyTolerancePlus,0)) BETWEEN C.rateMin AND C.rateMax
			AND  (@buyRate - ISNULL(@buyToleranceMinus,0)) BETWEEN C.rateMin  AND C.rateMax
			AND  (@saleRate + ISNULL(@saleTolerancePlus,0)) BETWEEN C.rateMin  AND C.rateMax
			AND  (@saleRate - ISNULL(@saleToleranceMinus,0)) BETWEEN C.rateMin  AND C.rateMax
			AND   @revRate BETWEEN	C.rateMin  AND C.rateMax
			)
		BEGIN
		SELECT TOP 1 '1' errorCode,'MIN, MAX and Base rate must be lies between : '+CAST(C.rateMin AS VARCHAR)+' and '+CAST(C.rateMax AS VARCHAR)+' with Tolerance' MSG ,null id
			FROM dbo.currencyMaster C WITH(NOLOCK) 
			INNER JOIN  EXCHANGE_CURRENCYRATE_SETUP E WITH(NOLOCK) ON C.currencyCode = E.baseCurrency
			WHERE E.currencyrateId = @currencyRateId
			RETURN;
		END
	
     
          BEGIN TRANSACTION
          INSERT INTO EXCHANGE_CURRENCYRATE_SETUP_HISTORY(currencyRateId,baseCurrency,quoteCurrency,FixedCurUnit,RevRate,BuyRate,Buytoleranceplus,Buytoleranceminus,
          SaleRate,Saletoleranceplus,Saletoleranceminus,Active,CreatedBy,CreatedDate,ModifiedBy,ModifiedDate,buyLimit,sellLimit)
          SELECT currencyRateId,baseCurrency,quoteCurrency,FixedCurUnit,RevRate,BuyRate,Buytoleranceplus,Buytoleranceminus,
          SaleRate,Saletoleranceplus,Saletoleranceminus,Active,CreatedBy,CreatedDate,@user,GETDATE(),buyLimit,sellLimit
          FROM EXCHANGE_CURRENCYRATE_SETUP WHERE currencyRateId = @currencyRateId
          
               UPDATE EXCHANGE_CURRENCYRATE_SETUP SET
                         
                          baseCurrency                  = @baseCurrency
                         ,quoteCurrency                 = @quoteCurrency
                         ,FixedCurUnit                  = @FixedCurUnit
                         ,RevRate                       = @revRate
                         ,BuyRate                       = @BuyRate
                         ,Buytoleranceplus              = @buyTolerancePlus
                         ,Buytoleranceminus             = @buyToleranceMinus
                         ,SaleRate                      = @SaleRate
                         ,Saletoleranceplus             = @saleTolerancePlus
                         ,Saletoleranceminus            = @saleToleranceMinus
                         ,active						= @active
                         ,modifiedBy					= @user
                         ,modifiedDate					= GETDATE()
                    --WHERE CurFixed = @curFixed AND CurVariable=@curVariable and RateCode = @rateCode
                    WHERE currencyRateId						= @currencyRateId

					-- update buy rate/ sale rate --
					UPDATE EXCHANGE_COSTRATE_SETUP 
							SET buyRate=@buyRate
								,saleRate=@saleRate 
					WHERE baseCurrency=@baseCurrency

                   SET @currencyRateId = SCOPE_IDENTITY()
               IF @@TRANCOUNT > 0
               COMMIT TRANSACTION
          Exec JobHistoryRecord 'u','ExRate updated',@baseCurrency,@quoteCurrency ,'',@currencyRateId,@user
          SELECT 0 errorCode,'Rate updated successfully' MSG,null id
		RETURN;
     END
     ELSE
     BEGIN
	 IF EXISTS(select 'A' from EXCHANGE_CURRENCYRATE_SETUP (NOLOCK) WHERE baseCurrency=@baseCurrency AND quoteCurrency = @quoteCurrency)
	 BEGIN
		SELECT  '1' errorCode,'Rate already defined for currency :' + @quoteCurrency +' and ' + @baseCurrency MSG ,null id
		RETURN
	 END	     
		IF NOT EXISTS(
			SELECT 'A' FROM currencyMaster C WITH(NOLOCK) 
			WHERE C.currencyCode = @baseCurrency
			AND  (@buyRate + ISNULL(@buyTolerancePlus,0)) BETWEEN C.rateMin AND C.rateMax
			AND  (@buyRate - ISNULL(@buyToleranceMinus,0)) BETWEEN C.rateMin AND C.rateMax
			AND  (@saleRate + ISNULL(@saleTolerancePlus,0)) BETWEEN C.rateMin AND C.rateMax
			AND  (@saleRate - ISNULL(@saleToleranceMinus,0)) BETWEEN C.rateMin AND C.rateMax
			AND @revRate BETWEEN	C.rateMin  AND C.rateMax
			)
		BEGIN
			SELECT TOP 1 '1' CODE,'MIN,MAX and Base rate must be lies between : '+CAST(C.rateMin AS VARCHAR)+' and '+CAST(C.rateMax AS VARCHAR)+' with Tolerance' MSG ,null id
			FROM currencyMaster C WITH(NOLOCK) 
			WHERE C.currencyCode = @baseCurrency
			RETURN;
		END
  
          BEGIN TRANSACTION
               INSERT INTO EXCHANGE_CURRENCYRATE_SETUP (
					 baseCurrency
                    ,quoteCurrency
                    ,FixedCurUnit
                    ,RevRate
                    ,BuyRate
                    ,Buytoleranceplus
                    ,Buytoleranceminus
                    ,SaleRate
                    ,Saletoleranceplus
                    ,Saletoleranceminus
                    ,active
                    ,createdBy
                    ,createdDate
               )
               SELECT
                     @baseCurrency
                    ,@quoteCurrency
                    ,@FixedCurUnit
                    ,@revRate
                    ,@BuyRate
                    ,@buyTolerancePlus
                    ,@buyToleranceMinus
                    ,@SaleRate
                    ,@saleTolerancePlus
                    ,@saleToleranceMinus
                    ,@active
                    ,@user
                    ,GETDATE()
               SET @currencyRateId = SCOPE_IDENTITY()

               INSERT INTO EXCHANGE_CURRENCYRATE_SETUP_HISTORY(currencyRateId,baseCurrency,quoteCurrency,FixedCurUnit,RevRate,BuyRate,Buytoleranceplus,Buytoleranceminus,
					SaleRate,Saletoleranceplus,Saletoleranceminus,Active,CreatedBy,CreatedDate,ModifiedBy,ModifiedDate,buyLimit,sellLimit)
               SELECT currencyRateId,baseCurrency,quoteCurrency,FixedCurUnit,RevRate,BuyRate,Buytoleranceplus,Buytoleranceminus,
					 SaleRate,Saletoleranceplus,Saletoleranceminus,Active,CreatedBy,CreatedDate,@user,GETDATE(),buyLimit,sellLimit 
			FROM EXCHANGE_CURRENCYRATE_SETUP WHERE currencyRateId = @currencyRateId
            
			/*assign branch currency and  generate voucher*/  


			DECLARE @totalRows INT, @Temp_Id INT,@agentName	VARCHAR(500)

			CREATE TABLE #tempagentId (Temp_Id INT IDENTITY,agentid BIGINT,agentName VARCHAR(200))

			INSERT INTO #tempagentId(agentid,agentName) SELECT agentId ,agentName FROM dbo.agentMaster (NOLOCK)
			 WHERE parentid='1008' AND agentGrp=11023 AND isActive='Y'

			SELECT @Temp_Id=max(temp_Id) from #tempagentId
			SET @totalRows=1
			WHILE @Temp_Id >=  @totalRows
				BEGIN			 			
				SELECT @agentId=agentid ,@agentName = agentName FROM #tempagentId WHERE Temp_Id=@totalRows
				INSERT INTO dbo.EXCHANGE_COSTRATE_SETUP
				(
					baseCurrency, quoteCurrency, buyRate, buyTolerancePlus, buyToleranceMinus,
					saleRate,saleTolerancePlus,saleToleranceMinus,agentId,modifiedBy,modifiedDate
				)
				SELECT cc.baseCurrency, cc.quoteCurrency, cc.buyRate, cc.buyTolerancePlus, cc.buyToleranceMinus,
					cc.saleRate,cc.saleTolerancePlus,cc.saleToleranceMinus,@agentId,@user,GETDATE()
					FROM EXCHANGE_CURRENCYRATE_SETUP cc 
					LEFT JOIN EXCHANGE_COSTRATE_SETUP c ON cc.baseCurrency=c.baseCurrency AND c.agentId=@agentId
				WHERE c.baseCurrency IS NULL AND  ISNULL(cc.active,'N')='Y' 

				
				--IF NOT EXISTS(SELECT 'X' FROM FastMoneyPro_Account.dbo.GL_Group (NOLOCK) WHERE p_id='22' AND  gl_Name=@agentName )
				--BEGIN
				--	EXEC FastMoneyPro_Account.dbo.procFindGLTreeShape @p_id='22',@gl_name = @agentName,@bal_grp='',@accountPrifix=''
				--END
				/*Account no */
				EXEC FastMoneyPro_Account.dbo.EXCHANGE_PROC_BRANCHCURR_ASSIGN @BRANCH_ID=@agentId,@user=@user

			SET @totalRows=@totalRows+1
			END
			   
               IF @@TRANCOUNT > 0
               COMMIT TRANSACTION
               Exec JobHistoryRecord 'i','ExRate ADDED',@baseCurrency,@quoteCurrency ,'',@currencyRateId,@user
               SELECT 0 CODE,'Rate added successfully' MSG,null id
				RETURN;
          END

		
	END
	ELSE IF @flag = 'a'
	BEGIN		
		--SELECT @baseCurrency = baseCurrency FROM EXCHANGE_CURRENCYRATE_SETUP with(nolock) WHERE currencyRateId = @currencyRateId
		
		--SELECT @revRate = CASE WHEN SUM(ISNULL(USD_AMT,0)) = 0 THEN CAST(0 AS FLOAT) ELSE CAST(SUM (ISNULL(CLR_BAL_AMT,0)) AS FLOAT) / CAST(SUM (ISNULL(USD_AMT,0)) AS FLOAT) END
		--FROM FastMoneyPro_Account.dbo.AC_MASTER  A WITH (NOLOCK) 
		--INNER JOIN AgentMaster B WITH (NOLOCK) ON A.BRANCH_ID=B.agentId
		--AND A.AC_CURRENCY = @baseCurrency --AND B.CASHID = @rateCode
	
		--SELECT *,CAST(@revRate AS DECIMAL(10,6)) avgRate FROM EXCHANGE_CURRENCYRATE_SETUP  with(nolock) WHERE currencyRateId = @currencyRateId

		SELECT *,ISNULL(c.rateMin,0) AS minRate,ISNULL(c.rateMax,0) AS maxrate FROM dbo.currencyMaster C WITH(NOLOCK) 
			 INNER JOIN  EXCHANGE_CURRENCYRATE_SETUP E WITH(NOLOCK) ON C.currencyCode = E.baseCurrency
			 WHERE e.currencyRateId = @currencyRateId

			 RETURN
	END	
	
	ELSE IF @FLAG = 'RateEdit'-->> TODAYS RATE FOR RATE MAINTENANCE
	BEGIN
	DECLARE @table VARCHAR(MAX),@sql_filter VARCHAR(100),@select_field_list VARCHAR(MAX),@extra_field_list VARCHAR(10)
	
	--IF @sortBy IS NULL
		SET @sortBy = 'currencyRateId'
		IF @sortOrder IS NULL
			SET @sortOrder = 'ASC'

	SET @table = '(SELECT E.currencyRateId,E.baseCurrency,E.quoteCurrency,E.FixedCurUnit,E.RevRate
				,E.BuyRate,E.SaleRate,CAST(ISNULL(SaleRate,0)-ISNULL(BuyRate,0) AS Decimal(20,6)) as MARGIN,active
				,ISNULL(e.ModifiedDate,E.CREATEDDATE) [moddate],ISNULL(e.ModifiedBy,E.CreatedBy) ModifiedBy 
				FROM EXCHANGE_CURRENCYRATE_SETUP E WITH(NOLOCK)  
				INNER JOIN dbo.currencyMaster (NOLOCK) cm ON  cm.currencyCode=e.baseCurrency
				where  1=1 and E.Active=''Y''  
				) x'
	print @table
	SET @sql_filter = ''
	IF @baseCurrency IS NOT NULL
		SET @sql_filter = @sql_filter + ' AND CurFixed = '''+@baseCurrency+''''
	
	
	SET @select_field_list ='
			 currencyRateId			 
			 ,baseCurrency
			 ,quoteCurrency
			 ,FixedCurUnit
			 ,RevRate
			 ,BuyRate
			 ,SaleRate
			 ,MARGIN
			 ,moddate
			 ,ModifiedBy'
			
		EXEC dbo.proc_paging
			@table
			,@sql_filter
			,@select_field_list
			,@extra_field_list
			,@sortBy
			,@sortOrder
			,@pageSize
			,@pageNumber
	END
ELSE IF @flag = 'minmax'
	BEGIN
		SELECT ISNULL(c.rateMin,0) AS rateMin,ISNULL(c.rateMax,0) AS rateMax 
			FROM dbo.currencyMaster C WITH(NOLOCK) 
		WHERE c.currencyCode=@baseCurrency
		RETURN		
	END	


END TRY
BEGIN CATCH
     IF @@TRANCOUNT > 0
     ROLLBACK TRANSACTION
     SELECT 1 CODE, ERROR_MESSAGE() MSG
END CATCH





GO
