    DROP TEMPORARY TABLE IF EXISTS tmp_morrateall_;
    CREATE TEMPORARY TABLE tmp_morrateall_ (
        RateID INT,
        Country VARCHAR(155),
        CountryCode VARCHAR(50),
        Code VARCHAR(50),
        Description VARCHAR(200),
        Interval1 INT,
        IntervalN INT,
        ConnectionFee DECIMAL(18, 6),
        RoutinePlanName VARCHAR(50),
        Rate DECIMAL(18, 6),
        EffectiveDate DATE,
        LastModifiedDate DATETIME,
        LastModifiedBy VARCHAR(50),
        CustomerRateId INT,
        TrunkID INT,
        RateTableRateId INT,
        IncludePrefix TINYINT,
        Prefix VARCHAR(50),
        RatePrefix VARCHAR(50),
        AreaPrefix VARCHAR(50),
        SubCode VARCHAR(50)
    );

    INSERT INTO tmp_morrateall_
     SELECT
		  tc.RateID,
	  	  c.Country,
		  c.ISO3,
		  tc.Code,
		  tc.Description,
		  tc.Interval1,
        tc.IntervalN,
        tc.ConnectionFee,
        tc.RoutinePlanName,
        tc.Rate,
        tc.EffectiveDate,
        tc.LastModifiedDate,
        tc.LastModifiedBy,
        tc.CustomerRateId,
        tc.TrunkID,
        tc.RateTableRateId,
        tc.IncludePrefix,
        tc.Prefix,
        tc.RatePrefix,
        tc.AreaPrefix,
        'FIX' as `SubCode`
	  	 FROM tmp_customerrateall_ tc
	  			 INNER JOIN tblRate r ON tc.RateID = r.RateID
				 LEFT JOIN tblCountry c ON r.CountryID = c.CountryID
					;

	  UPDATE tmp_morrateall_
	  			SET SubCode='MOB'
	  			WHERE Description LIKE '%Mobile%';


		SELECT DISTINCT
	      Country as `Direction` ,
	      Description  as `Destination`,
		   Code as `Prefix`,
		   SubCode as `Subcode`,
		   CountryCode as `Country code`,
		   Rate as `Rate(EUR)`,
		   ConnectionFee as `Connection Fee(EUR)`,
		   Interval1 as `Increment`,
		   IntervalN as `Minimal Time`,
		   '0:00:00 'as `Start Time`,
		   '23:59:59' as `End Time`,
		   '' as `Week Day`
     FROM tmp_morrateall_;

		SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_CronJobGenerateMorVendorSheet` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_CronJobGenerateMorVendorSheet`(
	IN `p_AccountID` INT ,
	IN `p_trunks` VARCHAR(200),
	IN `p_TimezonesID` INT,
	IN `p_Effective` VARCHAR(50),
	IN `p_CustomDate` DATE
)
BEGIN
		SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

		DROP TEMPORARY TABLE IF EXISTS tmp_VendorRate_;
    CREATE TEMPORARY TABLE tmp_VendorRate_ (
        TrunkId INT,
        TimezonesID INT,
   	  RateId INT,
        Rate DECIMAL(18,6),
        EffectiveDate DATE,
        Interval1 INT,
        IntervalN INT,
        ConnectionFee DECIMAL(18,6),
        INDEX tmp_RateTable_RateId (`RateId`)
    );
        INSERT INTO tmp_VendorRate_
        SELECT   `TrunkID`, `TimezonesID`, `RateId`, `Rate`, `EffectiveDate`, `Interval1`, `IntervalN`, `ConnectionFee`
		  FROM tblVendorRate WHERE tblVendorRate.AccountId =  p_AccountID
								AND FIND_IN_SET(tblVendorRate.TrunkId,p_trunks) != 0
								AND tblVendorRate.TimezonesID = p_TimezonesID
                        AND
								(
					  				(p_Effective = 'Now' AND EffectiveDate <= NOW())
								  	OR
								  	(p_Effective = 'Future' AND EffectiveDate > NOW())
								  	OR
								  	(p_Effective = 'CustomDate' AND EffectiveDate <= p_CustomDate AND (EndDate IS NULL OR EndDate > p_CustomDate))
								  	OR
								  	(p_Effective = 'All')
								);

		 DROP TEMPORARY TABLE IF EXISTS tmp_VendorRate4_;
       CREATE TEMPORARY TABLE IF NOT EXISTS tmp_VendorRate4_ as (select * from tmp_VendorRate_);

      DELETE n1 FROM tmp_VendorRate_ n1, tmp_VendorRate4_ n2 WHERE n1.EffectiveDate < n2.EffectiveDate
 	   AND n1.TrunkID = n2.TrunkID
 	   AND n1.TimezonesID = n2.TimezonesID
	   AND  n1.RateId = n2.RateId
		AND
	   (
			(p_Effective = 'CustomDate' AND n1.EffectiveDate <= p_CustomDate AND n2.EffectiveDate <= p_CustomDate)
		  	OR
		  	(p_Effective != 'CustomDate' AND n1.EffectiveDate <= NOW() AND n2.EffectiveDate <= NOW())
		);

		DROP TEMPORARY TABLE IF EXISTS tmp_morrateall_;
    CREATE TEMPORARY TABLE tmp_morrateall_ (
        RateID INT,
        Country VARCHAR(155),
        CountryCode VARCHAR(50),
        Code VARCHAR(50),
        Description VARCHAR(200),
        Interval1 INT,
        IntervalN INT,
        ConnectionFee DECIMAL(18, 6),
        Rate DECIMAL(18, 6),
        SubCode VARCHAR(50)
    );

     INSERT INTO tmp_morrateall_
     SELECT Distinct
          tblRate.RateID as `RateID`,
			  c.Country as `Country`,
			  c.ISO3 as `CountryCode`,
			  tblRate.Code as `Code`,
               tblRate.Description as `Description` ,
               CASE WHEN tblVendorRate.Interval1 IS NOT NULL
                   THEN tblVendorRate.Interval1
                   ElSE tblRate.Interval1
               END AS `Interval1`,
               CASE WHEN tblVendorRate.IntervalN IS NOT NULL
                   THEN tblVendorRate.IntervalN
                   ElSE tblRate.IntervalN
               END  AS `IntervalN`,
               tblVendorRate.ConnectionFee as `ConnectionFee`,
               Abs(tblVendorRate.Rate) as `Rate`,
               'FIX' as `SubCode`

       FROM    tmp_VendorRate_ as tblVendorRate
               JOIN tblRate on tblVendorRate.RateId =tblRate.RateID
               LEFT JOIN tblCountry as c
                   ON tblRate.CountryID = c.CountryID;

		UPDATE tmp_morrateall_
	  			SET SubCode='MOB'
	  			WHERE Description LIKE '%Mobile%';


		SELECT DISTINCT
	      Country as `Direction` ,
	      Description  as `Destination`,
		   Code as `Prefix`,
		   SubCode as `Subcode`,
		   CountryCode as `Country code`,
		   Rate as `Rate(EUR)`,
		   ConnectionFee as `Connection Fee(EUR)`,
		   Interval1 as `Increment`,
		   IntervalN as `Minimal Time`,
		   '0:00:00 'as `Start Time`,
		   '23:59:59' as `End Time`,
		   '' as `Week Day`
     FROM tmp_morrateall_;

      SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_CronJobGeneratePortaSheet` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_CronJobGeneratePortaSheet`(
	IN `p_CustomerID` INT ,
	IN `p_trunks` VARCHAR(200) ,
	IN `p_TimezonesID` INT,
	IN `p_Effective` VARCHAR(50),
	IN `p_CustomDate` DATE
)
BEGIN

	-- get customer rates
	CALL vwCustomerRate(p_CustomerID,p_Trunks,p_TimezonesID,p_Effective,p_CustomDate);

	 SELECT distinct
       Code as `Destination` ,
       Description  as `Description`,
       Interval1 as `First Interval`,
       IntervalN as `Next Interval`,
       Abs(Rate) as `First Price` ,
       Abs(RateN) as `Next Price`,
       DATE_FORMAT(EffectiveDate ,'%d/%m/%Y') as  `Effective From`,
       CASE WHEN Rate < 0 THEN 'Y' ELSE '' END  `Payback Rate` ,
		 CASE WHEN ConnectionFee > 0 THEN
			CONCAT('SEQ=', ConnectionFee,'&int1x1@price1&intNxN@priceN')
		 ELSE
			''
		 END as `Formula`
     FROM tmp_customerrateall_;

		SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_CronJobGeneratePortaVendorSheet` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_CronJobGeneratePortaVendorSheet`(
	IN `p_AccountID` INT ,
	IN `p_trunks` VARCHAR(200),
	IN `p_TimezonesID` INT,
	IN `p_Effective` VARCHAR(50),
	IN `p_CustomDate` DATE
)
BEGIN
		SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

		DROP TEMPORARY TABLE IF EXISTS tmp_VendorRate_;
    CREATE TEMPORARY TABLE tmp_VendorRate_ (
        TrunkId INT,
        TimezonesID INT,
   	  RateId INT,
        Rate DECIMAL(18,6),
        RateN DECIMAL(18,6),
        EffectiveDate DATE,
        Interval1 INT,
        IntervalN INT,
        ConnectionFee DECIMAL(18,6),
        INDEX tmp_RateTable_RateId (`RateId`)
    );
        INSERT INTO tmp_VendorRate_
        SELECT   `TrunkID`, `TimezonesID`, `RateId`, `Rate`, `RateN`,
		  DATE_FORMAT (`EffectiveDate`, '%Y-%m-%d') AS EffectiveDate,
		   `Interval1`, `IntervalN`, `ConnectionFee`
		  FROM tblVendorRate WHERE tblVendorRate.AccountId =  p_AccountID
								AND FIND_IN_SET(tblVendorRate.TrunkId,p_trunks) != 0
								AND tblVendorRate.TimezonesID = p_TimezonesID
                        AND
								(
					  				(p_Effective = 'Now' AND EffectiveDate <= NOW())
								  	OR
								  	(p_Effective = 'Future' AND EffectiveDate > NOW())
								  	OR
								  	(p_Effective = 'CustomDate' AND EffectiveDate <= p_CustomDate AND (EndDate IS NULL OR EndDate > p_CustomDate))
								  	OR
								  	(p_Effective = 'All')
								);

		 DROP TEMPORARY TABLE IF EXISTS tmp_VendorRate4_;
       CREATE TEMPORARY TABLE IF NOT EXISTS tmp_VendorRate4_ as (select * from tmp_VendorRate_);
      DELETE n1 FROM tmp_VendorRate_ n1, tmp_VendorRate4_ n2 WHERE n1.EffectiveDate < n2.EffectiveDate
 	   AND n1.TrunkID = n2.TrunkID
 	   AND n1.TimezonesID = n2.TimezonesID
	   AND  n1.RateId = n2.RateId
		AND
	   (
			(p_Effective = 'CustomDate' AND n1.EffectiveDate <= p_CustomDate AND n2.EffectiveDate <= p_CustomDate)
		  	OR
		  	(p_Effective != 'CustomDate' AND n1.EffectiveDate <= NOW() AND n2.EffectiveDate <= NOW())
		);



	DROP TEMPORARY TABLE IF EXISTS tmp_VendorArchiveCurrentRates_;
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_VendorArchiveCurrentRates_(
		AccountId int,
		Code varchar(50),
		Description varchar(200),
		Rate float,
		RateN float,
		EffectiveDate date,
		TrunkID int,
		CountryID int,
		RateID int,
		Interval1 INT,
		IntervalN varchar(100),
		ConnectionFee float,
		EndDate date
    );

	IF p_Effective = 'Now' || p_Effective = 'All' THEN

  	 	call vwVendorArchiveCurrentRates(p_AccountID,p_Trunks,p_TimezonesID,p_Effective);

	END IF;

       SELECT Distinct  tblRate.Code as `Destination`,
               tblRate.Description as `Description` ,
               CASE WHEN tblVendorRate.Interval1 IS NOT NULL
                   THEN tblVendorRate.Interval1
                   ElSE tblRate.Interval1
               END AS `First Interval`,
               CASE WHEN tblVendorRate.IntervalN IS NOT NULL
                   THEN tblVendorRate.IntervalN
                   ElSE tblRate.IntervalN
               END  AS `Next Interval`,
               Abs(tblVendorRate.Rate) as `First Price`,
               Abs(tblVendorRate.RateN) as `Next Price`,
               DATE_FORMAT (tblVendorRate.EffectiveDate, '%Y-%m-%d')  as `Effective From` ,
               IFNULL(Preference,5) as `Preference`,
               CASE
                   WHEN (blockCode.VendorBlockingId IS NOT NULL AND
                   	FIND_IN_SET(tblVendorRate.TrunkId,blockCode.TrunkId) != 0
                       )OR
                       (blockCountry.VendorBlockingId IS NOT NULL AND
                       FIND_IN_SET(tblVendorRate.TrunkId,blockCountry.TrunkId) != 0
                       ) THEN 'Y'
                   ELSE 'N'
               END AS `Forbidden`,
               CASE WHEN tblVendorRate.Rate < 0 THEN 'Y' ELSE '' END AS 'Payback Rate' ,
               CASE WHEN ConnectionFee > 0 THEN
						CONCAT('SEQ=',ConnectionFee,'&int1x1@price1&intNxN@priceN')
					ELSE
						''
					END as `Formula`,
					'N' AS `Discontinued`
       FROM    tmp_VendorRate_ as tblVendorRate
               JOIN tblRate on tblVendorRate.RateId =tblRate.RateID
               LEFT JOIN tblVendorBlocking as blockCode
                   ON tblVendorRate.RateID = blockCode.RateId
                   AND blockCode.AccountId = p_AccountID
                   AND tblVendorRate.TrunkID = blockCode.TrunkID
               LEFT JOIN tblVendorBlocking AS blockCountry
                   ON tblRate.CountryID = blockCountry.CountryId
                   AND blockCountry.AccountId = p_AccountID
                   AND tblVendorRate.TrunkID = blockCountry.TrunkID
					LEFT JOIN tblVendorPreference
						ON tblVendorPreference.AccountId = p_AccountID
						AND tblVendorPreference.TrunkID = tblVendorRate.TrunkID
						AND tblVendorPreference.RateId = tblVendorRate.RateId
       UNION ALL



		SELECT
					Distinct
			    	tblRate.Code AS `Destination`,
			 		tblRate.Description AS `Description` ,

			 		CASE WHEN vrd.Interval1 IS NOT NULL
                   THEN vrd.Interval1
                   ElSE tblRate.Interval1
               END AS `First Interval`,
               CASE WHEN vrd.IntervalN IS NOT NULL
                   THEN vrd.IntervalN
                   ElSE tblRate.IntervalN
               END  AS `Next Interval`,

			 		Abs(vrd.Rate) AS `First Price`,
			 		Abs(vrd.RateN) AS `Next Price`,
			 		DATE_FORMAT (vrd.EffectiveDate, '%Y-%m-%d') AS `Effective From`,
			 		'' AS `Preference`,
			 		'' AS `Forbidden`,
			 		CASE WHEN vrd.Rate < 0 THEN 'Y' ELSE '' END AS 'Payback Rate' ,
			 		CASE WHEN vrd.ConnectionFee > 0 THEN
						CONCAT('SEQ=',vrd.ConnectionFee,'&int1x1@price1&intNxN@priceN')
					ELSE
						''
					END as `Formula`,
			 		'Y' AS `Discontinued`
			FROM tmp_VendorArchiveCurrentRates_ AS vrd
	 		JOIN tblRate on vrd.RateId = tblRate.RateID
			LEFT JOIN tblVendorRate vr
						ON vrd.AccountId = vr.AccountId
							AND vrd.TrunkID = vr.TrunkID
							AND vrd.RateId = vr.RateId
					WHERE FIND_IN_SET(vrd.TrunkID,p_trunks) != 0
						AND vrd.AccountId = p_AccountID
						AND vr.VendorRateID IS NULL
						AND vrd.Rate > 0;


			/*
		    SELECT
			 		vrd.Code AS `Destination`,
			 		vrd.Description AS `Description` ,
			 		vrd.Interval1 AS `First Interval`,
			 		vrd.IntervalN AS `Next Interval`,
			 		Abs(vrd.Rate) AS `First Price`,
			 		Abs(vrd.Rate) AS `Next Price`,
			 		vrd.EffectiveDate AS `Effective From`,
			 		'' AS `Preference`,
			 		'' AS `Forbidden`,
			 		CASE WHEN vrd.Rate < 0 THEN 'Y' ELSE '' END AS 'Payback Rate' ,
			 		CASE WHEN vrd.ConnectionFee > 0 THEN
						CONCAT('SEQ=',vrd.ConnectionFee,'&int1x1@price1&intNxN@priceN')
					ELSE
						''
					END as `Formula`,
			 		'Y' AS `Discontinued`
			  FROM tblVendorRateDiscontinued vrd
					LEFT JOIN tblVendorRate vr
						ON vrd.AccountId = vr.AccountId
							AND vrd.TrunkID = vr.TrunkID
							AND vrd.RateId = vr.RateId
					WHERE FIND_IN_SET(vrd.TrunkID,p_trunks) != 0
						AND vrd.AccountId = p_AccountID
						AND vr.VendorRateID IS NULL ;
*/


      SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_CustomerBulkRateClear` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_CustomerBulkRateClear`(IN `p_AccountIdList` LONGTEXT , IN `p_TrunkId` INT , IN `p_CodeDeckId` int, IN `p_code` VARCHAR(50), IN `p_description` VARCHAR(200) , IN `p_CountryId` INT , IN `p_CompanyId` INT)
BEGIN

   SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; 
	delete tblCustomerRate
	from tblCustomerRate
   INNER JOIN ( 
		SELECT c.CustomerRateID
      FROM   tblCustomerRate c
      INNER JOIN tblCustomerTrunk
          ON tblCustomerTrunk.TrunkID = c.TrunkID
          AND tblCustomerTrunk.AccountID = c.CustomerID
          AND tblCustomerTrunk.Status = 1
      INNER JOIN tblRate r
          ON c.RateID = r.RateID and r.CodeDeckId=p_CodeDeckId
		WHERE c.TrunkID = p_TrunkId
			   AND FIND_IN_SET(c.CustomerID,p_AccountIdList) != 0 
				AND ( ( p_code IS NULL ) OR ( p_code IS NOT NULL AND r.Code LIKE REPLACE(p_code,'*', '%')))
				AND ( ( p_description IS NULL ) OR ( p_description IS NOT NULL AND r.Description LIKE REPLACE(p_description,'*', '%')))
				AND ( ( p_CountryId IS NULL )  OR ( p_CountryId IS NOT NULL AND r.CountryID = p_CountryId ) ) 
		) cr ON cr.CustomerRateID = tblCustomerRate.CustomerRateID;
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_CustomerBulkRateInsert` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_CustomerBulkRateInsert`(
	IN `p_AccountIdList` LONGTEXT ,
	IN `p_TrunkId` INT ,
	IN `p_TimezonesID` INT,
	IN `p_CodeDeckId` int,
	IN `p_code` VARCHAR(50) ,
	IN `p_description` VARCHAR(200) ,
	IN `p_CountryId` INT ,
	IN `p_CompanyId` INT ,
	IN `p_Rate` DECIMAL(18, 6) ,
	IN `p_RateN` DECIMAL(18,6),
	IN `p_ConnectionFee` DECIMAL(18, 6) ,
	IN `p_EffectiveDate` DATETIME ,
	IN `p_EndDate` DATETIME ,
	IN `p_Interval1` INT,
	IN `p_IntervalN` INT,
	IN `p_RoutinePlan` INT,
	IN `p_ModifiedBy` VARCHAR(50)
)
BEGIN

 	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	INSERT  INTO tblCustomerRate
	(
		RateID ,
		CustomerID ,
		TrunkID ,
		TimezonesID,
		Rate ,
		RateN ,
		ConnectionFee,
		EffectiveDate ,
		EndDate ,
		Interval1,
		IntervalN ,
		RoutinePlan,
		CreatedDate ,
		LastModifiedBy ,
		LastModifiedDate
	)
	SELECT
		r.RateID ,
		r.AccountId ,
		p_TrunkId ,
		p_TimezonesID,
		p_Rate ,
		p_RateN ,
		p_ConnectionFee,
		p_EffectiveDate ,
		p_EndDate ,
		p_Interval1,
		p_IntervalN,
		RoutinePlan,
		NOW() ,
		p_ModifiedBy ,
		NOW()
	FROM
	(
		SELECT
			RateID,Code,AccountId,CompanyID,CodeDeckId,Description,CountryID,RoutinePlan
		FROM
			tblRate ,
			(
				SELECT
					a.AccountId,
					CASE WHEN ctr.TrunkID IS NOT NULL
					THEN p_RoutinePlan
					ELSE NULL
					END AS RoutinePlan
				FROM tblAccount a
				INNER JOIN tblCustomerTrunk
					ON TrunkID = p_TrunkId
					AND a.AccountID    = tblCustomerTrunk.AccountID
					AND tblCustomerTrunk.Status = 1
				LEFT JOIN tblCustomerTrunk ctr
					ON ctr.TrunkID = p_TrunkId
					AND ctr.AccountID = a.AccountID
					AND ctr.RoutinePlanStatus = 1
				WHERE
					FIND_IN_SET(a.AccountID,p_AccountIdList) != 0
			) a
	) r
	LEFT OUTER JOIN
	(
		SELECT DISTINCT
			RateID ,
			c.CustomerID as AccountId ,
			c.TrunkID,
			c.EffectiveDate
		FROM
			tblCustomerRate c
		INNER JOIN tblCustomerTrunk
			ON tblCustomerTrunk.TrunkID = c.TrunkID
			AND tblCustomerTrunk.AccountID = c.CustomerID
			AND tblCustomerTrunk.Status = 1
		WHERE
			FIND_IN_SET(c.CustomerID,p_AccountIdList) != 0 AND c.TrunkID = p_TrunkId AND c.TimezonesID = p_TimezonesID
	) cr ON r.RateID = cr.RateID
		AND r.AccountId = cr.AccountId
		AND r.CompanyID = p_CompanyId
		and cr.EffectiveDate = p_EffectiveDate
	WHERE
		r.CompanyID = p_CompanyId
		AND r.CodeDeckId=p_CodeDeckId
		AND ( ( p_code IS NULL ) OR ( p_code IS NOT NULL AND r.Code LIKE REPLACE(p_code,'*', '%')))
		AND ( ( p_description IS NULL ) OR ( p_description IS NOT NULL AND r.Description LIKE REPLACE(p_description,'*', '%')))
		AND ( ( p_CountryId IS NULL )  OR ( p_CountryId IS NOT NULL AND r.CountryID = p_CountryId ) )
		AND cr.RateID IS NULL;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_CustomerBulkRateUpdate` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_CustomerBulkRateUpdate`(
	IN `p_AccountIdList` LONGTEXT ,
	IN `p_TrunkId` INT ,
	IN `p_TimezonesID` INT,
	IN `p_CodeDeckId` int,
	IN `p_code` VARCHAR(50) ,
	IN `p_description` VARCHAR(200) ,
	IN `p_CountryId` INT ,
	IN `p_CompanyId` INT ,
	IN `p_Effective` VARCHAR(50),
	IN `p_CustomDate` DATE,
	IN `p_Rate` DECIMAL(18, 6) ,
	IN `p_RateN` DECIMAL(18, 6) ,
	IN `p_ConnectionFee` DECIMAL(18, 6) ,
	IN `p_EffectiveDate` DATETIME ,
	IN `p_EndDate` DATETIME ,
	IN `p_Interval1` INT,
	IN `p_IntervalN` INT,
	IN `p_RoutinePlan` INT,
	IN `p_ModifiedBy` VARCHAR(50)
)
BEGIN

 	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	DROP TEMPORARY TABLE IF EXISTS tmp_CustomerRates_;
    CREATE TEMPORARY TABLE tmp_CustomerRates_ (
        CustomerRateID INT,
        RateID INT,
        CustomerID INT,
        Interval1 INT,
        IntervalN  INT,
        Rate DECIMAL(18, 6),
        RateN DECIMAL(18, 6),
        PreviousRate DECIMAL(18, 6),
        ConnectionFee DECIMAL(18, 6),
        EffectiveDate DATE,
        EndDate DATE,
        CreatedDate DATETIME,
        CreatedBy VARCHAR(50),
        LastModifiedDate DATETIME,
        LastModifiedBy VARCHAR(50),
        TrunkID INT,
        TimezonesID INT,
        RoutinePlan INT,
        INDEX tmp_CustomerRates__CustomerRateID (`CustomerRateID`)/*,
        INDEX tmp_CustomerRates__RateID (`RateID`),
        INDEX tmp_CustomerRates__TrunkID (`TrunkID`),
        INDEX tmp_CustomerRates__EffectiveDate (`EffectiveDate`)*/
    );

	-- insert rates in temp table which needs to update (based on grid filter)
	INSERT INTO tmp_CustomerRates_
	(
		CustomerRateID,
		RateID,
		CustomerID,
		Interval1,
		IntervalN,
		Rate,
		RateN,
		PreviousRate,
		ConnectionFee,
		EffectiveDate,
		EndDate,
		CreatedDate,
		CreatedBy,
		LastModifiedDate,
		LastModifiedBy,
		TrunkID,
		TimezonesID,
		RoutinePlan
	)
	SELECT
		tblCustomerRate.CustomerRateID,
		tblCustomerRate.RateID,
		tblCustomerRate.CustomerID,
		p_Interval1 AS Interval1,
		p_IntervalN AS IntervalN,
		p_Rate AS Rate,
		p_RateN AS RateN,
		tblCustomerRate.PreviousRate,
		p_ConnectionFee AS ConnectionFee,
		tblCustomerRate.EffectiveDate,
		tblCustomerRate.EndDate,
		tblCustomerRate.CreatedDate,
		tblCustomerRate.CreatedBy,
		NOW() AS LastModifiedDate,
		p_ModifiedBy AS LastModifiedBy,
		tblCustomerRate.TrunkID,
		tblCustomerRate.TimezonesID,
		tblCustomerRate.RoutinePlan
	FROM
		tblCustomerRate
	INNER JOIN (
		SELECT c.CustomerRateID,
			c.EffectiveDate,
			CASE WHEN ctr.TrunkID IS NOT NULL
			THEN p_RoutinePlan
			ELSE NULL
			END AS RoutinePlan
		FROM   tblCustomerRate c
		INNER JOIN tblCustomerTrunk
			ON tblCustomerTrunk.TrunkID = c.TrunkID
			AND tblCustomerTrunk.AccountID = c.CustomerID
			AND tblCustomerTrunk.Status = 1
		INNER JOIN tblRate r
			ON c.RateID = r.RateID and r.CodeDeckId=p_CodeDeckId
		LEFT JOIN tblCustomerTrunk ctr
			ON ctr.TrunkID = c.TrunkID
			AND ctr.AccountID = c.CustomerID
			AND ctr.RoutinePlanStatus = 1
		WHERE  ( ( p_code IS NULL ) OR ( p_code IS NOT NULL AND r.Code LIKE REPLACE(p_code,'*', '%')))
			AND ( ( p_description IS NULL ) OR ( p_description IS NOT NULL AND r.Description LIKE REPLACE(p_description,'*', '%')))
			AND ( ( p_CountryId IS NULL )  OR ( p_CountryId IS NOT NULL AND r.CountryID = p_CountryId ) )
			AND
			(
				( p_Effective = 'Now' AND c.EffectiveDate <= NOW() )
				OR
				( p_Effective = 'Future' AND c.EffectiveDate > NOW() )
				OR
				( p_Effective = 'CustomDate' AND c.EffectiveDate <= p_CustomDate AND (c.EndDate IS NULL OR c.EndDate > p_CustomDate) )
				OR
				p_Effective = 'All'
			)
			AND c.TrunkID = p_TrunkId
			AND c.TimezonesID = p_TimezonesID
			AND FIND_IN_SET(c.CustomerID,p_AccountIdList) != 0
	) cr ON cr.CustomerRateID = tblCustomerRate.CustomerRateID; -- and cr.EffectiveDate = p_EffectiveDate;

	-- if custom date then remove duplicate rates of earlier date
	-- for examle custom date is 2018-05-03 today's date is 2018-05-01 and there are 2 rates available for 1 code
	-- Code	Date
	-- 1204	2018-05-01
	-- 1204	2018-05-03
	-- then it will delete 2018-05-01 from temp table and keeps only 2018-05-03 rate to update
	IF p_Effective = 'CustomDate'
	THEN
		DROP TEMPORARY TABLE IF EXISTS tmp_CustomerRates_2_;
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_CustomerRates_2_ AS (SELECT * FROM tmp_CustomerRates_);

		DELETE
			n1
		FROM
			tmp_CustomerRates_ n1,
			tmp_CustomerRates_2_ n2
		WHERE
			n1.EffectiveDate < n2.EffectiveDate AND
			n1.RateID = n2.RateID AND
			n1.CustomerID = n2.CustomerID AND
			n1.TrunkID = n2.TrunkId AND
			n1.TimezonesID = n2.TimezonesID AND
			(
				(p_Effective = 'CustomDate' AND n1.EffectiveDate <= p_CustomDate AND n2.EffectiveDate <= p_CustomDate)
				OR
				(p_Effective != 'CustomDate' AND n1.EffectiveDate <= NOW() AND n2.EffectiveDate <= NOW())
			);
	END IF;

	-- update EndDate to Archive rates which needs to update
	UPDATE
		tblCustomerRate cr
	JOIN
		tmp_CustomerRates_ temp ON cr.CustomerRateID=temp.CustomerRateID
	SET
		cr.EndDate = NOW();

	-- archive rates which rates' EndDate < NOW()
	CALL prc_ArchiveOldCustomerRate(p_AccountIdList, p_TrunkId, p_TimezonesID, p_ModifiedBy);

	-- insert rates in tblCustomerRate with updated values
	INSERT INTO tblCustomerRate
	(
		CustomerRateID,
		RateID,
		CustomerID,
		Interval1,
		IntervalN,
		Rate,
		RateN,
		PreviousRate,
		ConnectionFee,
		EffectiveDate,
		EndDate,
		CreatedDate,
		CreatedBy,
		LastModifiedDate,
		LastModifiedBy,
		TrunkID,
		TimezonesID,
		RoutinePlan
	)
	SELECT
		NULL, -- primary key
		RateID,
		CustomerID,
		Interval1,
		IntervalN,
		Rate,
		RateN,
		PreviousRate,
		ConnectionFee,
		EffectiveDate,
		EndDate,
		CreatedDate,
		CreatedBy,
		LastModifiedDate,
		LastModifiedBy,
		TrunkID,
		TimezonesID,
		RoutinePlan
	FROM
		tmp_CustomerRates_;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_CustomerPanel_GetinboundRate` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_CustomerPanel_GetinboundRate`(IN `p_companyid` INT, IN `p_AccountID` INT, IN `p_ratetableid` INT, IN `p_trunkID` INT, IN `p_contryID` INT, IN `p_code` VARCHAR(50), IN `p_description` VARCHAR(50), IN `p_Effective` VARCHAR(50), IN `p_effectedRates` INT, IN `p_RoutinePlan` INT, IN `p_PageNumber` INT, IN `p_RowspPage` INT, IN `p_lSortCol` VARCHAR(50), IN `p_SortOrder` VARCHAR(5), IN `p_isExport` INT )
BEGIN
   DECLARE v_codedeckid_ INT;
   DECLARE v_ratetableid_ INT;
   DECLARE v_RateTableAssignDate_ DATETIME;
   DECLARE v_NewA2ZAssign_ INT;
   DECLARE v_OffSet_ int;
   DECLARE v_IncludePrefix_ INT;
   DECLARE v_Prefix_ VARCHAR(50);
   DECLARE v_RatePrefix_ VARCHAR(50);
   DECLARE v_AreaPrefix_ VARCHAR(50);
   
   SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
   SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

	SELECT CodeDeckId INTO v_codedeckid_ FROM tblRateTable where RateTableId=p_ratetableid and CompanyId=p_companyid;
	
	DROP TEMPORARY TABLE IF EXISTS tmp_RateTableRate_;
    CREATE TEMPORARY TABLE tmp_RateTableRate_ (
    	  RateID INT,	
        Code VARCHAR(50),
        Description VARCHAR(200),
        Interval1 INT,
        IntervalN INT,
        ConnectionFee DECIMAL(18, 6),
        Rate DECIMAL(18, 6),
        EffectiveDate DATE,
        INDEX tmp_RateTableRate_RateID (`RateID`)
    );
    
   INSERT INTO tmp_RateTableRate_
	select 
	      r.RateID,
			r.Code,
			r.Description,			
			ifnull(rtr.Interval1,1) as Interval1,
         ifnull(rtr.IntervalN,1) as IntervalN,
			rtr.ConnectionFee,
			IFNULL(rtr.Rate, 0) as Rate,
			IFNULL(rtr.EffectiveDate, NOW()) as EffectiveDate
		 from tblRate r LEFT JOIN tblRateTableRate rtr on r.RateID=rtr.RateID
		 AND r.CodeDeckId = v_codedeckid_ AND  
						 (
						 	( p_Effective = 'Now' AND rtr.EffectiveDate <= NOW() )
						 	OR
						 	( p_Effective = 'Future' AND rtr.EffectiveDate > NOW())
						 	OR p_Effective = 'All'
						 )
		 where rtr.RateTableId = p_ratetableid AND r.CompanyID=p_companyid
		  AND	(p_contryID IS NULL OR r.CountryID = p_contryID)
        AND (p_code IS NULL OR r.Code LIKE REPLACE(p_code, '*', '%'))
        AND (p_description IS NULL OR r.Description LIKE REPLACE(p_description, '*', '%'));
        
        IF p_Effective = 'Now'
		THEN
		   CREATE TEMPORARY TABLE IF NOT EXISTS tmp_RateTableRate4_ as (select * from tmp_RateTableRate_);	        
         DELETE n1 FROM tmp_RateTableRate_ n1, tmp_RateTableRate4_ n2 WHERE n1.EffectiveDate < n2.EffectiveDate 
		   AND  n1.RateID = n2.RateID;
		END IF;
        
        IF p_isExport = 0
    THEN


         SELECT         
				RateID,
                Code,
                Description,
                Interval1,
                IntervalN,
                ConnectionFee,
                Rate,
                EffectiveDate
            FROM tmp_RateTableRate_ 
            ORDER BY
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeDESC') THEN Code
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeASC') THEN Code
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionDESC') THEN Description
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionASC') THEN Description
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateDESC') THEN Rate
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateASC') THEN Rate
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1DESC') THEN Interval1
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1ASC') THEN Interval1
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNDESC') THEN IntervalN
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNASC') THEN IntervalN
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeDESC') THEN ConnectionFee
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeASC') THEN ConnectionFee
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateDESC') THEN EffectiveDate
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateASC') THEN EffectiveDate
                END ASC
            LIMIT p_RowspPage OFFSET v_OffSet_;

        SELECT
            COUNT(RateID) AS totalcount
        FROM tmp_RateTableRate_;

    END IF;
    
    IF p_isExport = 1
    THEN
			 
          select 
            RateID,
                Code,
                Description,
                Interval1,
                IntervalN,
                ConnectionFee,
                Rate,
                EffectiveDate
            FROM tmp_RateTableRate_;

    END IF;
    
 
    SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_CustomerRateClear` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_CustomerRateClear`(
	IN `p_AccountIdList` LONGTEXT,
	IN `p_TrunkId` INT,
	IN `p_TimezonesID` INT,
	IN `p_CodeDeckId` int,
	IN `p_CustomerRateId` LONGTEXT,
	IN `p_code` VARCHAR(50),
	IN `p_description` VARCHAR(200),
	IN `p_CountryId` INT,
	IN `p_CompanyId` INT,
	IN `p_ModifiedBy` VARCHAR(50)
)
BEGIN

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	/*delete tblCustomerRate
	from tblCustomerRate
	INNER JOIN (
		SELECT c.CustomerRateID
		FROM   tblCustomerRate c
		INNER JOIN tblCustomerTrunk
			ON tblCustomerTrunk.TrunkID = c.TrunkID
			AND tblCustomerTrunk.AccountID = c.CustomerID
			AND tblCustomerTrunk.Status = 1
		INNER JOIN tblRate r
			ON c.RateID = r.RateID and r.CodeDeckId=p_CodeDeckId
		WHERE c.TrunkID = p_TrunkId
			AND FIND_IN_SET(c.CustomerID,p_AccountIdList) != 0
			AND ( ( p_code IS NULL ) OR ( p_code IS NOT NULL AND r.Code LIKE REPLACE(p_code,'*', '%')))
			AND ( ( p_description IS NULL ) OR ( p_description IS NOT NULL AND r.Description LIKE REPLACE(p_description,'*', '%')))
			AND ( ( p_CountryId IS NULL )  OR ( p_CountryId IS NOT NULL AND r.CountryID = p_CountryId ) )
	) cr ON cr.CustomerRateID = tblCustomerRate.CustomerRateID;*/

	UPDATE
		tblCustomerRate
	INNER JOIN (
		SELECT
			c.CustomerRateID
		FROM
			tblCustomerRate c
		INNER JOIN tblCustomerTrunk
			ON tblCustomerTrunk.TrunkID = c.TrunkID
			AND tblCustomerTrunk.AccountID = c.CustomerID
			AND tblCustomerTrunk.Status = 1
		INNER JOIN tblRate r
			ON c.RateID = r.RateID and r.CodeDeckId=p_CodeDeckId
		WHERE
			c.TrunkID = p_TrunkId AND
			c.TimezonesID = p_TimezonesID AND
			(
				( -- if single or selected rates delete
					p_CustomerRateId IS NOT NULL AND FIND_IN_SET(c.CustomerRateId,p_CustomerRateId) != 0
				)
				OR
				( -- if bulk rates delete
					p_CustomerRateId IS NULL AND
					FIND_IN_SET(c.CustomerID,p_AccountIdList) != 0  AND
					( ( p_code IS NULL ) OR ( p_code IS NOT NULL AND r.Code LIKE REPLACE(p_code,'*', '%'))) AND
					( ( p_description IS NULL ) OR ( p_description IS NOT NULL AND r.Description LIKE REPLACE(p_description,'*', '%'))) AND
					( ( p_CountryId IS NULL )  OR ( p_CountryId IS NOT NULL AND r.CountryID = p_CountryId ) )
				)
			)
	) cr ON cr.CustomerRateID = tblCustomerRate.CustomerRateID
	SET
		tblCustomerRate.EndDate=NOW();

	CALL prc_ArchiveOldCustomerRate(p_AccountIdList,p_TrunkId,p_TimezonesID,p_ModifiedBy);

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_CustomerRateForExport` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_CustomerRateForExport`(
	IN `p_CompanyID` INT,
	IN `p_CustomerID` INT ,
	IN `p_TrunkID` INT,
	IN `p_NameFormat` VARCHAR(50),
	IN `p_Account` VARCHAR(200),
	IN `p_Trunk` VARCHAR(200) ,
	IN `p_TrunkPrefix` VARCHAR(50),
	IN `p_Effective` VARCHAR(50)
)
BEGIN
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	CALL prc_GetCustomerRate(p_CompanyID,p_CustomerID,p_TrunkID,null,null,null,null,p_Effective,CURDATE(),1,0,0,0,'','',-1);

	SELECT
		p_NameFormat AS AuthRule,
		p_Account AS AccountName,
		p_Trunk AS Trunk,
		p_TrunkPrefix AS CustomerTrunkPrefix,
		Code,
		Description,
		Rate,
		EffectiveDate,
		ConnectionFee,
		Interval1,
		IntervalN,
		Prefix AS TrunkPrefix,
		RatePrefix AS TrunkRatePrefix,
		AreaPrefix AS TrunkAreaPrefix
	FROM tmp_customerrate_;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_CustomerRateInsert` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_CustomerRateInsert`(
	IN `p_CompanyId` INT,
	IN `p_AccountIdList` LONGTEXT ,
	IN `p_TrunkId` VARCHAR(100) ,
	IN `p_TimezonesID` INT,
	IN `p_RateIDList` LONGTEXT,
	IN `p_Rate` DECIMAL(18, 6) ,
	IN `p_RateN` DECIMAL(18, 6) ,
	IN `p_ConnectionFee` DECIMAL(18, 6) ,
	IN `p_EffectiveDate` DATETIME ,
	IN `p_Interval1` INT,
	IN `p_IntervalN` INT,
	IN `p_RoutinePlan` INT,
	IN `p_ModifiedBy` VARCHAR(50)
)
ThisSP:BEGIN
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	INSERT  INTO tblCustomerRate
	(
		RateID ,
		CustomerID ,
		TrunkID ,
		TimezonesID,
		Rate ,
		RateN ,
		ConnectionFee,
		EffectiveDate ,
		EndDate,
		Interval1,
		IntervalN ,
		RoutinePlan,
		CreatedDate ,
		LastModifiedBy ,
		LastModifiedDate
	)
	SELECT
		r.RateID,
		r.AccountId ,
		p_TrunkId ,
		p_TimezonesID,
		p_Rate ,
		p_RateN ,
		p_ConnectionFee,
		p_EffectiveDate ,
		NULL AS EndDate,
		p_Interval1,
		p_IntervalN,
		RoutinePlan,
		NOW() ,
		p_ModifiedBy ,
		NOW()
	FROM
	(
		SELECT
			tblRate.RateID ,
			a.AccountId,
			tblRate.CompanyID,
			RoutinePlan
		FROM
			tblRate ,
			(
				SELECT
					a.AccountId,
					CASE WHEN ctr.TrunkID IS NOT NULL
					THEN p_RoutinePlan
					ELSE 0
					END AS RoutinePlan
				FROM
					tblAccount a
				INNER JOIN tblCustomerTrunk ON TrunkID = p_TrunkId
					AND a.AccountId = tblCustomerTrunk.AccountID
					AND tblCustomerTrunk.Status = 1
				LEFT JOIN tblCustomerTrunk ctr
					ON ctr.TrunkID = p_TrunkId
					AND ctr.AccountID = a.AccountID
					AND ctr.RoutinePlanStatus = 1
				WHERE  FIND_IN_SET(a.AccountID,p_AccountIdList) != 0
			) a
		WHERE FIND_IN_SET(tblRate.RateID,p_RateIDList) != 0
	) r
	LEFT JOIN
	(
		SELECT DISTINCT
			c.RateID,
			c.CustomerID as AccountId ,
			c.TrunkID,
			c.EffectiveDate
		FROM
			tblCustomerRate c
		INNER JOIN tblCustomerTrunk ON tblCustomerTrunk.TrunkID = c.TrunkID
			AND tblCustomerTrunk.AccountID = c.CustomerID
			AND tblCustomerTrunk.Status = 1
		WHERE FIND_IN_SET(c.CustomerID,p_AccountIdList) != 0 AND c.TrunkID = p_TrunkId AND c.TimezonesID = p_TimezonesID
	) cr ON r.RateID = cr.RateID
		AND r.AccountId = cr.AccountId
		AND r.CompanyID = p_CompanyId
		and cr.EffectiveDate = p_EffectiveDate
	WHERE
		r.CompanyID = p_CompanyId
		and cr.RateID is NULL;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_CustomerRatesFileImport` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_CustomerRatesFileImport`(
	IN `p_ProcessID` VARCHAR(200),
	IN `p_tbltemp_name` VARCHAR(200)
)
BEGIN

	DECLARE v_pointer_ INT;
	DECLARE v_rowCount_ INT;
	DECLARE v_TrunkID_ INT;
	DECLARE v_AccountID_ INT;
	DECLARE v_codedeckid_ INT;
	DECLARE v_companyid_ INT;

	SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

	DROP TEMPORARY TABLE IF EXISTS tmp_AccountTrunk_;
	CREATE TEMPORARY TABLE tmp_AccountTrunk_  (
		RowID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
		AccountID INT,
		TrunkID INT
	);
	SET @stm = CONCAT('
	INSERT INTO tmp_AccountTrunk_(AccountID,TrunkID)
	SELECT DISTINCT AccountID,TrunkID FROM `' , p_tbltemp_name , '` ud WHERE ProcessID="' , p_ProcessID , '" AND AccountID IS NOT NULL AND TrunkID IS NOT NULL;
	');

	PREPARE stm FROM @stm;
	EXECUTE stm;
	DEALLOCATE PREPARE stm;

	SET v_pointer_ = 1;
	SET v_rowCount_ = (SELECT COUNT(*)FROM tmp_AccountTrunk_);

	WHILE v_pointer_ <= v_rowCount_
	DO

		SET v_TrunkID_ = (SELECT TrunkID FROM tmp_AccountTrunk_ t WHERE t.RowID = v_pointer_); 
		SET v_AccountID_ = (SELECT AccountID FROM tmp_AccountTrunk_ t WHERE t.RowID = v_pointer_);
		SET v_codedeckid_ = (SELECT CodeDeckId FROM tblCustomerTrunk WHERE tblCustomerTrunk.TrunkID = v_TrunkID_ AND tblCustomerTrunk.AccountID = v_AccountID_ /*AND tblCustomerTrunk.Status = 1 */ );

		IF v_codedeckid_ IS NOT NULL AND (SELECT COUNT(*) FROM tblCodeDeck WHERE CodeDeckId = v_codedeckid_)>0
		THEN

			SET v_companyid_ = (SELECT CompanyId FROM tblCodeDeck WHERE CodeDeckId = v_codedeckid_);			

			-- code insert and update rate id in temp table
			CALL prc_updateRateID(v_AccountID_,v_codedeckid_,p_tbltemp_name,p_ProcessID);

			-- CALL prc_GetCustomerRate(v_companyid_,v_AccountID_,v_TrunkID_,null,null,null,'All',1,0,0,0,'','',-1);
			
			-- customerrate insert,update and delete
			CALL prc_putCustomerCodeRate(v_AccountID_,v_TrunkID_,p_tbltemp_name,p_ProcessID);

		END IF;

		SET v_pointer_ = v_pointer_ + 1;

	END WHILE;

	
	SET @stm = CONCAT('
	DELETE FROM `' , p_tbltemp_name , '` WHERE ProcessID="' , p_ProcessID , '" ;
	');

	PREPARE stm FROM @stm;
	EXECUTE stm;
	DEALLOCATE PREPARE stm;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_CustomerRateUpdate` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_CustomerRateUpdate`(
	IN `p_AccountIdList` LONGTEXT ,
	IN `p_TrunkId` VARCHAR(100) ,
	IN `p_TimezonesID` INT,
	IN `p_CustomerRateIDList` LONGTEXT,
	IN `p_Rate` DECIMAL(18, 6) ,
	IN `p_RateN` DECIMAL(18, 6) ,
	IN `p_ConnectionFee` DECIMAL(18, 6) ,
	IN `p_EffectiveDate` DATETIME ,
	IN `p_Interval1` INT,
	IN `p_IntervalN` INT,
	IN `p_RoutinePlan` INT,
	IN `p_ModifiedBy` VARCHAR(50)
)
ThisSP:BEGIN
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	DROP TEMPORARY TABLE IF EXISTS tmp_CustomerRates_;
    CREATE TEMPORARY TABLE tmp_CustomerRates_ (
        CustomerRateID INT,
        RateID INT,
        CustomerID INT,
        Interval1 INT,
        IntervalN  INT,
        Rate DECIMAL(18, 6),
        RateN DECIMAL(18, 6),
        PreviousRate DECIMAL(18, 6),
        ConnectionFee DECIMAL(18, 6),
        EffectiveDate DATE,
        EndDate DATE,
        CreatedDate DATETIME,
        CreatedBy VARCHAR(50),
        LastModifiedDate DATETIME,
        LastModifiedBy VARCHAR(50),
        TrunkID INT,
        TimezonesID INT,
        RoutinePlan INT,
        INDEX tmp_CustomerRates__CustomerRateID (`CustomerRateID`)/*,
        INDEX tmp_CustomerRates__RateID (`RateID`),
        INDEX tmp_CustomerRates__TrunkID (`TrunkID`),
        INDEX tmp_CustomerRates__EffectiveDate (`EffectiveDate`)*/
    );

	-- if p_EffectiveDate null means multiple rates update
	-- and if multiple rates update then we don't allow to change EffectiveDate
	-- we only allow EffectiveDate change when single edit

	-- insert rates in temp table which needs to update
	INSERT INTO tmp_CustomerRates_
	(
		CustomerRateID,
		RateID,
		CustomerID,
		Interval1,
		IntervalN,
		Rate,
		RateN,
		PreviousRate,
		ConnectionFee,
		EffectiveDate,
		EndDate,
		CreatedDate,
		CreatedBy,
		LastModifiedDate,
		LastModifiedBy,
		TrunkID,
		TimezonesID,
		RoutinePlan
	)
	SELECT
		cr.CustomerRateID,
		cr.RateID,
		cr.CustomerID,
		p_Interval1 AS Interval1,
		p_IntervalN AS IntervalN,
		p_Rate AS Rate,
		p_RateN AS RateN,
		cr.PreviousRate,
		p_ConnectionFee AS ConnectionFee,
		IFNULL(p_EffectiveDate,cr.EffectiveDate) AS EffectiveDate, -- if p_EffectiveDate null take exiting EffectiveDate
		cr.EndDate,
		cr.CreatedDate,
		cr.CreatedBy,
		NOW() AS LastModifiedDate,
		p_ModifiedBy AS LastModifiedBy,
		cr.TrunkID,
		cr.TimezonesID,
		CASE WHEN ctr.TrunkID IS NOT NULL
		THEN p_RoutinePlan
		ELSE NULL
		END AS RoutinePlan
	FROM
		tblCustomerRate cr
	LEFT JOIN tblCustomerTrunk ctr
		ON ctr.TrunkID = cr.TrunkID
		AND ctr.AccountID = cr.CustomerID
		AND ctr.RoutinePlanStatus = 1
	LEFT JOIN
	(
		SELECT
			RateID,CustomerID
		FROM
			tblCustomerRate
		WHERE
			EffectiveDate = p_EffectiveDate AND
			FIND_IN_SET(tblCustomerRate.CustomerRateID,p_CustomerRateIDList) = 0
	) crc ON crc.RateID=cr.RateID AND crc.CustomerID=cr.CustomerID
	WHERE
		 cr.TimezonesID = p_TimezonesID AND FIND_IN_SET(cr.CustomerRateID,p_CustomerRateIDList) != 0 AND crc.RateID IS NULL;

	-- update EndDate to Archive rates which needs to update
	UPDATE
		tblCustomerRate cr
	JOIN
		tmp_CustomerRates_ temp ON cr.CustomerRateID=temp.CustomerRateID
	SET
		cr.EndDate = NOW();

	-- archive rates which rates' EndDate < NOW()
	CALL prc_ArchiveOldCustomerRate(p_AccountIdList, p_TrunkId, p_TimezonesID, p_ModifiedBy);

	-- insert rates in tblCustomerRate with updated values
	INSERT INTO tblCustomerRate
	(
		CustomerRateID,
		RateID,
		CustomerID,
		Interval1,
		IntervalN,
		Rate,
		RateN,
		PreviousRate,
		ConnectionFee,
		EffectiveDate,
		EndDate,
		CreatedDate,
		CreatedBy,
		LastModifiedDate,
		LastModifiedBy,
		TrunkID,
		TimezonesID,
		RoutinePlan
	)
	SELECT
		NULL, -- primary key
		RateID,
		CustomerID,
		Interval1,
		IntervalN,
		Rate,
		RateN,
		PreviousRate,
		ConnectionFee,
		EffectiveDate,
		EndDate,
		CreatedDate,
		CreatedBy,
		LastModifiedDate,
		LastModifiedBy,
		TrunkID,
		TimezonesID,
		RoutinePlan
	FROM
		tmp_CustomerRates_;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_CustomerRateUpdateBySelectedRateId` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_CustomerRateUpdateBySelectedRateId`(
	IN `p_CompanyId` INT,
	IN `p_AccountIdList` LONGTEXT ,
	IN `p_RateIDList` LONGTEXT ,
	IN `p_TrunkId` VARCHAR(100) ,
	IN `p_Rate` DECIMAL(18, 6) ,
	IN `p_ConnectionFee` DECIMAL(18, 6) ,
	IN `p_EffectiveDate` DATETIME ,
	IN `p_EndDate` DATETIME,
	IN `p_Interval1` INT,
	IN `p_IntervalN` INT,
	IN `p_RoutinePlan` INT,
	IN `p_ModifiedBy` VARCHAR(50)
)
ThisSP:BEGIN
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	UPDATE  tblCustomerRate
	INNER JOIN (
		SELECT
			c.CustomerRateID,c.EffectiveDate,
			CASE WHEN ctr.TrunkID IS NOT NULL
			THEN p_RoutinePlan
			ELSE 0
			END AS RoutinePlan
		FROM
			tblCustomerRate c
		INNER JOIN tblCustomerTrunk ON tblCustomerTrunk.TrunkID = c.TrunkID
			AND tblCustomerTrunk.AccountID = c.CustomerID
			AND tblCustomerTrunk.Status = 1
			AND c.EffectiveDate = p_EffectiveDate
		LEFT JOIN tblCustomerTrunk ctr
			ON ctr.TrunkID = c.TrunkID
			AND ctr.AccountID = c.CustomerID
			AND ctr.RoutinePlanStatus = 1
	) cr ON cr.CustomerRateID = tblCustomerRate.CustomerRateID and cr.EffectiveDate = p_EffectiveDate
	SET
		
		tblCustomerRate.LastModifiedBy = p_ModifiedBy ,
		tblCustomerRate.LastModifiedDate = NOW(),
		tblCustomerRate.EndDate = NOW()
	WHERE tblCustomerRate.TrunkID = p_TrunkId
		AND FIND_IN_SET(tblCustomerRate.RateID,p_RateIDList) != 0
		AND FIND_IN_SET(tblCustomerRate.CustomerID,p_AccountIdList) != 0;

   CALL prc_ArchiveOldCustomerRate(p_AccountIdList, p_TrunkId, p_ModifiedBy);

        INSERT  INTO tblCustomerRate
                ( RateID ,
                  CustomerID ,
                  TrunkID ,
                  Rate ,
					   ConnectionFee,
                  EffectiveDate ,
                  EndDate,
                  Interval1,
				  		IntervalN ,
				  		RoutinePlan,
                  CreatedDate ,
                  LastModifiedBy ,
                  LastModifiedDate
                )
                SELECT  r.RateID,
                        r.AccountId ,
                        p_TrunkId ,
                        p_Rate ,
								p_ConnectionFee,
                        p_EffectiveDate ,
                        p_EndDate,
                        p_Interval1,
					    		p_IntervalN,
								RoutinePlan,
                        NOW() ,
                        p_ModifiedBy ,
                        NOW()
                FROM    ( SELECT    tblRate.RateID ,
                                    a.AccountId,
                                    tblRate.CompanyID,
									RoutinePlan
                          FROM      tblRate ,
                                    ( SELECT  a.AccountId,
													CASE WHEN ctr.TrunkID IS NOT NULL
														THEN p_RoutinePlan
														ELSE 0
													END AS RoutinePlan
                                      FROM tblAccount a
												  INNER JOIN tblCustomerTrunk ON TrunkID = p_TrunkId
                                      		AND a.AccountId = tblCustomerTrunk.AccountID
                                          AND tblCustomerTrunk.Status = 1
												LEFT JOIN tblCustomerTrunk ctr
													ON ctr.TrunkID = p_TrunkId
													AND ctr.AccountID = a.AccountID
													AND ctr.RoutinePlanStatus = 1
												WHERE  FIND_IN_SET(a.AccountID,p_AccountIdList) != 0
                                    ) a
                          WHERE FIND_IN_SET(tblRate.RateID,p_RateIDList) != 0
                        ) r
                        LEFT JOIN ( SELECT DISTINCT
                                                    c.RateID,
                                                    c.CustomerID as AccountId ,
                                                    c.TrunkID,
                                                    c.EffectiveDate
                                          FROM      tblCustomerRate c
                                                    INNER JOIN tblCustomerTrunk ON tblCustomerTrunk.TrunkID = c.TrunkID
                                                              AND tblCustomerTrunk.AccountID = c.CustomerID
                                                              AND tblCustomerTrunk.Status = 1
                                          WHERE FIND_IN_SET(c.CustomerID,p_AccountIdList) != 0 AND c.TrunkID = p_TrunkId
                                        ) cr ON r.RateID = cr.RateID
                                                AND r.AccountId = cr.AccountId
                                                AND r.CompanyID = p_CompanyId
                                                and cr.EffectiveDate = p_EffectiveDate
                WHERE
                 r.CompanyID = p_CompanyId
                 and cr.RateID is NULL;

 

      SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_deleteArchiveOldRate` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_deleteArchiveOldRate`(
	IN `p_CompanyID` INT,
	IN `p_DeleteDate` DATETIME,
	IN `p_processID` VARCHAR(200)
)
BEGIN
 	
 	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	  
	  CALL telsomespainRM.prc_UpdateMysqlPID(p_processID);
	  
	  DELETE
			tblCustomerRateArchive
	  FROM tblCustomerRateArchive 
	  INNER JOIN tblAccount 
		ON tblAccount.AccountID=tblCustomerRateArchive.AccountId
	  WHERE 
	  tblAccount.CompanyId=p_CompanyID
	  AND tblCustomerRateArchive.EffectiveDate <= p_DeleteDate;

		
	  DELETE
	  		tblVendorRateArchive
	  FROM tblVendorRateArchive 
	  INNER JOIN tblAccount 
		ON tblAccount.AccountID=tblVendorRateArchive.AccountId
	  WHERE
		tblAccount.CompanyId=p_CompanyID
	  AND EffectiveDate <= p_DeleteDate;


	  DELETE
	  		tblRateTableRateArchive
	  FROM tblRateTableRateArchive 
	  INNER JOIN tblRateTable 
	  ON tblRateTable.RateTableId=tblRateTableRateArchive.RateTableId
	  WHERE 
	  tblRateTable.CompanyId=p_CompanyID
	  AND tblRateTableRateArchive.EffectiveDate <= p_DeleteDate;	  	  
	  
	 
   SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ; 
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_DeleteDynamicFieldStatus` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_DeleteDynamicFieldStatus`(
	IN `d_CompanyID` INT,
	IN `d_user_name` VARCHAR(50),
	IN `d_Type` VARCHAR(50),
	IN `d_FieldName` VARCHAR(50),
	IN `d_FieldDomType` VARCHAR(50),
	IN `d_ItemTypeID` VARCHAR(50),
	IN `d_Status` INT
)
BEGIN
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	delete tblDynamicFields from tblDynamicFields left join tblDynamicFieldsValue on tblDynamicFieldsValue.DynamicFieldsID = tblDynamicFields.DynamicFieldsID
	where tblDynamicFieldsValue.DynamicFieldsID is null
		AND tblDynamicFields.CompanyID = d_CompanyID
		AND tblDynamicFields.`Type`= d_Type
		AND(d_FieldName = '' OR tblDynamicFields.FieldName like Concat('%',d_FieldName,'%'))
		AND(d_FieldDomType = '' OR tblDynamicFields.FieldDomType like Concat('%',d_FieldDomType,'%'))
      AND(d_Status = 9 OR tblDynamicFields.Status = d_Status)
      ;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_deleteJobOrCronJobLogByRetention` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_deleteJobOrCronJobLogByRetention`(IN `p_CompanyID` INT, IN `p_DeleteDate` DATETIME, IN `p_ActionName` VARCHAR(200))
BEGIN
 	
 	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	
	IF p_ActionName = 'Cronjob'
	THEN
		
		DELETE
			 tblCronJobLog
		FROM tblCronJobLog
		INNER JOIN tblCronJob
		 	 ON tblCronJob.CronJobID = tblCronJobLog.CronJobID
		WHERE tblCronJob.CompanyID = p_CompanyID
			 AND tblCronJobLog.created_at < p_DeleteDate;
	
	END IF;	

	
	IF p_ActionName = 'Job'
	THEN
		
		DELETE 
			tblJobFile
		FROM tblJobFile
		INNER JOIN  tblJob
			ON tblJob.JobID = tblJobFile.JobID
	  	INNER JOIN tblJobType
			 ON tblJob.JobTypeID = tblJobType.JobTypeID
		WHERE tblJobType.`Code` NOT IN('CD','VD','VU') 
			AND tblJob.CompanyID = p_CompanyID 
			AND tblJob.created_at < p_DeleteDate;

		
			
		DELETE
			tblJob
		FROM tblJob
		INNER JOIN tblJobType
			ON tblJob.JobTypeID = tblJobType.JobTypeID
		WHERE tblJobType.`Code` NOT IN('CD','VD','VU')
			AND tblJob.CompanyID = p_CompanyID 
	  		AND tblJob.created_at < p_DeleteDate;
	
	END IF;	
	
	
	IF p_ActionName = 'CustomerRateSheet'
	THEN
		
			
		DELETE
			 tblJob
		FROM tblJob
		INNER JOIN tblJobType
			ON tblJob.JobTypeID = tblJobType.JobTypeID
		WHERE tblJobType.`Code` IN('CD')
			AND tblJob.CompanyID = p_CompanyID 
	  		AND tblJob.created_at < p_DeleteDate;
	
	END IF;	
	
	
	IF p_ActionName = 'VendorRateSheet'
	THEN
		
		
		DELETE 
			tblJobFile
		FROM tblJobFile
		INNER JOIN  tblJob
			ON tblJob.JobID = tblJobFile.JobID
	  	INNER JOIN tblJobType
			 ON tblJob.JobTypeID = tblJobType.JobTypeID
		WHERE tblJobType.`Code` IN('VD','VU') 
			AND tblJob.CompanyID = p_CompanyID 
			AND tblJob.created_at < p_DeleteDate;	
			
		DELETE
			 tblJob
		FROM tblJob
		INNER JOIN tblJobType
			ON tblJob.JobTypeID = tblJobType.JobTypeID
		WHERE tblJobType.`Code` IN('VD','VU')
			AND tblJob.CompanyID = p_CompanyID 
	  		AND tblJob.created_at < p_DeleteDate;
	
	END IF;	
		
   SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ; 
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_DeleteTicketGroup` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_DeleteTicketGroup`(
	IN `p_CompanyID` INT,
	IN `p_GroupID` INT
)
BEGIN

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;




	DELETE tl FROM
		tblTicketLog tl
		inner join tblTickets t
		on tl.TicketID = t.TicketID
	where t.`Group` = p_GroupID
		AND t.CompanyID = p_CompanyID;









	DELETE td FROM
		tblTicketsDetails td
		inner join tblTickets t
		on td.TicketID = t.TicketID
	where t.`Group` = p_GroupID
		AND t.CompanyID = p_CompanyID;





	DELETE FROM tblTicketsDeletedLog where tblTicketsDeletedLog.`Group` = p_GroupID AND CompanyID = p_CompanyID;




	DELETE ae FROM
		AccountEmailLogDeletedLog ae
		inner join tblTickets t
		on ae.TicketID = t.TicketID
	where t.`Group` = p_GroupID
		AND t.CompanyID = p_CompanyID;




	DELETE ae FROM
		AccountEmailLog ae
		inner join tblTickets t
		on ae.TicketID = t.TicketID
	where t.`Group` = p_GroupID
		AND t.CompanyID = p_CompanyID;




	DELETE FROM tblTickets where tblTickets.`Group` = p_GroupID AND CompanyID = p_CompanyID;




	DELETE FROM tblTicketGroups where GroupID = p_GroupID AND CompanyID = p_CompanyID;


	DELETE FROM tblTicketGroupAgents where GroupID = p_GroupID;



SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_deleteTickets` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_deleteTickets`(
	IN `p_CompanyID` INT,
	IN `p_DeleteDate` DATETIME,
	IN `p_processID` VARCHAR(200)
)
BEGIN
 	DECLARE p_status INT;
 	
 	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
 	
 	CALL telsomespainRM.prc_UpdateMysqlPID(p_processID);
 	
 	DROP TEMPORARY TABLE IF EXISTS tmp_attachments_;
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_attachments_(
		attachment LONGTEXT
	);
	  
	  -- get closed StatusID
	  SELECT 
	  		tblTicketfieldsValues.ValuesID INTO p_status 
	  FROM tblTicketfields 
	  INNER JOIN tblTicketfieldsValues 
	 	 	ON tblTicketfields.TicketFieldsID=tblTicketfieldsValues.FieldsID 
	  WHERE tblTicketfields.FieldType='default_status' 
		  AND tblTicketfieldsValues.FieldValueAgent='Closed';
	  
	  
	  DELETE
	  		tblJunkTicketEmail
	  FROM tblJunkTicketEmail 
	  INNER JOIN tblTickets
		ON tblTickets.TicketID=tblJunkTicketEmail.TicketID
	  WHERE 
		  tblTickets.CompanyID=p_CompanyID
		  AND tblTickets.`Status`=p_status
		  AND tblTickets.updated_at <= p_DeleteDate;
	  	  
	  DELETE
	  		tblTicketLog
	  FROM tblTicketLog 
	  INNER JOIN tblTickets
		ON tblTickets.TicketID=tblTicketLog.TicketID
	  WHERE 
		tblTickets.CompanyID=p_CompanyID
		AND tblTickets.`Status`=p_status
		AND tblTickets.updated_at <= p_DeleteDate;
	  
	  -- get attachment to delete files later
	  INSERT INTO tmp_attachments_
	  SELECT 
	  tblTicketsDeletedLog.AttachmentPaths
	  FROM tblTicketsDeletedLog
	  INNER JOIN tblTickets
	  	ON tblTickets.TicketID=tblTicketsDeletedLog.TicketID
	  WHERE 
	  tblTickets.CompanyID=p_CompanyID
	  AND tblTickets.`Status`=p_status
	  AND tblTicketsDeletedLog.AttachmentPaths!=''
	  AND tblTickets.updated_at <= p_DeleteDate;
	  
	  DELETE
	  		tblTicketsDeletedLog
	  FROM tblTicketsDeletedLog 
	  INNER JOIN tblTickets
	  	ON tblTickets.TicketID=tblTicketsDeletedLog.TicketID
	  WHERE 
	  	tblTickets.CompanyID=p_CompanyID
	  	AND tblTickets.`Status`=p_status
	  	AND tblTickets.updated_at <= p_DeleteDate;
	  
	  INSERT INTO tmp_attachments_
	  SELECT 
	  AccountEmailLogDeletedLog.AttachmentPaths
	  FROM AccountEmailLogDeletedLog
	  INNER JOIN tblTickets
	  ON tblTickets.TicketID=AccountEmailLogDeletedLog.TicketID
	  WHERE 
	  tblTickets.CompanyID=p_CompanyID
	  AND tblTickets.`Status`=p_status
	  AND AccountEmailLogDeletedLog.AttachmentPaths!=''
	  AND tblTickets.updated_at <= p_DeleteDate;
	  
	  DELETE
	  		AccountEmailLogDeletedLog
	  FROM AccountEmailLogDeletedLog 
	  INNER JOIN tblTickets
	  	ON tblTickets.TicketID=AccountEmailLogDeletedLog.TicketID
	  WHERE 
	  tblTickets.CompanyID=p_CompanyID
	  AND tblTickets.`Status`=p_status
	  AND tblTickets.updated_at <= p_DeleteDate;
	  
	  INSERT INTO tmp_attachments_
	  SELECT 
	  AccountEmailLog.AttachmentPaths
	  FROM AccountEmailLog
	  INNER JOIN tblTickets
	  	ON tblTickets.TicketID=AccountEmailLog.TicketID
	  WHERE 
	  tblTickets.CompanyID=p_CompanyID
	  AND tblTickets.`Status`=p_status
	  AND AccountEmailLog.AttachmentPaths!=''
	  AND tblTickets.updated_at <= p_DeleteDate;
	  	  
	  DELETE
	  		AccountEmailLog
	  FROM AccountEmailLog 
	  INNER JOIN tblTickets
	  	ON tblTickets.TicketID=AccountEmailLog.TicketID
	  WHERE 
	  tblTickets.CompanyID=p_CompanyID
	  AND tblTickets.`Status`=p_status
	  AND tblTickets.updated_at <= p_DeleteDate;	  
	  
	  INSERT INTO tmp_attachments_
	  SELECT
	  		AttachmentPaths
	  FROM tblTickets
	  WHERE 
	  CompanyID=p_CompanyID
	  AND tblTickets.`Status`=p_status
	  AND AttachmentPaths!=''
	  AND updated_at <= p_DeleteDate;
	  
	  DELETE 
	  FROM tblTickets
	  WHERE 
	  CompanyID=p_CompanyID
	  AND tblTickets.`Status`=p_status
	  AND updated_at <= p_DeleteDate; 
	   
	  SELECT * FROM tmp_attachments_;
		 
   SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ; 
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_DialStringCodekBulkUpdate` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_DialStringCodekBulkUpdate`(IN `p_dialstringid` int, IN `p_up_chargecode` int, IN `p_up_description` int, IN `p_up_forbidden` int, IN `p_critearea` int, IN `p_dialstringcode` varchar(500), IN `p_critearea_dialstring` varchar(250), IN `p_critearea_chargecode` varchar(250), IN `p_critearea_description` varchar(250), IN `p_critearea_forbidden` INT, IN `p_chargecode` varchar(250), IN `p_description` varchar(250), IN `p_forbidden` varchar(250), IN `p_isAction` int )
BEGIN

   SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; 
   
   DROP TEMPORARY TABLE IF EXISTS tmp_dialstringcode;
    CREATE TEMPORARY TABLE tmp_dialstringcode (
      DialStringCodeID INT
    ); 
    
    IF p_critearea = 0
    THEN
    	
    		INSERT INTO tmp_dialstringcode
			  SELECT DialStringCodeID from tblDialStringCode
				where FIND_IN_SET(DialStringCodeID,p_dialstringcode)
						AND DialStringID = p_dialstringid;
    	
    END IF;
    
    IF p_critearea = 1
    THEN
    	
    		INSERT INTO tmp_dialstringcode
			  SELECT DialStringCodeID
			   FROM tblDialStringCode
				WHERE DialStringID = p_dialstringid
						AND (Forbidden = p_critearea_forbidden)
						AND (p_critearea_dialstring IS NULL OR DialString LIKE REPLACE(p_critearea_dialstring, '*', '%'))
		            AND (p_critearea_chargecode IS NULL OR ChargeCode LIKE REPLACE(p_critearea_chargecode, '*', '%'))
      		      AND (p_critearea_description IS NULL OR Description LIKE REPLACE(p_critearea_description, '*', '%'));
    	
    END IF;
    
    IF p_isAction = 0
    THEN
    
    	IF p_up_chargecode = 1
    	THEN
			    	
    		UPDATE tblDialStringCode
    		 INNER JOIN tmp_dialstringcode dc 
    		 	ON dc.DialStringCodeID = tblDialStringCode.DialStringCodeID
    		 SET ChargeCode = p_chargecode
			 WHERE tblDialStringCode.DialStringID = p_dialstringid;	
    	
    	END IF;
    	
    	IF p_up_description = 1
    	THEN

    		UPDATE tblDialStringCode
    		 INNER JOIN tmp_dialstringcode dc 
    		 	ON dc.DialStringCodeID = tblDialStringCode.DialStringCodeID
    		 SET Description = p_description
			 WHERE tblDialStringCode.DialStringID = p_dialstringid;	
    	
    	END IF;
    	
    	IF p_up_forbidden = 1
    	THEN
    	
    		UPDATE tblDialStringCode
    		 INNER JOIN tmp_dialstringcode dc 
    		 	ON dc.DialStringCodeID = tblDialStringCode.DialStringCodeID
    		 SET Forbidden = p_forbidden
			 WHERE tblDialStringCode.DialStringID = p_dialstringid;	
    	
    	END IF;
    
    END IF;
    
    IF p_isAction = 1
    THEN
    	
    	DELETE tblDialStringCode
    		FROM tblDialStringCode
    		 INNER JOIN( SELECT dc.DialStringCodeID FROM tmp_dialstringcode dc) dpc 
    		 	ON dpc.DialStringCodeID = tblDialStringCode.DialStringCodeID
			 WHERE tblDialStringCode.DialStringID = p_dialstringid;	
    	
    END IF;
    
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_editpreference` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_editpreference`(
	IN `p_groupby` VARCHAR(50),
	IN `p_preference` INT,
	IN `p_accountId` INT,
	IN `p_trunk` INT,
	IN `p_TimezonesID` INT,
	IN `p_rowcode` INT,
	IN `p_codedeckId` INT,
	IN `p_description` VARCHAR(200),
	IN `p_username` VARCHAR(50)
)
BEGIN

	DECLARE v_description VARCHAR(200);
	DECLARE v_vendorPreferenceId int;
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;


	DROP TEMPORARY TABLE IF EXISTS tmp_pref0;
	CREATE TEMPORARY TABLE tmp_pref0(
		RateId INT
	);

	DROP TEMPORARY TABLE IF EXISTS tmp_pref1;
	CREATE TEMPORARY TABLE tmp_pref1(
		VendorPreferenceID INT,
		Preference INT
	);

		IF p_groupby = 'description' THEN

				IF p_preference = 0 THEN

					INSERT INTO tmp_pref0
						select DISTINCT RateId
						FROM (
						select vr.RateId
							 from tblVendorRate vr
							 	 inner join tblRate r
								   on vr.RateId=r.RateID
						    where vr.AccountId = p_accountId AND vr.TrunkID=p_trunk AND vr.TimezonesID = p_TimezonesID AND r.Description = p_description) tbl;


						INSERT INTO tmp_pref1
						select VendorPreferenceID,Preference
						FROM (
						select vp.VendorPreferenceID,vp.Preference
							 from tblVendorPreference vp
							 	 inner join tmp_pref0 tmp0
								   on vp.RateId=tmp0.RateID
						    where vp.AccountId = p_accountId AND vp.TrunkID=p_trunk AND vp.TimezonesID = p_TimezonesID) tbl1;

						select max(Preference) as Preference from tmp_pref1;

				ELSE


					INSERT INTO tmp_pref0
						select DISTINCT RateId
						FROM (
						select vr.RateId
							 from tblVendorRate vr
							 	 inner join tblRate r
								   on vr.RateId=r.RateID
						    where vr.AccountId = p_accountId AND vr.TrunkID=p_trunk AND vr.TimezonesID = p_TimezonesID AND r.Description = p_description) tbl;

					/* Update preference */
					 UPDATE tblVendorPreference
						INNER JOIN tmp_pref0 temp
							ON tblVendorPreference.RateId = temp.RateID
						SET tblVendorPreference.Preference = p_preference,created_at=NOW(),CreatedBy=p_username
						WHERE tblVendorPreference.AccountId = p_accountId AND tblVendorPreference.TrunkID = p_trunk AND tblVendorPreference.TimezonesID = p_TimezonesID ;

					 /* insert preference if not in tblVendorPreference */
					 insert into tblVendorPreference (AccountId,Preference,RateID,TrunkID,TimezonesID,CreatedBy,created_at)
						    select p_accountId as AccountId, p_preference as Preference,tmp0.RateID as RateId,p_trunk as TrunkID, p_TimezonesID AS TimezonesID,p_username as CreatedBy,NOW() as created_at
							 from  tmp_pref0 tmp0
							 	 left join tblVendorPreference vp
								   on vp.RateId=tmp0.RateID
								   AND vp.AccountId = p_accountId AND vp.TrunkID=p_trunk AND vp.TimezonesID = p_TimezonesID
						    where  vp.VendorPreferenceID IS NULL;


				END IF;
		ELSE

				IF p_preference = 0 THEN

						select distinct vp.Preference
							 from tblVendorRate vr
							 	 inner join tblRate r
								   on vr.RateId=r.RateID
								 inner join tblVendorPreference vp
								   on r.RateID=vp.RateId and vr.AccountId=vp.AccountId and vr.TrunkID=vp.TrunkID and vr.TimezonesID=vp.TimezonesID
						    where vp.AccountId = p_accountId AND vr.TrunkID=p_trunk AND vr.TimezonesID = p_TimezonesID AND r.Code = p_rowcode;

				ELSE



						INSERT INTO tmp_pref0
						select DISTINCT RateId
						FROM (
						select vr.RateId
							 from tblVendorRate vr
							 	 inner join tblRate r
								   on vr.RateId=r.RateID
						    where vr.AccountId = p_accountId AND vr.TrunkID=p_trunk AND vr.TimezonesID = p_TimezonesID AND r.Code = p_rowcode) tbl;

					/* Update preference */
					 UPDATE tblVendorPreference
						INNER JOIN tmp_pref0 temp
							ON tblVendorPreference.RateId = temp.RateID
						SET tblVendorPreference.Preference = p_preference,created_at=NOW(),CreatedBy=p_username
						WHERE tblVendorPreference.AccountId = p_accountId AND tblVendorPreference.TrunkID = p_trunk AND tblVendorPreference.TimezonesID = p_TimezonesID;

					 /* insert preference if not in tblVendorPreference */
					 insert into tblVendorPreference (AccountId,Preference,RateID,TrunkID,TimezonesID,CreatedBy,created_at)
						    select p_accountId as AccountId, p_preference as Preference,tmp0.RateID as RateId,p_trunk as TrunkID,p_TimezonesID AS TimezonesID,p_username as CreatedBy,NOW() as created_at
							 from  tmp_pref0 tmp0
							 	 left join tblVendorPreference vp
								   on vp.RateId=tmp0.RateID
								   AND vp.AccountId = p_accountId AND vp.TrunkID=p_trunk AND vp.TimezonesID = p_TimezonesID
						    where  vp.VendorPreferenceID IS NULL;



				END IF;

		END IF;




SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getAccountAuditExportLog` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getAccountAuditExportLog`(
	IN `p_CompanyID` INT,
	IN `p_GatewayID` INT
)
BEGIN
    DECLARE v_last_time_exist INT DEFAULT 0;
    DECLARE v_last_time DATETIME;
    DECLARE v_start_time DATETIME;
    DECLARE v_end_time DATETIME;
    DECLARE v_cur_date DATE DEFAULT CURDATE();
    DECLARE v_cur_time DATETIME DEFAULT NOW();

    SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

    SELECT end_time INTO v_last_time FROM tblAccountAuditExportLog WHERE CompanyID=p_CompanyID AND CompanyGatewayID=p_GatewayID AND Type='account' AND Status=1 ORDER BY AccountAuditExportLogID DESC LIMIT 1;

    IF (v_last_time IS NOT NULL AND v_last_time != '')
    THEN
      

        SELECT
             MIN(tad.created_at), MAX(tad.created_at) INTO v_start_time, v_end_time
        FROM
            tblAuditHeader AS tah
        LEFT JOIN
            tblAuditDetails AS tad ON tah.AuditHeaderID=tad.AuditHeaderID
        LEFT JOIN
            tblDynamicFieldsValue AS dfv ON dfv.ParentID=tah.ParentColumnID
        LEFT JOIN
            tblDynamicFields AS df ON df.DynamicFieldsID=dfv.DynamicFieldsID
        WHERE
            df.FieldName='Gateway' AND find_in_set(p_GatewayID,dfv.FieldValue) > 0 AND tah.Type='account' AND tah.Date>=DATE(v_last_time) AND tah.Date<=DATE(v_cur_date) AND tad.created_at>v_last_time;

        IF ((v_start_time IS NOT NULL AND v_start_time != '') AND (v_end_time IS NOT NULL AND v_end_time != ''))
        THEN
            INSERT INTO tblAccountAuditExportLog (CompanyID,CompanyGatewayID,Type,start_time,end_time,created_at) VALUES (p_CompanyID, p_GatewayID, 'account', v_start_time, v_end_time, v_cur_time);
        END IF;

        SELECT
            tah.ParentColumnID,tah.ParentColumnName,tad.ColumnName,tad.OldValue,tad.NewValue,v_start_time AS start_time,v_end_time AS end_time,v_cur_time AS created_at
        FROM
            tblAuditHeader AS tah
        LEFT JOIN
            tblAuditDetails AS tad ON tah.AuditHeaderID=tad.AuditHeaderID
        LEFT JOIN
            tblDynamicFieldsValue AS dfv ON dfv.ParentID=tah.ParentColumnID
        LEFT JOIN
            tblDynamicFields AS df ON df.DynamicFieldsID=dfv.DynamicFieldsID
        WHERE
            df.FieldName='Gateway' AND find_in_set(p_GatewayID,dfv.FieldValue) > 0 AND tah.Type='account' AND tah.Date>=DATE(v_last_time) AND tah.Date<=DATE(v_cur_date) AND tad.created_at>v_last_time;

    ELSE
        SELECT
            MIN(tad.created_at), MAX(tad.created_at) INTO v_start_time, v_end_time
        FROM
            tblAuditHeader AS tah
        LEFT JOIN
            tblAuditDetails AS tad ON tah.AuditHeaderID=tad.AuditHeaderID
        LEFT JOIN
            tblDynamicFieldsValue AS dfv ON dfv.ParentID=tah.ParentColumnID
        LEFT JOIN
            tblDynamicFields AS df ON df.DynamicFieldsID=dfv.DynamicFieldsID
        WHERE
            df.FieldName='Gateway' AND find_in_set(p_GatewayID,dfv.FieldValue) > 0 AND tah.Type='account' AND tah.Date>=(v_cur_date - INTERVAL 1 DAY) AND tah.Date<=v_cur_date AND tad.created_at<=v_cur_time;

        IF ((v_start_time IS NOT NULL AND v_start_time != '') AND (v_end_time IS NOT NULL AND v_end_time != ''))
        THEN
            INSERT INTO tblAccountAuditExportLog (CompanyID,CompanyGatewayID,Type,start_time,end_time,created_at) VALUES (p_CompanyID, p_GatewayID, 'account', v_start_time, v_end_time, v_cur_time);
        END IF;

        SELECT
            tah.ParentColumnID,tah.ParentColumnName,tad.ColumnName,tad.OldValue,tad.NewValue,v_start_time AS start_time,v_end_time AS end_time,v_cur_time AS created_at
        FROM
            tblAuditHeader AS tah
        LEFT JOIN
            tblAuditDetails AS tad ON tah.AuditHeaderID=tad.AuditHeaderID
        LEFT JOIN
            tblDynamicFieldsValue AS dfv ON dfv.ParentID=tah.ParentColumnID
        LEFT JOIN
            tblDynamicFields AS df ON df.DynamicFieldsID=dfv.DynamicFieldsID
        WHERE
            df.FieldName='Gateway' AND find_in_set(p_GatewayID,dfv.FieldValue) > 0 AND tah.Type='account' AND tah.Date>=(v_cur_date - INTERVAL 1 DAY) AND tah.Date<=v_cur_date AND tad.created_at<=v_cur_time;
    END IF;

    SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetAccountBalanceHistory` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetAccountBalanceHistory`(IN `p_CompanyID` INT, IN `p_AccountID` INT, IN `p_PageNumber` INT, IN `p_RowspPage` INT, IN `p_lSortCol` VARCHAR(50), IN `p_SortOrder` VARCHAR(5), IN `p_isExport` INT)
BEGIN

   DECLARE v_OffSet_ int;
   SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
	 
	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
	
	
    IF p_isExport = 0
    THEN
         
		SELECT
			abh.PermanentCredit,
			abh.BalanceThreshold,
			abh.CreatedBy,
			abh.created_at
		FROM tblAccountBalanceHistory abh
      WHERE abh.AccountID = p_AccountID
      ORDER BY                
			CASE
			  WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'PermanentCreditDESC') THEN abh.PermanentCredit
			END DESC,
			CASE
			  WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'PermanentCreditASC') THEN abh.PermanentCredit
			END ASC,				
			CASE
			  WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ThresholdASC') THEN abh.BalanceThreshold
			END ASC,
			CASE
			  WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ThresholdDESC') THEN abh.BalanceThreshold
			END DESC,
			CASE
			  WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atASC') THEN abh.created_at
			END ASC,
			CASE
			  WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atDESC') THEN abh.created_at
			END DESC,
			CASE
			  WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CreatedByASC') THEN abh.CreatedBy
			END ASC,
			CASE
			  WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CreatedByDESC') THEN abh.CreatedBy
			END DESC
		LIMIT p_RowspPage OFFSET v_OffSet_;


     SELECT
         COUNT(abh.AccountBalanceHistoryID) as totalcount
     FROM tblAccountBalanceHistory abh
         WHERE abh.AccountID = p_AccountID;
    END IF;

    IF p_isExport = 1
    THEN
        SELECT
			abh.PermanentCredit,
			abh.BalanceThreshold,
			abh.CreatedBy,
			abh.created_at
		FROM tblAccountBalanceHistory abh
      WHERE abh.AccountID = p_AccountID;
    END IF;
    SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getAccountDiscountPlan` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getAccountDiscountPlan`(
	IN `p_AccountID` INT,
	IN `p_Type` INT,
	IN `p_ServiceID` INT,
	IN `p_AccountSubscriptionID` INT,
	IN `p_SubscriptionDiscountPlanID` INT
)
BEGIN
	
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	SELECT 
		dg.Name,
		ROUND(adc.Threshold/60,0) as Threshold,
		IF (adc.Unlimited=1,'Unlimited','') as Unlimited,
		ROUND(adc.SecondsUsed/60,0) as MinutesUsed,
		StartDate,
		EndDate,
		adp.created_at,
		adp.CreatedBy
	FROM tblAccountDiscountPlan adp
	INNER JOIN tblAccountDiscountScheme adc
		ON adc.AccountDiscountPlanID = adp.AccountDiscountPlanID
	INNER JOIN tblDiscount d
		ON d.DiscountID = adc.DiscountID
	INNER JOIN tblDestinationGroup dg
		ON dg.DestinationGroupID = d.DestinationGroupID
	WHERE AccountID = p_AccountID 
	   AND adp.ServiceID = p_ServiceID
	   AND adp.AccountSubscriptionID = p_AccountSubscriptionID
	   AND adp.SubscriptionDiscountPlanID = p_SubscriptionDiscountPlanID
		AND Type = p_Type;
	

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getAccountIPAuditExportLog` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getAccountIPAuditExportLog`(
	IN `p_CompanyID` INT,
	IN `p_GatewayID` INT
)
BEGIN
	DECLARE v_last_time_exist INT DEFAULT 0;
	DECLARE v_last_time DATETIME;
	DECLARE v_start_time DATETIME;
	DECLARE v_end_time DATETIME;
	DECLARE v_cur_date DATE DEFAULT CURDATE();
	DECLARE v_cur_time DATETIME DEFAULT NOW();

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SELECT end_time INTO v_last_time FROM tblAccountAuditExportLog WHERE CompanyID=p_CompanyID AND CompanyGatewayID=p_GatewayID AND Type='accountip' AND Status=1 ORDER BY AccountAuditExportLogID DESC LIMIT 1;

	IF (v_last_time IS NOT NULL AND v_last_time != '')
	THEN
		SELECT
			 MIN(tad.created_at), MAX(tad.created_at) INTO v_start_time, v_end_time
		FROM
			tblAuditHeader AS tah
		LEFT JOIN
			tblAccountAuthenticate AS aa ON tah.ParentColumnID=aa.AccountAuthenticateID
		LEFT JOIN
			tblAccount AS a ON aa.AccountID=a.AccountID
		LEFT JOIN
			tblAuditDetails AS tad ON tah.AuditHeaderID=tad.AuditHeaderID
		LEFT JOIN
			tblDynamicFieldsValue AS dfv ON dfv.ParentID=a.AccountID
		LEFT JOIN
			tblDynamicFields AS df ON df.DynamicFieldsID=dfv.DynamicFieldsID
		WHERE
			df.FieldName='Gateway' AND find_in_set(p_GatewayID,dfv.FieldValue) > 0 AND tah.Type='accountip' AND tah.Date>=DATE(v_last_time) AND tah.Date<=DATE(v_cur_date) AND tad.created_at>v_last_time;

		IF ((v_start_time IS NOT NULL AND v_start_time != '') AND (v_end_time IS NOT NULL AND v_end_time != ''))
     	THEN
			INSERT INTO tblAccountAuditExportLog (CompanyID,CompanyGatewayID,Type,start_time,end_time,created_at) VALUES (p_CompanyID, p_GatewayID, 'accountip', v_start_time, v_end_time, v_cur_time);
		END IF;

		SELECT
			tah.ParentColumnID,tah.ParentColumnName,tad.ColumnName,tad.OldValue,tad.NewValue,s.ServiceName,v_start_time AS start_time,v_end_time AS end_time,v_cur_time AS created_at
		FROM
			tblAuditHeader AS tah
		LEFT JOIN
			tblAccountAuthenticate AS aa ON tah.ParentColumnID=aa.AccountAuthenticateID
		LEFT JOIN
			tblAccount AS a ON aa.AccountID=a.AccountID
		LEFT JOIN
			tblService AS s ON s.ServiceID=aa.ServiceID
		LEFT JOIN
			tblAuditDetails AS tad ON tah.AuditHeaderID=tad.AuditHeaderID
		LEFT JOIN
			tblDynamicFieldsValue AS dfv ON dfv.ParentID=a.AccountID
		LEFT JOIN
			tblDynamicFields AS df ON df.DynamicFieldsID=dfv.DynamicFieldsID
		WHERE
			df.FieldName='Gateway' AND find_in_set(p_GatewayID,dfv.FieldValue) > 0 AND tah.Type='accountip' AND tah.Date>=DATE(v_last_time) AND tah.Date<=DATE(v_cur_date) AND tad.created_at>v_last_time;

	ELSE
		SELECT
	   	MIN(tad.created_at), MAX(tad.created_at) INTO v_start_time, v_end_time
		FROM
			tblAuditHeader AS tah
		LEFT JOIN
			tblAccountAuthenticate AS aa ON tah.ParentColumnID=aa.AccountAuthenticateID
		LEFT JOIN
			tblAccount AS a ON aa.AccountID=a.AccountID
		LEFT JOIN
			tblAuditDetails AS tad ON tah.AuditHeaderID=tad.AuditHeaderID
		LEFT JOIN
			tblDynamicFieldsValue AS dfv ON dfv.ParentID=a.AccountID
		LEFT JOIN
			tblDynamicFields AS df ON df.DynamicFieldsID=dfv.DynamicFieldsID
		WHERE
			df.FieldName='Gateway' AND find_in_set(p_GatewayID,dfv.FieldValue) > 0 AND tah.Type='accountip' AND tah.Date>=(v_cur_date - INTERVAL 1 DAY) AND tah.Date<=v_cur_date AND tad.created_at<=v_cur_time;

		IF ((v_start_time IS NOT NULL AND v_start_time != '') AND (v_end_time IS NOT NULL AND v_end_time != ''))
    	THEN
			INSERT INTO tblAccountAuditExportLog (CompanyID,CompanyGatewayID,Type,start_time,end_time,created_at) VALUES (p_CompanyID, p_GatewayID, 'accountip', v_start_time, v_end_time, v_cur_time);
		END IF;

		SELECT
	   		tah.ParentColumnID,tah.ParentColumnName,tad.ColumnName,tad.OldValue,tad.NewValue,s.ServiceName,v_start_time AS start_time,v_end_time AS end_time,v_cur_time AS created_at
		FROM
			tblAuditHeader AS tah
		LEFT JOIN
			tblAccountAuthenticate AS aa ON tah.ParentColumnID=aa.AccountAuthenticateID
		LEFT JOIN
			tblAccount AS a ON aa.AccountID=a.AccountID
		LEFT JOIN
			tblService AS s ON s.ServiceID=aa.ServiceID
		LEFT JOIN
			tblAuditDetails AS tad ON tah.AuditHeaderID=tad.AuditHeaderID
		LEFT JOIN
			tblDynamicFieldsValue AS dfv ON dfv.ParentID=a.AccountID
		LEFT JOIN
			tblDynamicFields AS df ON df.DynamicFieldsID=dfv.DynamicFieldsID
		WHERE
			df.FieldName='Gateway' AND find_in_set(p_GatewayID,dfv.FieldValue) > 0 AND tah.Type='accountip' AND tah.Date>=(v_cur_date - INTERVAL 1 DAY) AND tah.Date<=v_cur_date AND tad.created_at<=v_cur_time;
   	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetAccountLogs` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetAccountLogs`(
	IN `p_CompanyID` int,
	IN `p_userID` int ,
	IN `p_AccountID` int ,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5)
)
BEGIN
	DECLARE v_OffSet_ int;
	DECLARE v_Round_ int;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;

	SELECT * FROM
	(
		(
			SELECT
				d.ColumnName,
				CASE
					WHEN (d.ColumnName='accountgateway') THEN
						GROUP_CONCAT(DISTINCT cgo.Title)
					WHEN (d.ColumnName='IsCustomer' AND d.OldValue=0) THEN
						'NO'
					WHEN (d.ColumnName='IsCustomer' AND d.OldValue=1) THEN
						'YES'
					WHEN (d.ColumnName='IsVendor' AND d.OldValue=0) THEN
						'NO'
					WHEN (d.ColumnName='IsVendor' AND d.OldValue=1) THEN
						'YES'
					ELSE
						d.OldValue
				END AS OldValue,
				CASE
					WHEN (d.ColumnName='accountgateway') THEN
						GROUP_CONCAT(DISTINCT cgn.Title)
					WHEN (d.ColumnName='IsCustomer' AND d.NewValue=0) THEN
						'NO'
					WHEN (d.ColumnName='IsCustomer' AND d.NewValue=1) THEN
						'YES'
					WHEN (d.ColumnName='IsVendor' AND d.NewValue=0) THEN
						'NO'
					WHEN (d.ColumnName='IsVendor' AND d.NewValue=1) THEN
						'YES'
					ELSE
						d.NewValue
				END AS NewValue,
				d.created_at,
				d.created_by
			FROM tblAuditDetails AS d
			LEFT JOIN tblAuditHeader AS h
				ON h.AuditHeaderID = d.AuditHeaderID
			LEFT JOIN tblAccount AS a
				ON h.ParentColumnID = a.AccountID
			LEFT JOIN tblCompanyGateway AS cgo
				ON FIND_IN_SET(cgo.CompanyGatewayID,d.OldValue)
			LEFT JOIN tblCompanyGateway AS cgn
				ON FIND_IN_SET(cgn.CompanyGatewayID,d.NewValue)
			WHERE   
				h.Type = 'account' AND 
				h.ParentColumnName = 'AccountID' AND 
				h.ParentColumnID = p_AccountID AND 
				a.AccountID = p_AccountID
			GROUP BY
				d.AuditDetailID,d.OldValue,d.NewValue
		)
		
		UNION
		
		(
			SELECT
				d.ColumnName,
				d.OldValue AS OldValue,
				d.NewValue AS NewValue,
				d.created_at,
				d.created_by
			FROM tblAuditDetails AS d
			LEFT JOIN tblAuditHeader AS h
				ON h.AuditHeaderID = d.AuditHeaderID
			LEFT JOIN tblAccountBilling AS ab
				ON h.ParentColumnID = ab.AccountBillingID	
			LEFT JOIN tblAccount AS a
				ON ab.AccountID = a.AccountID
			WHERE   
				h.Type = 'accountbilling' AND 
				h.ParentColumnName = 'AccountBillingID' AND 
				ab.AccountID = p_AccountID
			GROUP BY
				d.AuditDetailID,d.OldValue,d.NewValue
		)
		
		UNION
		
		(
			SELECT
				IF(d2.ColumnName="CustomerAuthValue","Customer IP","Vendor IP"),
				d2.OldValue AS OldValue,
				d2.NewValue AS NewValue,
				d2.created_at,
				d2.created_by
			FROM tblAuditDetails AS d2
			LEFT JOIN tblAuditHeader AS h2
				ON h2.AuditHeaderID = d2.AuditHeaderID
			LEFT JOIN tblAccountAuthenticate AS aa
				ON aa.AccountAuthenticateID=h2.ParentColumnID
			LEFT JOIN tblAccount AS a2
				ON aa.AccountID = a2.AccountID
			WHERE   
				h2.Type = 'accountip' AND 
				h2.ParentColumnName = 'AccountAuthenticateID' AND 
				a2.AccountID = p_AccountID
			GROUP BY
				d2.AuditDetailID,d2.OldValue,d2.NewValue
		)
	) mix

	ORDER BY
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ColumnNameDESC') THEN mix.ColumnName
		END DESC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ColumnNameASC') THEN mix.ColumnName
		END ASC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atDESC') THEN mix.created_at
		END DESC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atASC') THEN mix.created_at
		END ASC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_byDESC') THEN mix.created_by
		END DESC,
		CASE
			WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_byASC') THEN mix.created_by
		END ASC
	LIMIT p_RowspPage OFFSET v_OffSet_;

	SELECT 
		COUNT(*) AS totalcount
	FROM
	(
		(
			SELECT
				d.ColumnName,
				CASE
					WHEN (d.ColumnName='accountgateway') THEN
						GROUP_CONCAT(DISTINCT cgo.Title)
					WHEN (d.ColumnName='IsCustomer' AND d.OldValue=0) THEN
						'NO'
					WHEN (d.ColumnName='IsCustomer' AND d.OldValue=1) THEN
						'YES'
					WHEN (d.ColumnName='IsVendor' AND d.OldValue=0) THEN
						'NO'
					WHEN (d.ColumnName='IsVendor' AND d.OldValue=1) THEN
						'YES'
					ELSE
						d.OldValue
				END AS OldValue,
				CASE
					WHEN (d.ColumnName='accountgateway') THEN
						GROUP_CONCAT(DISTINCT cgn.Title)
					WHEN (d.ColumnName='IsCustomer' AND d.NewValue=0) THEN
						'NO'
					WHEN (d.ColumnName='IsCustomer' AND d.NewValue=1) THEN
						'YES'
					WHEN (d.ColumnName='IsVendor' AND d.NewValue=0) THEN
						'NO'
					WHEN (d.ColumnName='IsVendor' AND d.NewValue=1) THEN
						'YES'
					ELSE
						d.NewValue
				END AS NewValue,
				d.created_at,
				d.created_by
			FROM tblAuditDetails AS d
			LEFT JOIN tblAuditHeader AS h
				ON h.AuditHeaderID = d.AuditHeaderID
			LEFT JOIN tblAccount AS a
				ON h.ParentColumnID = a.AccountID
			LEFT JOIN tblCompanyGateway AS cgo
				ON FIND_IN_SET(cgo.CompanyGatewayID,d.OldValue)
			LEFT JOIN tblCompanyGateway AS cgn
				ON FIND_IN_SET(cgn.CompanyGatewayID,d.NewValue)
			WHERE   
				h.Type = 'account' AND 
				h.ParentColumnName = 'AccountID' AND 
				h.ParentColumnID = p_AccountID AND 
				a.AccountID = p_AccountID
			GROUP BY
				d.AuditDetailID,d.OldValue,d.NewValue
		)
		
		UNION
		
		(
			SELECT
				d.ColumnName,
				d.OldValue AS OldValue,
				d.NewValue AS NewValue,
				d.created_at,
				d.created_by
			FROM tblAuditDetails AS d
			LEFT JOIN tblAuditHeader AS h
				ON h.AuditHeaderID = d.AuditHeaderID
			LEFT JOIN tblAccountBilling AS ab
				ON h.ParentColumnID = ab.AccountBillingID	
			LEFT JOIN tblAccount AS a
				ON ab.AccountID = a.AccountID
			WHERE   
				h.Type = 'accountbilling' AND 
				h.ParentColumnName = 'AccountBillingID' AND 
				ab.AccountID = p_AccountID
			GROUP BY
				d.AuditDetailID,d.OldValue,d.NewValue
		)
		
		UNION
		
		(
			SELECT
				d2.ColumnName,
				d2.OldValue AS OldValue,
				d2.NewValue AS NewValue,
				d2.created_at,
				d2.created_by
			FROM tblAuditDetails AS d2
			LEFT JOIN tblAuditHeader AS h2
				ON h2.AuditHeaderID = d2.AuditHeaderID
			LEFT JOIN tblAccountAuthenticate AS aa
				ON aa.AccountAuthenticateID=h2.ParentColumnID
			LEFT JOIN tblAccount AS a2
				ON aa.AccountID = a2.AccountID
			WHERE   
				h2.Type = 'accountip' AND 
				h2.ParentColumnName = 'AccountAuthenticateID' AND 
				a2.AccountID = p_AccountID
			GROUP BY
				d2.AuditDetailID,d2.OldValue,d2.NewValue
		)
	) totalcount;
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetAccounts` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_GetAccounts`(
	IN `p_CompanyID` int,
	IN `p_userID` int ,
	IN `p_IsVendor` int ,
	IN `p_isCustomer` int ,
	IN `p_isReseller` INT,
	IN `p_ResellerID` INT,
	IN `p_activeStatus` int,
	IN `p_VerificationStatus` int,
	IN `p_AccountNo` VARCHAR(100),
	IN `p_ContactName` VARCHAR(50),
	IN `p_AccountName` VARCHAR(50),
	IN `p_tags` VARCHAR(50),
	IN `p_IPCLI` VARCHAR(50),
	IN `p_low_balance` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT
)
BEGIN
	DECLARE v_OffSet_ int;
	DECLARE v_Round_ int;
	DECLARE v_raccountids TEXT;
	DECLARE v_resellercompanyid int;
	SET v_raccountids = '';
	SET v_resellercompanyid = 0;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;

	IF p_ResellerID > 0
	THEN
		DROP TEMPORARY TABLE IF EXISTS tmp_reselleraccounts_;
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_reselleraccounts_(
			AccountID int
		);
	
		INSERT INTO tmp_reselleraccounts_
		SELECT AccountID FROM tblAccountDetails WHERE ResellerOwner=p_ResellerID
		UNION
		SELECT AccountID FROM tblReseller WHERE ResellerID=p_ResellerID;
		
		SELECT ChildCompanyID INTO v_resellercompanyid FROM tblReseller WHERE ResellerID=p_ResellerID;		
	
		SELECT IFNULL(GROUP_CONCAT(AccountID),'') INTO v_raccountids FROM tmp_reselleraccounts_;
		
	END IF;

	IF p_isExport = 0
	THEN

		SELECT
			tblAccount.AccountID,
			tblAccount.Number,
			tblAccount.AccountName,
			CONCAT(tblAccount.FirstName,' ',tblAccount.LastName) as Ownername,
			tblAccount.Phone,
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,ROUND(COALESCE(abc.SOAOffset,0),v_Round_)) as OutStandingAmount,
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,ROUND(COALESCE(abc.UnbilledAmount,0),v_Round_) - ROUND(COALESCE(abc.VendorUnbilledAmount,0),v_Round_)) as UnbilledAmount,
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,ROUND(COALESCE(abc.PermanentCredit,0),v_Round_)) as PermanentCredit,
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,ROUND(COALESCE(abc.BalanceAmount,0),v_Round_)) as AccountExposure,
			tblAccount.Email,
			tblAccount.IsCustomer,
			tblAccount.IsVendor,
			tblAccount.VerificationStatus,
			tblAccount.Address1,
			tblAccount.Address2,
			tblAccount.Address3,
			tblAccount.City,
			tblAccount.Country,
			tblAccount.PostCode,
			tblAccount.Picture,
	--	IF ( (CASE WHEN abc.BalanceThreshold LIKE '%p' THEN REPLACE(abc.BalanceThreshold, 'p', '')/ 100 * abc.PermanentCredit ELSE abc.BalanceThreshold END) < abc.BalanceAmount AND abc.BalanceThreshold <> 0 ,1,0) as BalanceWarning,
	     IF ( (
				CASE WHEN abc.BalanceThreshold LIKE '%p' 
					THEN REPLACE(abc.BalanceThreshold, 'p', '')/ 100 * abc.PermanentCredit 
						ELSE abc.BalanceThreshold END
				) > CASE WHEN abg.BillingType = 1 THEN (CASE WHEN abc.BalanceAmount <0 THEN ABS(abc.BalanceAmount) ELSE (abc.BalanceAmount * -1) END) ELSE abc.BalanceAmount END  AND abc.BalanceThreshold <> 0 ,1,0) as BalanceWarning, 
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,ROUND(COALESCE(abc.UnbilledAmount,0),v_Round_)) as CUA,
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,ROUND(COALESCE(abc.VendorUnbilledAmount,0),v_Round_)) as VUA,
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,ROUND(COALESCE(abc.BalanceAmount,0),v_Round_)) as AE,
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,IF(ROUND(COALESCE(abc.PermanentCredit,0),v_Round_) - ROUND(COALESCE(abc.BalanceAmount,0),v_Round_)<0,0,ROUND(COALESCE(abc.PermanentCredit,0),v_Round_) - ROUND(COALESCE(abc.BalanceAmount,0),v_Round_))) as ACL,
			abc.BalanceThreshold,
			tblAccount.Blocked
		FROM tblAccount
		LEFT JOIN tblAccountBilling abg 
			ON tblAccount.AccountID = abg.AccountID  AND abg.ServiceID = 0
		LEFT JOIN tblAccountBalance abc
			ON abc.AccountID = tblAccount.AccountID
		LEFT JOIN tblUser
			ON tblAccount.Owner = tblUser.UserID
		LEFT JOIN tblContact
			ON tblContact.Owner=tblAccount.AccountID
		LEFT JOIN tblAccountAuthenticate
			ON tblAccountAuthenticate.AccountID = tblAccount.AccountID
		LEFT JOIN tblCLIRateTable
			ON tblCLIRateTable.AccountID = tblAccount.AccountID
		WHERE  
			 tblAccount.AccountType = 1
			AND tblAccount.Status = p_activeStatus
			AND tblAccount.VerificationStatus = p_VerificationStatus
			AND (p_userID = 0 OR tblAccount.Owner = p_userID)
			AND ((p_IsVendor = 0 OR tblAccount.IsVendor = 1))
			AND ((p_isCustomer = 0 OR tblAccount.IsCustomer = 1))
			AND ((p_isReseller = 0 OR tblAccount.IsReseller = 1))
			AND (p_ResellerID = 0 OR tblAccount.CompanyID = v_resellercompanyid)
			AND ((p_AccountNo = '' OR tblAccount.Number LIKE p_AccountNo))
			AND ((p_AccountName = '' OR tblAccount.AccountName LIKE Concat('%',p_AccountName,'%')))
			AND ((p_IPCLI = '' OR tblCLIRateTable.CLI LIKE CONCAT('%',p_IPCLI,'%') OR CONCAT(IFNULL(tblAccountAuthenticate.CustomerAuthValue,''),',',IFNULL(tblAccountAuthenticate.VendorAuthValue,'')) LIKE CONCAT('%',p_IPCLI,'%')))
			AND ((p_tags = '' OR tblAccount.tags LIKE Concat(p_tags,'%')))
			AND ((p_ContactName = '' OR (CONCAT(IFNULL(tblContact.FirstName,'') ,' ', IFNULL(tblContact.LastName,''))) LIKE CONCAT('%',p_ContactName,'%')))
	 --	AND (p_low_balance = 0 OR ( p_low_balance = 1 AND abc.BalanceThreshold <> 0 AND (CASE WHEN abc.BalanceThreshold LIKE '%p' THEN REPLACE(abc.BalanceThreshold, 'p', '')/ 100 * abc.PermanentCredit ELSE abc.BalanceThreshold END) < abc.BalanceAmount) )
		AND (p_low_balance = 0 OR ( p_low_balance = 1 AND abc.BalanceThreshold <> 0 AND  (
				CASE WHEN abc.BalanceThreshold LIKE '%p' 
					THEN REPLACE(abc.BalanceThreshold, 'p', '')/ 100 * abc.PermanentCredit 
						ELSE abc.BalanceThreshold END
				) > CASE WHEN abg.BillingType = 1 THEN (CASE WHEN abc.BalanceAmount <0 THEN ABS(abc.BalanceAmount) ELSE (abc.BalanceAmount * -1) END) ELSE abc.BalanceAmount END)) 
		GROUP BY tblAccount.AccountID,abg.BillingType
		ORDER BY
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameASC') THEN tblAccount.AccountName
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AccountNameDESC') THEN tblAccount.AccountName
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'NumberDESC') THEN tblAccount.Number
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'NumberASC') THEN tblAccount.Number
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'OwnernameDESC') THEN tblUser.FirstName
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'OwnernameASC') THEN tblUser.FirstName
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'PhoneDESC') THEN tblAccount.Phone
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'PhoneASC') THEN tblAccount.Phone
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'OutStandingAmountDESC') THEN abc.SOAOffset
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'OutStandingAmountASC') THEN abc.SOAOffset
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'PermanentCreditDESC') THEN abc.PermanentCredit
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'PermanentCreditASC') THEN abc.PermanentCredit
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UnbilledAmountDESC') THEN (ROUND(COALESCE(abc.UnbilledAmount,0),v_Round_) - ROUND(COALESCE(abc.VendorUnbilledAmount,0),v_Round_))
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UnbilledAmountASC') THEN (ROUND(COALESCE(abc.UnbilledAmount,0),v_Round_) - ROUND(COALESCE(abc.VendorUnbilledAmount,0),v_Round_))
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EmailDESC') THEN tblAccount.Email
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EmailASC') THEN tblAccount.Email
			END ASC
		LIMIT p_RowspPage OFFSET v_OffSet_;

		SELECT
			COUNT(DISTINCT tblAccount.AccountID) AS totalcount
		FROM tblAccount
		LEFT JOIN tblAccountBilling abg 
		 ON tblAccount.AccountID = abg.AccountID AND abg.ServiceID = 0
		LEFT JOIN tblAccountBalance abc
			ON abc.AccountID = tblAccount.AccountID
		LEFT JOIN tblUser
			ON tblAccount.Owner = tblUser.UserID
		LEFT JOIN tblContact
			ON tblContact.Owner=tblAccount.AccountID
		LEFT JOIN tblAccountAuthenticate
			ON tblAccountAuthenticate.AccountID = tblAccount.AccountID
		LEFT JOIN tblCLIRateTable
			ON tblCLIRateTable.AccountID = tblAccount.AccountID
		WHERE 
			 tblAccount.AccountType = 1
			AND tblAccount.Status = p_activeStatus
			AND tblAccount.VerificationStatus = p_VerificationStatus
			AND (p_userID = 0 OR tblAccount.Owner = p_userID)
			AND ((p_IsVendor = 0 OR tblAccount.IsVendor = 1))
			AND ((p_isCustomer = 0 OR tblAccount.IsCustomer = 1))
			AND ((p_isReseller = 0 OR tblAccount.IsReseller = 1))
			AND (p_ResellerID = 0 OR tblAccount.CompanyID = v_resellercompanyid)
			AND ((p_AccountNo = '' OR tblAccount.Number LIKE p_AccountNo))
			AND ((p_AccountName = '' OR tblAccount.AccountName LIKE Concat('%',p_AccountName,'%')))
			AND ((p_IPCLI = '' OR tblCLIRateTable.CLI LIKE CONCAT('%',p_IPCLI,'%') OR CONCAT(IFNULL(tblAccountAuthenticate.CustomerAuthValue,''),',',IFNULL(tblAccountAuthenticate.VendorAuthValue,'')) LIKE CONCAT('%',p_IPCLI,'%')))
			AND ((p_tags = '' OR tblAccount.tags LIKE Concat(p_tags,'%')))
			AND ((p_ContactName = '' OR (CONCAT(IFNULL(tblContact.FirstName,'') ,' ', IFNULL(tblContact.LastName,''))) LIKE CONCAT('%',p_ContactName,'%')))
		--	AND (p_low_balance = 0 OR ( p_low_balance = 1 AND abc.BalanceThreshold <> 0 AND (CASE WHEN abc.BalanceThreshold LIKE '%p' THEN REPLACE(abc.BalanceThreshold, 'p', '')/ 100 * abc.PermanentCredit ELSE abc.BalanceThreshold END) < abc.BalanceAmount) );
			AND (p_low_balance = 0 OR ( p_low_balance = 1 AND abc.BalanceThreshold <> 0 AND  (
				CASE WHEN abc.BalanceThreshold LIKE '%p' 
					THEN REPLACE(abc.BalanceThreshold, 'p', '')/ 100 * abc.PermanentCredit 
						ELSE abc.BalanceThreshold END
				) > CASE WHEN abg.BillingType = 1 THEN (CASE WHEN abc.BalanceAmount <0 THEN ABS(abc.BalanceAmount) ELSE (abc.BalanceAmount * -1) END) ELSE abc.BalanceAmount END)) ;

	END IF;
	IF p_isExport = 1
	THEN
		SELECT
			tblAccount.Number as NO,
			tblAccount.AccountName,
			CONCAT(tblAccount.FirstName,' ',tblAccount.LastName) as Name,
			tblAccount.Phone,
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,ROUND(COALESCE(abc.SOAOffset,0),v_Round_)) as 'OutStanding',
			tblAccount.Email,
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,ROUND(COALESCE(abc.UnbilledAmount,0),v_Round_)  - ROUND(COALESCE(abc.VendorUnbilledAmount,0),v_Round_)) as 'Unbilled Amount',
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,ROUND(COALESCE(abc.PermanentCredit,0),v_Round_)) as 'Credit Limit',
			CONCAT(tblUser.FirstName,' ',tblUser.LastName) as 'Account Owner',
			CONCAT((SELECT Symbol FROM tblCurrency WHERE tblCurrency.CurrencyId = tblAccount.CurrencyId) ,ROUND(COALESCE(abc.BalanceAmount,0),v_Round_)) as AccountExposure
		FROM tblAccount
		LEFT JOIN tblAccountBilling abg 
			ON tblAccount.AccountID = abg.AccountID AND abg.ServiceID = 0
		LEFT JOIN tblAccountBalance abc
			ON abc.AccountID = tblAccount.AccountID
		LEFT JOIN tblUser
			ON tblAccount.Owner = tblUser.UserID
		LEFT JOIN tblContact
			ON tblContact.Owner=tblAccount.AccountID
		LEFT JOIN tblAccountAuthenticate
			ON tblAccountAuthenticate.AccountID = tblAccount.AccountID
		LEFT JOIN tblCLIRateTable
			ON tblCLIRateTable.AccountID = tblAccount.AccountID
		WHERE   tblAccount.CompanyID = p_CompanyID
			AND tblAccount.AccountType = 1
			AND tblAccount.Status = p_activeStatus
			AND tblAccount.VerificationStatus = p_VerificationStatus
			AND (p_userID = 0 OR tblAccount.Owner = p_userID)
			AND ((p_IsVendor = 0 OR tblAccount.IsVendor = 1))
			AND ((p_isCustomer = 0 OR tblAccount.IsCustomer = 1))
			AND ((p_isReseller = 0 OR tblAccount.IsReseller = 1))
			AND (p_ResellerID = 0 OR tblAccount.CompanyID = v_resellercompanyid)
			AND ((p_AccountNo = '' OR tblAccount.Number LIKE p_AccountNo))
			AND ((p_AccountName = '' OR tblAccount.AccountName LIKE Concat('%',p_AccountName,'%')))
			AND ((p_IPCLI = '' OR tblCLIRateTable.CLI LIKE CONCAT('%',p_IPCLI,'%') OR CONCAT(IFNULL(tblAccountAuthenticate.CustomerAuthValue,''),',',IFNULL(tblAccountAuthenticate.VendorAuthValue,'')) LIKE CONCAT('%',p_IPCLI,'%')))
			AND ((p_tags = '' OR tblAccount.tags LIKE Concat(p_tags,'%')))
			AND ((p_ContactName = '' OR (CONCAT(IFNULL(tblContact.FirstName,'') ,' ', IFNULL(tblContact.LastName,''))) LIKE CONCAT('%',p_ContactName,'%')))
		--	AND (p_low_balance = 0 OR ( p_low_balance = 1 AND abc.BalanceThreshold <> 0 AND (CASE WHEN abc.BalanceThreshold LIKE '%p' THEN REPLACE(abc.BalanceThreshold, 'p', '')/ 100 * abc.PermanentCredit ELSE abc.BalanceThreshold END) < abc.BalanceAmount) )
			AND (p_low_balance = 0 OR ( p_low_balance = 1 AND abc.BalanceThreshold <> 0 AND  (
				CASE WHEN abc.BalanceThreshold LIKE '%p' 
					THEN REPLACE(abc.BalanceThreshold, 'p', '')/ 100 * abc.PermanentCredit 
						ELSE abc.BalanceThreshold END
				) > CASE WHEN abg.BillingType = 1 THEN (CASE WHEN abc.BalanceAmount <0 THEN ABS(abc.BalanceAmount) ELSE (abc.BalanceAmount * -1) END) ELSE abc.BalanceAmount END)) 
		GROUP BY tblAccount.AccountID,abg.BillingType;
	END IF;
	IF p_isExport = 2
	THEN
		SELECT
			tblAccount.AccountID,
			tblAccount.AccountName
		FROM tblAccount
		LEFT JOIN tblAccountBilling abg 
			ON tblAccount.AccountID = abg.AccountID AND abg.ServiceID = 0
		LEFT JOIN tblAccountBalance abc
			ON abc.AccountID = tblAccount.AccountID
		LEFT JOIN tblUser
			ON tblAccount.Owner = tblUser.UserID
		LEFT JOIN tblContact
			ON tblContact.Owner=tblAccount.AccountID
		LEFT JOIN tblAccountAuthenticate
			ON tblAccountAuthenticate.AccountID = tblAccount.AccountID
		LEFT JOIN tblCLIRateTable
			ON tblCLIRateTable.AccountID = tblAccount.AccountID
		WHERE   tblAccount.CompanyID = p_CompanyID
			AND tblAccount.AccountType = 1
			AND tblAccount.Status = p_activeStatus
			AND tblAccount.VerificationStatus = p_VerificationStatus
			AND (p_userID = 0 OR tblAccount.Owner = p_userID)
			AND ((p_IsVendor = 0 OR tblAccount.IsVendor = 1))
			AND ((p_isCustomer = 0 OR tblAccount.IsCustomer = 1))
			AND ((p_isReseller = 0 OR tblAccount.IsReseller = 1))
			AND (p_ResellerID = 0 OR tblAccount.CompanyID = v_resellercompanyid)
			AND ((p_AccountNo = '' OR tblAccount.Number LIKE p_AccountNo))
			AND ((p_AccountName = '' OR tblAccount.AccountName LIKE Concat('%',p_AccountName,'%')))
			AND ((p_IPCLI = '' OR tblCLIRateTable.CLI LIKE CONCAT('%',p_IPCLI,'%') OR CONCAT(IFNULL(tblAccountAuthenticate.CustomerAuthValue,''),',',IFNULL(tblAccountAuthenticate.VendorAuthValue,'')) LIKE CONCAT('%',p_IPCLI,'%')))
			AND ((p_tags = '' OR tblAccount.tags LIKE Concat(p_tags,'%')))
			AND ((p_ContactName = '' OR (CONCAT(IFNULL(tblContact.FirstName,'') ,' ', IFNULL(tblContact.LastName,''))) LIKE CONCAT('%',p_ContactName,'%')))
			-- AND (p_low_balance = 0 OR ( p_low_balance = 1 AND abc.BalanceThreshold <> 0 AND (CASE WHEN abc.BalanceThreshold LIKE '%p' THEN REPLACE(abc.BalanceThreshold, 'p', '')/ 100 * abc.PermanentCredit ELSE abc.BalanceThreshold END) < abc.BalanceAmount) )
				AND (p_low_balance = 0 OR ( p_low_balance = 1 AND abc.BalanceThreshold <> 0 AND  (
				CASE WHEN abc.BalanceThreshold LIKE '%p' 
					THEN REPLACE(abc.BalanceThreshold, 'p', '')/ 100 * abc.PermanentCredit 
						ELSE abc.BalanceThreshold END
				) > CASE WHEN abg.BillingType = 1 THEN (CASE WHEN abc.BalanceAmount <0 THEN ABS(abc.BalanceAmount) ELSE (abc.BalanceAmount * -1) END) ELSE abc.BalanceAmount END)) 
		GROUP BY tblAccount.AccountID,abg.BillingType;
	END IF;
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getAccountService` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getAccountService`(
	IN `p_AccountID` INT,
	IN `p_ServiceID` INT
)
BEGIN

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	SELECT
		tblAccountService.*
	FROM tblAccountService
	LEFT JOIN tblAccountBilling 
		ON tblAccountBilling.AccountID = tblAccountService.AccountID AND tblAccountBilling.ServiceID =  tblAccountService.ServiceID
	WHERE tblAccountService.AccountID = p_AccountID
	AND Status = 1
	AND ( (p_ServiceID = 0 AND tblAccountBilling.ServiceID IS NULL) OR  tblAccountBilling.ServiceID = p_ServiceID);
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
	
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getAccountTimeLine` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getAccountTimeLine`(
	IN `p_AccountID` INT,
	IN `p_CompanyID` INT,
	IN `p_TicketType` INT,
	IN `p_GUID` VARCHAR(100),
	IN `p_Time` DATE,
	IN `p_Start` INT,
	IN `p_RowspPage` INT


)
BEGIN
DECLARE v_OffSet_ int;
DECLARE v_ActiveSupportDesk int;
DECLARE v_contacts_ids varchar(200);
DECLARE v_contacts_emails varchar(200);
DECLARE v_account_emails varchar(200);
DECLARE v_account_contacts_emails varchar(300);

SET v_OffSet_ = p_Start;
SET sql_mode = 'ALLOW_INVALID_DATES';


if(p_Start>0)
THEN
	DELETE FROM tbl_Account_Contacts_Activity  WHERE  `TableCreated_at` < DATE_SUB(p_Time, INTERVAL 2 DAY);
END IF;
if(p_Start= 0)
THEN
		
		SELECT 
			group_concat(CC.ContactID separator ',')
		FROM
			tblContact CC
		WHERE 
			CC.Owner = p_AccountID	INTO v_contacts_ids;
			
		SELECT 
			group_concat(DISTINCT CC.Email separator ',')
		FROM
			tblContact CC
		WHERE 
			CC.Owner = p_AccountID	INTO v_contacts_emails;
			
			
		SELECT 
		(CASE WHEN tac.Email = tac.BillingEmail THEN tac.Email ELSE concat(tac.Email,',',tac.BillingEmail) END) 
		FROM
			tblAccount tac
		WHERE 
			tac.AccountID = p_AccountID	INTO v_contacts_emails;	
		
		select concat(v_contacts_emails,',',v_contacts_emails) into v_account_contacts_emails;


			
			
			
			INSERT INTO tbl_Account_Contacts_Activity(  `Timeline_type`,  `TaskTitle`,  `TaskName`,  `TaskPriority`,  `DueDate`,  `TaskDescription`,  `TaskStatus`,  `followup_task`,  `TaskID`,  `Emailfrom`,  `EmailTo`,  `EmailToName`,  `EmailSubject`,  `EmailMessage`,  `EmailCc`, `EmailBcc`,  `EmailAttachments`,  `AccountEmailLogID`,  `NoteID`,  `Note`,  `TicketID`,  `TicketSubject`,  `TicketStatus`,  `RequestEmail`,  `TicketPriority`,  `TicketType`,  `TicketGroup`,  `TicketDescription`,  `CreatedBy`,  `created_at`,  `updated_at`,  `GUID`,`TableCreated_at`)
				SELECT 
				1 as Timeline_type,
				t.Subject,
				  concat(u.FirstName,' ',u.LastName) as Name,		
				 case when t.Priority =1
					  then 'High'
					  else
					   'Low' end  as Priority,
					DueDate,
				t.Description,
				bc.BoardColumnName as TaskStatus,
				t.Task_type,
				t.TaskID,
				'' as Emailfrom ,'' as EmailTo,'' as EmailToName,'' as EmailSubject,'' as Message,''as EmailCc,''as EmailBcc,''as EmailAttachments,0 as AccountEmailLogID,0 as NoteID,'' as Note ,
				0 as TicketID, '' as 	TicketSubject,	'' as	TicketStatus,	'' as 	RequestEmail,	'' as 	TicketPriority,	'' as 	TicketType,	'' as 	TicketGroup,	'' as TicketDescription,
				t.CreatedBy,t.created_at, t.updated_at,p_GUID as GUID,p_Time as TableCreated_at
			FROM tblTask t
			INNER JOIN tblCRMBoardColumn bc on  t.BoardColumnID = bc.BoardColumnID	
			JOIN tblUser u on  u.UserID = t.UsersIDs		
			WHERE t.AccountIDs = p_AccountID and t.CompanyID =p_CompanyID;
			
			
			
			
			INSERT INTO tbl_Account_Contacts_Activity(  `Timeline_type`,  `TaskTitle`,  `TaskName`,  `TaskPriority`,  `DueDate`,  `TaskDescription`,  `TaskStatus`,  `followup_task`,  `TaskID`,  `Emailfrom`,  `EmailTo`,  `EmailToName`,  `EmailSubject`,  `EmailMessage`,  `EmailCc`, `EmailBcc`,  `EmailAttachments`,  `AccountEmailLogID`,  `NoteID`,  `Note`,  `TicketID`,  `TicketSubject`,  `TicketStatus`,  `RequestEmail`,  `TicketPriority`,  `TicketType`,  `TicketGroup`,  `TicketDescription`,  `CreatedBy`,  `created_at`,  `updated_at`,  `GUID`,`TableCreated_at`)
			select 2 as Timeline_type,'' as TaskTitle,'' as TaskName,'' as TaskPriority, '0000-00-00 00:00:00' as DueDate, '' as TaskDescription,'' as TaskStatus,0 as Task_type,0 as TaskID, Emailfrom, EmailTo,	
			case when concat(tu.FirstName,' ',tu.LastName) IS NULL or concat(tu.FirstName,' ',tu.LastName) = ''
					then ael.EmailTo
					else concat(tu.FirstName,' ',tu.LastName)
			   end as EmailToName, 
			Subject,Message,Cc,Bcc,AttachmentPaths as EmailAttachments,AccountEmailLogID,0 as NoteID,'' as Note ,0 as TicketID, '' as 	TicketSubject,	'' as	TicketStatus,	'' as 	RequestEmail,	'' as 	TicketPriority,	'' as 	TicketType,	'' as 	TicketGroup,	'' as TicketDescription,ael.CreatedBy,ael.created_at, ael.updated_at,p_GUID as GUID,p_Time as TableCreated_at
			from `AccountEmailLog` ael
			left JOIN tblUser tu
				ON tu.EmailAddress = ael.EmailTo
			where ael.CompanyID = p_CompanyID AND ((ael.AccountID = p_AccountID) OR (FIND_IN_SET(ael.ContactID,(v_contacts_ids)) ))			
			and ael.EmailParent=0 and ael.TicketID = 0
						 
			order by ael.created_at desc;
			
			
			
			INSERT INTO tbl_Account_Contacts_Activity(  `Timeline_type`,  `TaskTitle`,  `TaskName`,  `TaskPriority`,  `DueDate`,  `TaskDescription`,  `TaskStatus`,  `followup_task`,  `TaskID`,  `Emailfrom`,  `EmailTo`,  `EmailToName`,  `EmailSubject`,  `EmailMessage`,  `EmailCc`, `EmailBcc`,  `EmailAttachments`,  `AccountEmailLogID`,  `NoteID`,  `Note`,  `TicketID`,  `TicketSubject`,  `TicketStatus`,  `RequestEmail`,  `TicketPriority`,  `TicketType`,  `TicketGroup`,  `TicketDescription`,  `CreatedBy`,  `created_at`,  `updated_at`,  `GUID`,`TableCreated_at`)
			select 3 as Timeline_type,'' as TaskTitle,'' as TaskName,'' as TaskPriority, '0000-00-00 00:00:00' as DueDate, '' as TaskDescription,'' as TaskStatus, 0 as Task_type,0 as TaskID, '' as Emailfrom ,'' as EmailTo,'' as EmailToName,'' as EmailSubject,'' as Message,''as EmailCc,''as EmailBcc,''as EmailAttachments,0 as AccountEmailLogID,NoteID,Note,0 as TicketID, '' as 	TicketSubject,	'' as	TicketStatus,	'' as 	RequestEmail,	'' as 	TicketPriority,	'' as 	TicketType,	'' as 	TicketGroup,	'' as TicketDescription,created_by,created_at,updated_at ,p_GUID as GUID,p_Time as TableCreated_at
			from `tblNote` 
			where (`CompanyID` = p_CompanyID and `AccountID` = p_AccountID and TicketID =0) order by created_at desc;
			
			INSERT INTO tbl_Account_Contacts_Activity(  `Timeline_type`,  `TaskTitle`,  `TaskName`,  `TaskPriority`,  `DueDate`,  `TaskDescription`,  `TaskStatus`,  `followup_task`,  `TaskID`,  `Emailfrom`,  `EmailTo`,  `EmailToName`,  `EmailSubject`,  `EmailMessage`,  `EmailCc`, `EmailBcc`,  `EmailAttachments`,  `AccountEmailLogID`,  `ContactNoteID`,  `Note`,  `TicketID`,  `TicketSubject`,  `TicketStatus`,  `RequestEmail`,  `TicketPriority`,  `TicketType`,  `TicketGroup`,  `TicketDescription`,  `CreatedBy`,  `created_at`,  `updated_at`,  `GUID`,`TableCreated_at`)
			select 3 as Timeline_type,'' as TaskTitle,'' as TaskName,'' as TaskPriority, '0000-00-00 00:00:00' as DueDate, '' as TaskDescription,'' as TaskStatus, 0 as Task_type,0 as TaskID, '' as Emailfrom ,'' as EmailTo,'' as EmailToName,'' as EmailSubject,'' as Message,''as EmailCc,''as EmailBcc,''as EmailAttachments,0 as AccountEmailLogID,NoteID,Note,0 as TicketID, '' as 	TicketSubject,	'' as	TicketStatus,	'' as 	RequestEmail,	'' as 	TicketPriority,	'' as 	TicketType,	'' as 	TicketGroup,	'' as TicketDescription,created_by,created_at,updated_at ,p_GUID as GUID,p_Time as TableCreated_at
			from `tblContactNote` where (`CompanyID` = p_CompanyID and FIND_IN_SET(ContactID,(v_contacts_ids)))  order by created_at desc;
			
			
			
			
				
			IF p_TicketType=2 
			THEN
			INSERT INTO tbl_Account_Contacts_Activity(  `Timeline_type`,  `TaskTitle`,  `TaskName`,  `TaskPriority`,  `DueDate`,  `TaskDescription`,  `TaskStatus`,  `followup_task`,  `TaskID`,  `Emailfrom`,  `EmailTo`,  `EmailToName`,  `EmailSubject`,  `EmailMessage`,  `EmailCc`, `EmailBcc`,  `EmailAttachments`,  `AccountEmailLogID`,  `NoteID`,  `Note`,  `TicketID`,  `TicketSubject`,  `TicketStatus`,  `RequestEmail`,  `TicketPriority`,  `TicketType`,  `TicketGroup`,  `TicketDescription`,  `CreatedBy`,  `created_at`,  `updated_at`,  `GUID`,`TableCreated_at`)
			select 4 as Timeline_type,'' as TaskTitle,'' as TaskName,'' as TaskPriority, '0000-00-00 00:00:00' as DueDate, '' as TaskDescription,'' as TaskStatus, 0 as Task_type,0 as TaskID, '' as Emailfrom ,'' as EmailTo,'' as EmailToName,'' as EmailSubject,'' as Message,''as EmailCc,''as EmailBcc,''as EmailAttachments,0 as AccountEmailLogID, 0 as NoteID,'' as Note,
			TAT.TicketID,	TAT.Subject as 	TicketSubject,	TAT.Status as	TicketStatus,	TAT.RequestEmail as 	RequestEmail,	TAT.Priority as 	TicketPriority,	TAT.`Type` as 	TicketType,	TAT.`Group` as 	TicketGroup,	TAT.`Description` as TicketDescription,created_by,ApiCreatedDate as created_at,ApiUpdateDate as updated_at,p_GUID as GUID,p_Time as TableCreated_at 
			from 
				`tblHelpDeskTickets` TAT 
			where 
				(TAT.`CompanyID` = p_CompanyID and TAT.`AccountID` = p_AccountID and TAT.GUID = p_GUID);
			END IF;

			IF p_TicketType=1 
			THEN
			INSERT INTO tbl_Account_Contacts_Activity(  `Timeline_type`,  `TaskTitle`,  `TaskName`,  `TaskPriority`,  `DueDate`,  `TaskDescription`,  `TaskStatus`,  `followup_task`,  `TaskID`,  `Emailfrom`,  `EmailTo`,  `EmailToName`,  `EmailSubject`,  `EmailMessage`,  `EmailCc`, `EmailBcc`,  `EmailAttachments`,  `AccountEmailLogID`,  `NoteID`,  `Note`,  `TicketID`,  `TicketSubject`,  `TicketStatus`,  `RequestEmail`,  `TicketPriority`,  `TicketType`,  `TicketGroup`,  `TicketDescription`,  `CreatedBy`,  `created_at`,  `updated_at`,  `GUID`,`TableCreated_at`)
				select 4 as Timeline_type,'' as TaskTitle,'' as TaskName,'' as TaskPriority, '0000-00-00 00:00:00' as DueDate, '' as TaskDescription,'' as TaskStatus, 0 as Task_type,0 as TaskID, '' as Emailfrom ,'' as EmailTo,'' as EmailToName,'' as EmailSubject,'' as Message,''as EmailCc,''as EmailBcc,''as EmailAttachments,0 as AccountEmailLogID, 0 as NoteID,'' as Note,
				TT.TicketID,TT.Subject as 	TicketSubject,	TFV.FieldValueAgent  as	TicketStatus,	TT.Requester as 	RequestEmail,TP.PriorityValue as TicketPriority,	TFVV.FieldValueAgent as 	TicketType,	TG.GroupName as TicketGroup,	TT.`Description` as TicketDescription,TT.created_by,TT.created_at,TT.updated_at,p_GUID as GUID,p_Time as TableCreated_at 
			from 
				`tblTickets` TT
			LEFT JOIN tblTicketfieldsValues TFV
				ON TFV.ValuesID = TT.Status		
			LEFT JOIN tblTicketPriority TP
				ON TP.PriorityID = TT.Priority
			LEFT JOIN tblTicketGroups TG
				ON TG.GroupID = TT.`Group`
			LEFT JOIN tblTicketfieldsValues TFVV
				ON TFVV.ValuesID = TT.Type
			
			where 			
				TT.`CompanyID` = p_CompanyID and 
			
			FIND_IN_SET(TT.Requester,(v_account_contacts_emails));	
			END IF;
			
END IF;
	select * from tbl_Account_Contacts_Activity where GUID = p_GUID order by created_at desc LIMIT p_RowspPage OFFSET v_OffSet_ ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetActiveCronJob` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_GetActiveCronJob`(
	IN `p_companyid` INT,
	IN `p_Title` VARCHAR(500),
	IN `p_Status` INT,
	IN `p_Active` INT,
	IN `p_Type` INT,
	IN `p_CurrentDateTime` DATETIME,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT 


)
BEGIN

   DECLARE v_OffSet_ int;
   SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
	 
	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
	
	
    IF p_isExport = 0
    THEN
         
		SELECT
			jb.Active,
			CONCAT(jb.PID,CASE WHEN jb.MysqlPID !='' THEN '-' ELSE '' END,CASE when jb.MysqlPID!='' THEN jb.MysqlPID ELSE '' END) as PID,
			jb.JobTitle,                
			CONCAT(TIMESTAMPDIFF(HOUR,LastRunTime,p_CurrentDateTime),' Hours, ',TIMESTAMPDIFF(minute,LastRunTime,p_CurrentDateTime)%60,' Minutes, ',TIMESTAMPDIFF(second,LastRunTime,p_CurrentDateTime)%60 , ' Seconds' ) AS RunningTime,
			
 			jb.LastRunTime,
			jb.NextRunTime,			
			jb.CronJobID,
			jb.Status,	                 	
          jb.CronJobCommandID,
          jb.Settings	,
 		   (select CronJobStatus from tblCronJobLog where tblCronJobLog.CronJobID = jb.CronJobID order by  CronJobLogID desc limit 1)  as  CronJobStatus
			 	                 							
		FROM tblCronJob jb
		INNER JOIN tblCronJobCommand cm ON cm.CronJobCommandID = jb.CronJobCommandID
      WHERE jb.CompanyID = p_companyid 
		AND (p_Title = '' OR (p_Title != '' AND jb.JobTitle like concat('%', p_Title , '%') ) )
		AND  (p_Status = -1 OR (p_Status != -1 and jb.Status = p_Status ) )
		 AND (p_Active = -1 OR (p_Active != -1 and  jb.Active = p_Active ) )
		 AND (p_Type = 0 OR (p_Type != 0 and  jb.CronJobCommandID = p_Type ) )
      ORDER BY                
			CASE
			  WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'JobTitleDESC') THEN jb.JobTitle
			END DESC,
			CASE
			  WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'JobTitleASC') THEN jb.JobTitle
			END ASC,				
			CASE
			  WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'PIDDESC') THEN jb.PID
			END DESC,
			CASE
			  WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'PIDASC') THEN jb.PID
			END ASC,
			CASE
			  WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'LastRunTimeASC') THEN jb.LastRunTime
			END ASC,
			CASE
			  WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'LastRunTimeDESC') THEN jb.LastRunTime
			END DESC,
			CASE
			  WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'NextRunTimeASC') THEN jb.NextRunTime
			END ASC,
			CASE
			  WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'NextRunTimeDESC') THEN jb.NextRunTime
			END DESC
		
		LIMIT p_RowspPage OFFSET v_OffSet_;


     SELECT
         COUNT(jb.CronJobID) as totalcount
     FROM tblCronJob jb
		INNER JOIN tblCronJobCommand cm ON cm.CronJobCommandID = jb.CronJobCommandID
      WHERE jb.CompanyID = p_companyid 
		AND (p_Title = '' OR (p_Title != '' AND jb.JobTitle like concat('%', p_Title , '%') ) )
		AND  (p_Status = -1 OR (p_Status != -1 and jb.Status = p_Status ) )
		AND (p_Active = -1 OR (p_Active != -1 and  jb.Active = p_Active ) )
		AND (p_Type = 0 OR (p_Type != 0 and  jb.CronJobCommandID = p_Type ) );
		 
    END IF;

    IF p_isExport = 1
    THEN
        SELECT
			jb.Active,
			jb.PID,
			jb.JobTitle,                
			CONCAT(TIMESTAMPDIFF(HOUR,LastRunTime,p_CurrentDateTime),' Hours, ',TIMESTAMPDIFF(minute,LastRunTime,p_CurrentDateTime)%60,' Minutes, ',TIMESTAMPDIFF(second,LastRunTime,p_CurrentDateTime)%60 , ' Seconds' ) AS RunningTime,
 			jb.LastRunTime,
			jb.NextRunTime
        FROM tblCronJob jb
			INNER JOIN tblCronJobCommand cm ON cm.CronJobCommandID = jb.CronJobCommandID
	      WHERE jb.CompanyID = p_companyid 
			AND (p_Title = '' OR (p_Title != '' AND jb.JobTitle like concat('%', p_Title , '%') ) )
			AND  (p_Status = -1 OR (p_Status != -1 and jb.Status = p_Status ) )
			AND (p_Active = -1 OR (p_Active != -1 and  jb.Active = p_Active ) )
			AND (p_Type = 0 OR (p_Type != 0 and  jb.CronJobCommandID = p_Type ) );
		 	
		 	
    END IF;
    SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getActiveCronJobCommand` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getActiveCronJobCommand`(IN `p_CompanyID` INT, IN `p_CronJobID` INT)
BEGIN

   SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SELECT
		tblCronJobCommand.Command,
		tblCronJob.CronJobID
	FROM tblCronJob
	INNER JOIN tblCronJobCommand
		ON tblCronJobCommand.CronJobCommandID = tblCronJob.CronJobCommandID
	WHERE tblCronJob.CronJobID = p_CronJobID and tblCronJob.CompanyID = p_CompanyID 
	AND tblCronJob.Status = 1;

   SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;	
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetAjaxActionList` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetAjaxActionList`(IN `p_CompanyID` INT, IN `p_ResourceCategoryID` LONGTEXT, IN `p_action` int)
BEGIN

    SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;  
	
	IF p_action = 1
    THEN
	select distinct r.ResourceID,r.ResourceName,
		case when rcm.ResourceID>0
		then
		1
		else
		null
		end As Checked 
	From `tblResource` r left join  `tblResourceCategoryMapping` rcm on r.ResourceID=rcm.ResourceID and (FIND_IN_SET(rcm.ResourceCategoryID,p_ResourceCategoryID) != 0 ) 
		where r.CompanyID=p_CompanyID
	order by
		 case when rcm.ResourceID>0
	 then
		1
     else
	    null
     end
	  desc, ResourceName asc;
	
	 END IF;
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetAjaxResourceList` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetAjaxResourceList`(
	IN `p_CompanyID` INT,
	IN `p_userid` LONGTEXT,
	IN `p_roleids` LONGTEXT,
	IN `p_action` int
)
BEGIN

    SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	IF p_action = 1
    THEN

        select distinct tblResourceCategories.ResourceCategoryID,tblResourceCategories.ResourceCategoryName,tblResourceCategories.CategoryGroupID,usrper.AddRemove,rolres.Checked
			from tblResourceCategories
			LEFT OUTER JOIN(
			select distinct rs.ResourceID, rs.ResourceName,usrper.AddRemove
			from tblResource rs
			inner join tblUserPermission usrper on usrper.resourceID = rs.ResourceID and FIND_IN_SET(usrper.UserID ,p_userid) != 0 ) usrper
			on usrper.ResourceID = tblResourceCategories.ResourceCategoryID
			LEFT OUTER JOIN(
			select distinct res.ResourceID, res.ResourceName,'true' as Checked
			from `tblResource` res
			inner join `tblRolePermission` rolper on rolper.resourceID = res.ResourceID and FIND_IN_SET(rolper.roleID ,p_roleids) != 0) rolres
			on rolres.ResourceID = tblResourceCategories.ResourceCategoryID
			where tblResourceCategories.CompanyID= p_CompanyID order by rolres.Checked desc,usrper.AddRemove desc,tblResourceCategories.ResourceCategoryName;


	END IF;

	IF p_action = 2
	THEN

		select  distinct `tblResourceCategories`.`ResourceCategoryID`, `tblResourceCategories`.`ResourceCategoryName`,tblResourceCategories.CategoryGroupID, tblRolePermission.resourceID as Checked ,case when tblRolePermission.resourceID>0
	 then
		1
     else
	    0
     end as check2
		from tblResourceCategories left join tblRolePermission on `tblRolePermission`.`resourceID` = `tblResourceCategories`.`ResourceCategoryID`
		and `tblRolePermission`.`CompanyID` = p_CompanyID and FIND_IN_SET(`tblRolePermission`.`roleID`,p_roleids) != 0
		order by
		case when tblRolePermission.resourceID>0
	 then
		1
     else
	    0
     end
	  desc,`tblResourceCategories`.`ResourceCategoryName` asc;


	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetAjaxRoleList` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetAjaxRoleList`(IN `p_CompanyID` INT, IN `p_UserID` LONGTEXT, IN `p_ResourceID` LONGTEXT, IN `p_action` int)
BEGIN

    SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;  
	
	IF p_action = 1
	THEN

	select distinct `tblRole`.`RoleID`, `tblRole`.`RoleName`, tblUserRole.RoleID as Checked,case when tblUserRole.RoleID>0
	 then
		1
     else
	    0
     end as check2
	 from tblRole 
	 left join tblUserRole on `tblUserRole`.`RoleID` = `tblRole`.`RoleID` and `tblRole`.`CompanyID` = p_CompanyID and  FIND_IN_SET(`tblUserRole`.`UserID`, p_UserID) != 0
	 order by
	 case when tblUserRole.RoleID>0
	 then
		1
     else
	    0
     end
	  desc,`tblRole`.`RoleName` asc;

	END IF;
	
	IF p_action = 2
	THEN

	select distinct `tblRole`.`RoleID`, `tblRole`.`RoleName`, tblRolePermission.RoleID as Checked,case when tblRolePermission.RoleID>0
	 then
		1
     else
	    0
     end as check2
	 from tblRole 
	 left join tblRolePermission on `tblRolePermission`.`roleID` = `tblRole`.`RoleID` and `tblRolePermission`.`CompanyID` = p_CompanyID and FIND_IN_SET(`tblRolePermission`.`resourceID`,p_ResourceID) != 0
	  order by
	  case when tblRolePermission.RoleID>0
	 then
		1
     else
	    0
     end
	  desc,`tblRole`.`RoleName` asc;
	
	END IF;
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetAjaxUserList` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetAjaxUserList`(IN `p_CompanyID` INT, IN `p_ResourceCategoryID` LONGTEXT, IN `p_roleids` LONGTEXT, IN `p_action` int)
BEGIN

   SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;  
	
	IF p_action = 1
	THEN

	select distinct `tblUser`.`UserID`, (CONCAT(tblUser.FirstName,' ',tblUser.LastName)) as UserName,case when tblUserRole.RoleID>0
	 then
		1
     else
	    null
     end As Checked 
		from tblUser left join tblUserRole on `tblUserRole`.`UserID` = `tblUser`.`UserID` 
		and `tblUser`.`CompanyID` = p_CompanyID and FIND_IN_SET(`tblUserRole`.`RoleID`,p_roleids)  != 0
		where `AdminUser` != '1' or `AdminUser` is null
		 order by
		 case when tblUserRole.RoleID>0
	 then
		1
     else
	    null
     end
	  desc, UserName asc;

	END IF;
	
	IF p_action = 2
	THEN

	SELECT distinct u.UserID,(CONCAT(u.FirstName,' ',u.LastName)) as UserName,Perm.Checked, UPerm.AddRemove
		FROM tblUser u
		LEFT OUTER JOIN
		(SELECT distinct u.userid,'true' as Checked,tblResourceCategories.ResourceCategoryName as permname
		FROM tblUser u
		inner join tblUserRole ur on u.UserID = ur.UserID
		inner join tblRole r on ur.RoleID = r.RoleID
		inner join tblRolePermission rp on r.RoleID = rp.roleID
		inner join tblResourceCategories on rp.resourceID = tblResourceCategories.ResourceCategoryID
		WHERE  FIND_IN_SET(tblResourceCategories.ResourceCategoryID,p_ResourceCategoryID) != 0 ) Perm
		ON u.UserID = Perm.UserID
		LEFT OUTER JOIN
		(SELECT distinct u.userid, up.AddRemove,tblResourceCategories.ResourceCategoryName as permname
		FROM tblUser u
		inner join tblUserPermission up on u.UserID = up.UserID
		inner join tblResourceCategories on up.resourceID = tblResourceCategories.ResourceCategoryID
		WHERE FIND_IN_SET(tblResourceCategories.ResourceCategoryID ,p_ResourceCategoryID) != 0 ) UPerm
		on u.userid = UPerm.userid
		where u.CompanyID = p_CompanyID and u.AdminUser != 1 or u.AdminUser is null
		order by Perm.Checked desc, UPerm.AddRemove desc,UserName asc;

	END IF;
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getAlert` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getAlert`(
	IN `p_CompanyID` INT,
	IN `p_AlertGroup` VARCHAR(50),
	IN `p_AlertType` VARCHAR(50),
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT
)
BEGIN

	DECLARE v_OffSet_ int;
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

	IF p_isExport = 0
	THEN

		SELECT
			Name,
			AlertType,
			Status,
			LowValue,
			HighValue,
			updated_at,
			UpdatedBy,
			AlertID,
			Settings
		FROM tblAlert
		WHERE  CompanyID = p_CompanyID
			AND CreatedByCustomer = 0 
			AND (p_AlertGroup = '' OR AlertGroup = p_AlertGroup)
			AND (p_AlertType = '' OR AlertType = p_AlertType)
		ORDER BY
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'NameDESC') THEN Name
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'NameASC') THEN Name
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UpdatedByDESC') THEN UpdatedBy
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UpdatedByASC') THEN UpdatedBy
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_atDESC') THEN updated_at
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_atASC') THEN updated_at
			END ASC
		LIMIT p_RowspPage OFFSET v_OffSet_;

		SELECT
			COUNT(AlertID) AS totalcount
		FROM tblAlert
		WHERE  CompanyID = p_CompanyID
			AND CreatedByCustomer = 0 
			AND (p_AlertGroup = '' OR AlertGroup = p_AlertGroup)
			AND (p_AlertType = '' OR AlertType = p_AlertType);

	END IF;

	IF p_isExport = 1
	THEN
	
		SELECT
			Name,
			UpdatedBy,
			updated_at
		FROM tblAlert
		WHERE  CompanyID = p_CompanyID
			AND CreatedByCustomer = 0 
			AND (p_AlertGroup = '' OR AlertGroup = p_AlertGroup)
			AND (p_AlertType = '' OR AlertType = p_AlertType);
	
	END IF;
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getAlertHistory` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getAlertHistory`(
	IN `p_CompanyID` INT,
	IN `p_AlertID` INT,
	IN `p_AlertType` VARCHAR(50),
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_SearchText` VARCHAR(50),
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT
)
BEGIN

	DECLARE v_OffSet_ int;
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

	IF p_isExport = 0
	THEN
		SELECT
			tblAlert.Name,
			tblAlert.AlertType,
			tblAlertLog.send_at,
			AccountEmailLog.Subject,
			AccountEmailLog.Message
		FROM tblAlert
		INNER JOIN tblAlertLog 
			ON tblAlert.AlertID = tblAlertLog.AlertID
		INNER JOIN AccountEmailLog 
			ON tblAlertLog.AccountEmailLogID = AccountEmailLog.AccountEmailLogID
		WHERE tblAlert.CompanyID = p_CompanyID
			AND (p_AlertID = 0 OR tblAlert.AlertID = p_AlertID)
			AND (p_AlertType = '' OR tblAlert.AlertType = p_AlertType)
			AND tblAlertLog.send_at BETWEEN p_StartDate and p_EndDate
			AND (p_SearchText='' OR tblAlert.Name LIKE CONCAT('%',p_SearchText,'%'))
		ORDER BY
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MessageDESC') THEN tblAlert.Name
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MessageASC') THEN tblAlert.Name
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AlertTypeDESC') THEN tblAlert.AlertType
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'AlertTypeASC') THEN tblAlert.AlertType
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atDESC') THEN tblAlertLog.send_at
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atASC') THEN tblAlertLog.send_at
			END ASC
		LIMIT p_RowspPage OFFSET v_OffSet_;

		SELECT
			COUNT(tblAlertLog.AlertLogID) as totalcount
		FROM tblAlert
		INNER JOIN tblAlertLog 
			ON tblAlert.AlertID = tblAlertLog.AlertID
		WHERE CompanyID = p_CompanyID
			AND (p_AlertID = 0 OR tblAlert.AlertID = p_AlertID)
			AND (p_AlertType = '' OR tblAlert.AlertType = p_AlertType)
			AND tblAlertLog.send_at BETWEEN p_StartDate and p_EndDate
			AND (p_SearchText='' OR tblAlert.Name LIKE CONCAT('%',p_SearchText,'%'));
	END IF;

	IF p_isExport = 1
	THEN
		SELECT
			tblAlert.Name,
			tblAlert.AlertType,
			tblAlertLog.send_at
		FROM tblAlert
		INNER JOIN tblAlertLog 
			ON tblAlert.AlertID = tblAlertLog.AlertID
		WHERE CompanyID = p_CompanyID
			AND (p_AlertID = 0 OR tblAlert.AlertID = p_AlertID)
			AND (p_AlertType = '' OR tblAlert.AlertType = p_AlertType)
			AND tblAlertLog.send_at BETWEEN p_StartDate and p_EndDate
			AND (p_SearchText='' OR tblAlert.Name LIKE CONCAT('%',p_SearchText,'%'));
	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetAllDashboardData` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetAllDashboardData`(IN `p_companyId` INT, IN `p_userId` INT, IN `p_isadmin` INT)
BEGIN
  DECLARE v_isAccountManager_ int;
   
SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
 

SELECT count(*) as TotalDueCustomer,DAYSDIFF from (
			SELECT distinct  a.AccountName,a.AccountID,cr.TrunkID,cr.EffectiveDate,TIMESTAMPDIFF(DAY,cr.EffectiveDate, NOW()) as DAYSDIFF
			FROM tblCustomerRate cr
			INNER JOIN tblRate  r on r.RateID =cr.RateID
			INNER JOIN tblCountry c on c.CountryID = r.CountryID
			INNER JOIN tblAccount a on a.AccountID = cr.CustomerID
			WHERE a.CompanyId =@companyId
			AND TIMESTAMPDIFF(DAY, cr.EffectiveDate, DATE_FORMAT (NOW(),120)) BETWEEN -1 AND 1

		) as tbl
		LEFT JOIN tblJob ON tblJob.AccountID = tbl.AccountID
					AND tblJob.JobID IN(select JobID from tblJob where JobTypeID = (select JobTypeID from tblJobType where Code='CD'))
					AND FIND_IN_SET (tbl.TrunkID,JSON_EXTRACT(tblJob.Options, '$.Trunks')) != 0

					AND ( TIMESTAMPDIFF(DAY, tblJob.created_at, NOW()) = DAYSDIFF or TIMESTAMPDIFF(DAY, tblJob.created_at, EffectiveDate)  BETWEEN -1 AND 0)

		where JobStatusID is null or JobStatusID <> (select JobStatusID from tblJobStatus where Code='S')
		group by DAYSDIFF
		order by DAYSDIFF desc;

 
        

        SELECT count(*) as TotalDueVendor ,DAYSDIFF from (
				SELECT  DISTINCT a.AccountName,a.AccountID,vr.TrunkID,vr.EffectiveDate,TIMESTAMPDIFF(DAY,vr.EffectiveDate, NOW()) as DAYSDIFF
			FROM tblVendorRate vr
			INNER JOIN tblRate  r on r.RateID =vr.RateID
			INNER JOIN tblCountry c on c.CountryID = r.CountryID
			INNER JOIN tblAccount a on a.AccountID = vr.AccountId
			WHERE a.CompanyId = @companyId
			AND TIMESTAMPDIFF(DAY,vr.EffectiveDate, NOW()) BETWEEN -1 AND 1
	   ) as tbl
		LEFT JOIN tblJob ON tblJob.AccountID = tbl.AccountID
					AND tblJob.JobID IN(select JobID from tblJob where JobTypeID = (select JobTypeID from tblJobType where Code='VD'))
					AND FIND_IN_SET (tbl.TrunkID,JSON_EXTRACT(tblJob.Options, '$.Trunks')) != 0
					AND ( TIMESTAMPDIFF(DAY, tblJob.created_at, NOW()) = DAYSDIFF or TIMESTAMPDIFF(DAY, tblJob.created_at, EffectiveDate)  BETWEEN -1 AND 0)

		where JobStatusID is null or JobStatusID <> (select JobStatusID from tblJobStatus where Code='S')
		group by DAYSDIFF
		order by DAYSDIFF desc;
  
   
     select `tblJob`.`JobID`, `tblJob`.`Title`, `tblJobStatus`.`Title` as Status, `tblJob`.`HasRead`, `tblJob`.`CreatedBy`, `tblJob`.`created_at` 
     from tblJob inner join tblJobStatus on `tblJob`.`JobStatusID` = `tblJobStatus`.`JobStatusID` inner join tblJobType on `tblJob`.`JobTypeID` = `tblJobType`.`JobTypeID` 
     where `tblJob`.`CompanyID` = p_companyId AND ( p_isadmin = 1 OR (p_isadmin = 0 and tblJob.JobLoggedUserID = p_userId) )
     order by `tblJob`.`ShowInCounter` desc, `tblJob`.`updated_at` desc,tblJob.JobID desc
	  limit 10;
     
    
 
    select count(*) as aggregate from tblJob inner join tblJobStatus on `tblJob`.`JobStatusID` = `tblJobStatus`.`JobStatusID` 
    where `tblJobStatus`.`Title` = 'Pending' and `tblJob`.`CompanyID` = p_companyId AND 
     ( p_isadmin = 1 OR ( p_isadmin = 0 and tblJob.JobLoggedUserID = p_userId) );
   
  
 
      select `tblJob`.`JobID`, `tblJob`.`Title`, `tblJobStatus`.`Title` as Status, `tblJob`.`CreatedBy`, `tblJob`.`created_at` from tblJob inner join tblJobStatus on `tblJob`.`JobStatusID` = `tblJobStatus`.`JobStatusID` inner join tblJobType on `tblJob`.`JobTypeID` = `tblJobType`.`JobTypeID` 
        where ( tblJobStatus.Title = 'Success' OR tblJobStatus.Title = 'Completed' ) and `tblJob`.`CompanyID` = p_companyId and
        ( p_isadmin = 1 OR ( p_isadmin = 0 and `tblJob`.`JobLoggedUserID` = p_userId))  and `tblJob`.`updated_at` >= DATE_SUB(NOW(), INTERVAL 7 DAY)
		  limit 10; 
        
	  
        select AccountID,AccountName,Phone,Email,created_by,created_at from tblAccount where (`AccountType` = '0' and `CompanyID` = p_companyId and `Status` = '1') order by `tblAccount`.`AccountID` desc limit 10;
    
 
    select AccountID,AccountName,Phone,Email,created_by,created_at from tblAccount 
          where 
          `AccountType` = '1' and CompanyID = p_companyId and `Status` = '1' 
          AND (  v_isAccountManager_ = 0 OR (v_isAccountManager_ = 1 AND tblAccount.Owner = p_userId ) )
    order by `tblAccount`.`AccountID` desc
	 limit 10;
  
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ; 
 
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetAllEmailMessages` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetAllEmailMessages`(
	IN `p_companyid` INT,
	IN `p_UserID` INT,
	IN `p_isadmin` INT,
	IN `p_EmailCall` VARCHAR(50),
	IN `p_Search` VARCHAR(200),
	IN `p_Unread` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT


)
    DETERMINISTIC
BEGIN
	DECLARE v_OffSet_ int;
	SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
	IF p_EmailCall = 1 
	THEN
         SELECT
           	   ae.AccountEmailLogID,
           	   ae.EmailfromName,
           	   ae.Subject,           	   
           	   ae.AttachmentPaths,
           	   tblMessages.created_at,              
               ae.AccountID,
               tblMessages.HasRead              
         FROM
				tblMessages
			INNER JOIN
					 AccountEmailLog ae
			ON 
				ae.AccountEmailLogID = tblMessages.EmailID			
         WHERE
				tblMessages.CompanyID = p_companyid        
				AND ae.EmailCall = p_EmailCall
				AND (p_isadmin = 1 OR (p_isadmin = 0 AND tblMessages.MsgLoggedUserID = p_UserID)) 
				AND (p_Search = '' OR (ae.Subject like Concat('%',p_Search,'%') OR ae.Message like Concat('%',p_Search,'%')))
				AND (p_Unread = 0 OR (p_Unread = 1 AND tblMessages.HasRead=0))				
		   ORDER BY
				tblMessages.MsgID desc      
         LIMIT
				p_RowspPage OFFSET p_PageNumber;
          
		  	  
         SELECT
				COUNT(tblMessages.MsgID) as totalcount
		   FROM tblMessages
				INNER JOIN AccountEmailLog ae
				ON ae.AccountEmailLogID = tblMessages.EmailID
		   WHERE tblMessages.CompanyID = p_companyid
				AND ae.EmailCall = p_EmailCall
				AND  (p_isadmin = 1 OR (p_isadmin = 0 AND tblMessages.MsgLoggedUserID = p_UserID))
				AND (p_Search = '' OR (ae.Subject like Concat('%',p_Search,'%') OR ae.Message like Concat('%',p_Search,'%')))
				AND (p_Unread = 0 OR (p_Unread = 1 AND tblMessages.HasRead=0));
   	END IF;
	 	IF p_EmailCall = 0 
		THEN
		SELECT
           	   ae.AccountEmailLogID as AccountEmailLogID,
           	   ae.EmailfromName as EmailfromName,
           	   ae.Subject as Subject,           	   
           	   ae.AttachmentPaths as AttachmentPaths, 
           	   ae.created_at as created_at,
               ae.CreatedBy as CreatedBy,
               ae.AccountID as AccountID,
               ae.EmailTo as EmailTo
      FROM
				AccountEmailLog ae						
      WHERE
				ae.CompanyID = p_companyid        
				AND ae.EmailCall = p_EmailCall
				AND  (p_isadmin = 1 OR (p_isadmin = 0 AND ae.UserID = p_UserID))  
				AND (p_Search = '' OR (ae.Subject like Concat('%',p_Search,'%') OR ae.Message like Concat('%',p_Search,'%')))
		ORDER BY
				ae.AccountEmailLogID desc      
      LIMIT
				p_RowspPage OFFSET p_PageNumber;
          
		  	  
         SELECT
				COUNT(ae.AccountEmailLogID) as totalcount
		   FROM AccountEmailLog ae
		   WHERE ae.CompanyID = p_companyid
				AND ae.EmailCall = p_EmailCall
				AND  (p_isadmin = 1 OR (p_isadmin = 0 AND ae.UserID = p_UserID))  
				AND (p_Search = '' OR (ae.Subject like Concat('%',p_Search,'%') OR ae.Message like Concat('%',p_Search,'%')));
	  END IF;  
			IF p_EmailCall = 2 
		THEN
				
			  SELECT
           	   ae.AccountEmailLogID,
           	   ae.EmailTo,
           	   ae.Subject,           	   
           	   ae.AttachmentPaths,
           	   ae.created_at           
            FROM
				AccountEmailLog ae						
            WHERE
				 ae.CompanyID = p_companyid   
				AND ae.EmailCall = p_EmailCall
				AND  (p_isadmin = 1 OR (p_isadmin = 0 AND ae.UserID = p_UserID)) 
				AND (p_Search = '' OR (ae.Subject like Concat('%',p_Search,'%')) OR (ae.Message like Concat('%',p_Search,'%')))			
		    order by
				ae.AccountEmailLogID desc      
           LIMIT
				p_RowspPage OFFSET p_PageNumber;
				
				  
           SELECT
				COUNT(ae.AccountEmailLogID) as totalcount
		   FROM AccountEmailLog ae
		   WHERE ae.CompanyID = p_companyid
				AND ae.EmailCall = p_EmailCall
				AND  (p_isadmin = 1 OR (p_isadmin = 0 AND ae.UserID = p_UserID))  
				AND (p_Search = '' OR (ae.Subject like Concat('%',p_Search,'%')) OR (ae.Message like Concat('%',p_Search,'%')));
				
			END IF; 	 
			
			
          SELECT
				COUNT(tblMessages.MsgID) as totalcountInbox
		   FROM tblMessages
				INNER JOIN AccountEmailLog ae
				ON ae.AccountEmailLogID = tblMessages.EmailID
	       WHERE
				 tblMessages.CompanyID = p_companyid
				 AND ae.EmailCall = 1
				 AND  (p_isadmin = 1 OR (p_isadmin = 0 AND tblMessages.MsgLoggedUserID = p_UserID))
				 AND  tblMessages.HasRead=0;
				 
				 
			SELECT
				COUNT(ae.AccountEmailLogID) as TotalCountDraft
		   FROM AccountEmailLog ae			
	       WHERE				
				 ae.CompanyID = p_companyid
				 AND ae.EmailCall = 2
				 AND  (p_isadmin = 1 OR (p_isadmin = 0 AND ae.UserID = p_UserID));
			
			
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetAllJobs` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetAllJobs`(IN `p_companyid` INT, IN `p_Status` INT, IN `p_Type` INT, IN `p_AccountID` INT, IN `p_UserID` INT, IN `p_PageNumber` INT, IN `p_RowspPage` INT, IN `p_lSortCol` VARCHAR(50), IN `p_SortOrder` VARCHAR(5), IN `p_isExport` INT)
BEGIN
	DECLARE v_OffSet_ int;
	SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
    
    

    IF p_isExport = 0
    THEN
          
            SELECT
                tblJob.Title,
                tblJobType.Title as Type,
                tblJobStatus.Title as Status,
                tblJob.created_at,
                tblJob.CreatedBy as CreatedBy,
                tblJob.JobID,
                tblJob.ShowInCounter,
                tblJob.updated_at
            FROM tblJob
           JOIN tblJobStatus 
                ON tblJob.JobStatusID = tblJobStatus.JobStatusID
            JOIN tblJobType 
                ON tblJob.JobTypeID = tblJobType.JobTypeID
            WHERE tblJob.CompanyID = p_companyid
            AND ( p_UserID = 0  OR ( p_UserID > 0 AND  tblJob.JobLoggedUserID = p_UserID )  )
            AND ( p_Status = ''  OR ( p_Status > 0 AND  tblJob.JobStatusID = p_Status )  )
            AND ( p_Type = ''  OR ( p_Type > 0 AND  tblJob.JobTypeID = p_Type )  )
            AND ( p_AccountID = ''  OR ( p_AccountID > 0 AND  tblJob.AccountID = p_AccountID )  )
            ORDER BY
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TitleDESC') THEN tblJob.Title
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TitleASC') THEN tblJob.Title
                END ASC,
                 CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TypeDESC') THEN tblJobType.Title
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TypeASC') THEN tblJobType.Title
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'StatusDESC') THEN tblJobStatus.Title
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'StatusASC') THEN tblJobStatus.Title
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atDESC') THEN tblJob.created_at
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atASC') THEN tblJob.created_at
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CreatedByDESC') THEN tblJob.CreatedBy
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CreatedByASC') THEN tblJob.CreatedBy
                END ASC

           LIMIT p_RowspPage OFFSET v_OffSet_;

        SELECT
            COUNT(tblJob.JobID) as totalcount
        FROM tblJob
           JOIN tblJobStatus 
                ON tblJob.JobStatusID = tblJobStatus.JobStatusID
            JOIN tblJobType 
                ON tblJob.JobTypeID = tblJobType.JobTypeID
            WHERE tblJob.CompanyID = p_companyid
            AND ( p_UserID = 0  OR ( p_UserID > 0 AND  tblJob.JobLoggedUserID = p_UserID )  )
            AND ( p_Status = ''  OR ( p_Status > 0 AND  tblJob.JobStatusID = p_Status )  )
            AND ( p_Type = ''  OR ( p_Type > 0 AND  tblJob.JobTypeID = p_Type )  )
            AND ( p_AccountID = ''  OR ( p_AccountID > 0 AND  tblJob.AccountID = p_AccountID )  );


    END IF;

    IF p_isExport = 1
    THEN
        SELECT
            tblJob.Title,
                tblJobType.Title as Type,
                tblJobStatus.Title as Status,
                tblJob.created_at,
                tblJob.CreatedBy as CreatedBy
        FROM tblJob
           JOIN tblJobStatus 
                ON tblJob.JobStatusID = tblJobStatus.JobStatusID
            JOIN tblJobType 
                ON tblJob.JobTypeID = tblJobType.JobTypeID
            WHERE tblJob.CompanyID = p_companyid
            AND ( p_UserID = 0  OR ( p_UserID > 0 AND  tblJob.JobLoggedUserID = p_UserID )  )
            AND ( p_Status = ''  OR ( p_Status > 0 AND  tblJob.JobStatusID = p_Status )  )
            AND ( p_Type = ''  OR ( p_Type > 0 AND  tblJob.JobTypeID = p_Type )  )
            AND ( p_AccountID = ''  OR ( p_AccountID > 0 AND  tblJob.AccountID = p_AccountID )  );
    END IF;
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetAllResourceCategoryByUser` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetAllResourceCategoryByUser`(
	IN `p_CompanyID` INT,
	IN `p_userid` LONGTEXT
)
BEGIN

    SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
     select distinct
		case
		when (rolres.Checked is not null and  usrper.AddRemove ='add') or (rolres.Checked is not null and usrper.AddRemove is null ) or	(rolres.Checked is null and  usrper.AddRemove ='add')
		then rescat.ResourceCategoryID
		end as ResourceCategoryID,
		case
		when (rolres.Checked is not null and  usrper.AddRemove ='add') or (rolres.Checked is not null and usrper.AddRemove is null ) or	(rolres.Checked is null and  usrper.AddRemove ='add')
		then rescat.ResourceCategoryName
		end as ResourceCategoryName
		from tblResourceCategories rescat
		LEFT OUTER JOIN(
			select distinct rescat.ResourceCategoryID, rescat.ResourceCategoryName,usrper.AddRemove
			from tblResourceCategories rescat
			inner join tblUserPermission usrper on usrper.resourceID = rescat.ResourceCategoryID and  FIND_IN_SET(usrper.UserID,p_userid) != 0 
			where usrper.CompanyID= p_CompanyID
			) usrper
			on usrper.ResourceCategoryID = rescat.ResourceCategoryID
			
	      LEFT OUTER JOIN(
			select distinct rescat.ResourceCategoryID, rescat.ResourceCategoryName,'true' as Checked
			from `tblResourceCategories` rescat
			inner join `tblRolePermission` rolper on rolper.resourceID = rescat.ResourceCategoryID and rolper.roleID in(SELECT RoleID FROM `tblUserRole` where FIND_IN_SET(UserID,p_userid) != 0 )
			where rolper.CompanyID= p_CompanyID
			) rolres
			on rolres.ResourceCategoryID = rescat.ResourceCategoryID
		;
		
		SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ; 
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getAutoImportMail` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getAutoImportMail`(
	IN `p_jobType` INT,
	IN `p_jobStatus` INT,
	IN `p_CompanyID` INT,
	IN `p_search` TEXT,
	IN `p_AccountID` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT
)
BEGIN

	DECLARE v_OffSet_ int;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

					IF (p_isExport = 0) THEN


							select IFNULL(jt.Title, 'Not Match') as jobType,
							CONCAT(  a.Subject, '<br>', a.AccountName, '<br>', a.`From` )  AS header,
							a.created_at,a.JobID,IFNULL(js.Title, 'Not Match') as jobstatus,a.AutoImportID, a.AccountID, IFNULL(ac.AccountName, '') from tblAutoImport a
							left join tblJob j on a.JobID=j.JobID
							left join tblJobType jt on j.JobTypeID = jt.JobTypeID
							left join tblJobStatus js on j.JobStatusID=js.JobStatusID
							left join tblAccount ac on a.AccountID=ac.AccountID
							where
								CASE
									WHEN (p_jobType > 0) THEN
										jt.JobTypeID = p_jobType AND a.CompanyID=p_CompanyID
									WHEN (p_jobStatus > 0) THEN
										js.JobStatusID = p_jobStatus AND a.CompanyID=p_CompanyID
									WHEN (p_search <> '') THEN
										    (  a.Subject LIKE CONCAT('%',p_search,'%')  OR a.JobID LIKE CONCAT('%',p_search,'%') )  AND a.CompanyID=p_CompanyID
								   ELSE
										a.CompanyID=p_CompanyID
								END
								AND ( p_AccountID = 0 OR a.AccountID=p_AccountID )
								ORDER BY
								  CASE WHEN p_lSortCol = 'Type' AND p_SortOrder = 'desc' THEN jobType END DESC,
								  CASE WHEN p_lSortCol = 'Type' THEN jobType END,
								  CASE WHEN p_lSortCol = 'Header' AND p_SortOrder = 'desc' THEN header END DESC,
								  CASE WHEN p_lSortCol = 'Header' THEN header END,
								  CASE WHEN p_lSortCol = 'Created' AND p_SortOrder = 'desc' THEN a.created_at END DESC,
								  CASE WHEN p_lSortCol = 'Created' THEN a.created_at END,
								  CASE WHEN p_lSortCol = 'Status' AND p_SortOrder = 'desc' THEN jobstatus END DESC,
								  CASE WHEN p_lSortCol = 'Status' THEN jobstatus END,
								  CASE WHEN p_lSortCol = 'JobId' AND p_SortOrder = 'desc' THEN a.JobID END DESC,
								  CASE WHEN p_lSortCol = 'JobId' THEN a.JobID END

							LIMIT p_RowspPage OFFSET v_OffSet_;

					ELSE


							select IFNULL(jt.Title, 'Not Match') as jobType,
							CONCAT(  a.Subject, '<br>', a.AccountName, '<br>', a.`From` )  AS header,
							a.created_at,a.JobID,IFNULL(js.Title, 'Not Match') as jobstatus,a.AutoImportID, a.AccountID, IFNULL(ac.AccountName, '') from tblAutoImport a
							left join tblJob j on a.JobID=j.JobID
							left join tblJobType jt on j.JobTypeID = jt.JobTypeID
							left join tblJobStatus js on j.JobStatusID=js.JobStatusID
							left join tblAccount ac on a.AccountID=ac.AccountID
							where
								CASE
									WHEN (p_jobType > 0) THEN
										jt.JobTypeID = p_jobType AND a.CompanyID=p_CompanyID
									WHEN (p_jobStatus > 0) THEN
										js.JobStatusID = p_jobStatus AND a.CompanyID=p_CompanyID
									WHEN (p_search <> '') THEN
										    (  a.Subject LIKE CONCAT('%',p_search,'%')  OR a.JobID LIKE CONCAT('%',p_search,'%') )  AND a.CompanyID=p_CompanyID
								   ELSE
										a.CompanyID=p_CompanyID
								END
								ORDER BY
								  CASE WHEN p_lSortCol = 'Type' AND p_SortOrder = 'desc' THEN jobType END DESC,
								  CASE WHEN p_lSortCol = 'Type' THEN jobType END,
								  CASE WHEN p_lSortCol = 'Header' AND p_SortOrder = 'desc' THEN header END DESC,
								  CASE WHEN p_lSortCol = 'Header' THEN header END,
								  CASE WHEN p_lSortCol = 'Created' AND p_SortOrder = 'desc' THEN a.created_at END DESC,
								  CASE WHEN p_lSortCol = 'Created' THEN a.created_at END,
								  CASE WHEN p_lSortCol = 'Status' AND p_SortOrder = 'desc' THEN jobstatus END DESC,
								  CASE WHEN p_lSortCol = 'Status' THEN jobstatus END,
								  CASE WHEN p_lSortCol = 'JobId' AND p_SortOrder = 'desc' THEN a.JobID END DESC,
								  CASE WHEN p_lSortCol = 'JobId' THEN a.JobID END
							;


					END IF;



					select COUNT(*) AS `totalcount` from tblAutoImport a
							left join tblJob j on a.JobID=j.JobID
							left join tblJobType jt on j.JobTypeID = jt.JobTypeID
							left join tblJobStatus js on j.JobStatusID=js.JobStatusID
							left join tblAccount ac on a.AccountID=ac.AccountID
							where 
								CASE 
									WHEN (p_jobType > 0) THEN
										jt.JobTypeID = p_jobType AND a.CompanyID=p_CompanyID
									WHEN (p_jobStatus > 0) THEN
										js.JobStatusID = p_jobStatus AND a.CompanyID=p_CompanyID
									WHEN (p_search <> '') THEN
										    (  a.Subject LIKE CONCAT('%',p_search,'%')  OR a.JobID LIKE CONCAT('%',p_search,'%') )  AND a.CompanyID=p_CompanyID
								   ELSE
										a.CompanyID=p_CompanyID				
								END
							LIMIT p_RowspPage OFFSET v_OffSet_;
		
		
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getAutoImportSetting_AccountAndRateTable` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getAutoImportSetting_AccountAndRateTable`(
	IN `p_SettingType` INT,
	IN `p_CompanyID` INT,
	IN `p_TrunkID` INT,
	IN `p_typePKID` INT,
	IN `p_search` TEXT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT


)
BEGIN

	DECLARE v_OffSet_ int;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
	
	
	
	IF (p_SettingType = 1 ) THEN  
		
					IF (p_isExport = 0) THEN
							
								
							select a.AccountName,t.Trunk , ut.Title,Subject,FileName,SendorEmail,a.AccountID,t.TrunkID,ut.FileUploadTemplateID,AutoImportSettingID from tblAutoImportSetting as s
							inner join tblTrunk as t on s.TrunkID=t.TrunkID
							inner join tblAccount as a on a.AccountID=s.TypePKID
							inner join tblFileUploadTemplate as ut on ut.FileUploadTemplateID=s.ImportFileTempleteID
							
							where 
								  CASE 
								  		WHEN (p_TrunkID > 0 AND p_typePKID > 0 AND p_search <> '') THEN
										    s.TrunkID=p_TrunkID AND  s.TypePKID=p_typePKID AND ( p_search = ''  OR s.Subject LIKE REPLACE(p_search,'*', '%') )  AND s.CompanyID = p_CompanyID AND s.`Type`= 1				    
								  		WHEN (p_TrunkID > 0 AND p_typePKID > 0) THEN
										    s.TrunkID=p_TrunkID AND  s.TypePKID=p_typePKID AND s.CompanyID = p_CompanyID AND s.`Type`= 1				    
										WHEN (p_TrunkID > 0) THEN
										    s.TrunkID=p_TrunkID AND  s.CompanyID = p_CompanyID AND s.`Type`= 1
									   WHEN (p_typePKID > 0) THEN
										    s.TypePKID = p_typePKID AND  s.CompanyID = p_CompanyID AND s.`Type`= 1
										WHEN (p_search <> '') THEN
										     (  s.Subject LIKE CONCAT('%',p_search,'%')  OR SendorEmail LIKE CONCAT('%',p_search,'%') OR ut.Title LIKE CONCAT('%',p_search,'%') ) AND  s.CompanyID = p_CompanyID AND s.`Type`= 1				    				    
										     
										    
										ELSE						
											 s.CompanyID = p_CompanyID AND s.`Type`= 1
										
									END
									
								ORDER BY
								  CASE WHEN p_lSortCol = 'AccountName' AND p_SortOrder = 'desc' THEN a.AccountName END DESC,
								  CASE WHEN p_lSortCol = 'AccountName' THEN a.AccountName END,
								  CASE WHEN p_lSortCol = 'Trunk' AND p_SortOrder = 'desc' THEN t.Trunk END DESC,
								  CASE WHEN p_lSortCol = 'Trunk' THEN t.Trunk END,
								  CASE WHEN p_lSortCol = 'Import File Templete' AND p_SortOrder = 'desc' THEN ut.Title END DESC,
								  CASE WHEN p_lSortCol = 'Import File Templete' THEN ut.Title END,
								  CASE WHEN p_lSortCol = 'Subject Match' AND p_SortOrder = 'desc' THEN Subject END DESC,
								  CASE WHEN p_lSortCol = 'Subject Match' THEN Subject END,
								  CASE WHEN p_lSortCol = 'Filename Match' AND p_SortOrder = 'desc' THEN FileName END DESC,
								  CASE WHEN p_lSortCol = 'Filename Match' THEN FileName END,
								  CASE WHEN p_lSortCol = 'Sendor Match' AND p_SortOrder = 'desc' THEN SendorEmail END DESC,
								  CASE WHEN p_lSortCol = 'Sendor Match' THEN SendorEmail END

													
							LIMIT p_RowspPage OFFSET v_OffSet_;
							
					ELSE
							
							
							select a.AccountName,t.Trunk , ut.Title,Subject,SendorEmail,FileName from tblAutoImportSetting as s
							inner join tblTrunk as t on s.TrunkID=t.TrunkID
							inner join tblAccount as a on a.AccountID=s.TypePKID
							inner join tblFileUploadTemplate as ut on ut.FileUploadTemplateID=s.ImportFileTempleteID
							
							where 
								  CASE 
								  		WHEN (p_TrunkID > 0 AND p_typePKID > 0 AND p_search <> '') THEN
										    s.TrunkID=p_TrunkID AND  s.TypePKID=p_typePKID AND ( p_search = ''  OR s.Subject LIKE REPLACE(p_search,'*', '%') )  AND s.CompanyID = p_CompanyID AND s.`Type`= 1				    
								  		WHEN (p_TrunkID > 0 AND p_typePKID > 0) THEN
										    s.TrunkID=p_TrunkID AND  s.TypePKID=p_typePKID AND s.CompanyID = p_CompanyID AND s.`Type`= 1				    
										WHEN (p_TrunkID > 0) THEN
										    s.TrunkID=p_TrunkID AND  s.CompanyID = p_CompanyID AND s.`Type`= 1
									   WHEN (p_typePKID > 0) THEN
										    s.TypePKID = p_typePKID AND  s.CompanyID = p_CompanyID AND s.`Type`= 1
										WHEN (p_search <> '') THEN

										    (  s.Subject LIKE CONCAT('%',p_search,'%')  OR SendorEmail LIKE CONCAT('%',p_search,'%') OR ut.Title LIKE CONCAT('%',p_search,'%') ) AND  s.CompanyID = p_CompanyID AND s.`Type`= 1				    				    
										ELSE						
											 s.CompanyID = p_CompanyID AND s.`Type`= 1
										
									END	
								ORDER BY
								  CASE WHEN p_lSortCol = 'AccountName' AND p_SortOrder = 'desc' THEN a.AccountName END DESC,
								  CASE WHEN p_lSortCol = 'AccountName' THEN a.AccountName END,
								  CASE WHEN p_lSortCol = 'Trunk' AND p_SortOrder = 'desc' THEN t.Trunk END DESC,
								  CASE WHEN p_lSortCol = 'Trunk' THEN t.Trunk END,
								  CASE WHEN p_lSortCol = 'Import File Templete' AND p_SortOrder = 'desc' THEN ut.Title END DESC,
								  CASE WHEN p_lSortCol = 'Import File Templete' THEN ut.Title END,
								  CASE WHEN p_lSortCol = 'Subject Match' AND p_SortOrder = 'desc' THEN Subject END DESC,
								  CASE WHEN p_lSortCol = 'Subject Match' THEN Subject END,
								  CASE WHEN p_lSortCol = 'Filename Match' AND p_SortOrder = 'desc' THEN FileName END DESC,
								  CASE WHEN p_lSortCol = 'Filename Match' THEN FileName END,
								  CASE WHEN p_lSortCol = 'Sendor Match' AND p_SortOrder = 'desc' THEN SendorEmail END DESC,
								  CASE WHEN p_lSortCol = 'Sendor Match' THEN SendorEmail END
							;			
							
							
					END IF;
		
	
		select COUNT(*) AS `totalcount` from tblAutoImportSetting as s
		inner join tblTrunk as t on s.TrunkID=t.TrunkID
		inner join tblAccount as a on a.AccountID=s.TypePKID
		inner join tblFileUploadTemplate as ut on ut.FileUploadTemplateID=s.ImportFileTempleteID
		where 
								  CASE 
								  		WHEN (p_TrunkID > 0 AND p_typePKID > 0 AND p_search <> '') THEN
										    s.TrunkID=p_TrunkID AND  s.TypePKID=p_typePKID AND ( p_search = ''  OR s.Subject LIKE REPLACE(p_search,'*', '%') )  AND s.CompanyID = p_CompanyID AND s.`Type`= 1				    
								  		WHEN (p_TrunkID > 0 AND p_typePKID > 0) THEN
										    s.TrunkID=p_TrunkID AND  s.TypePKID=p_typePKID AND s.CompanyID = p_CompanyID AND s.`Type`= 1				    
										WHEN (p_TrunkID > 0) THEN
										    s.TrunkID=p_TrunkID AND  s.CompanyID = p_CompanyID AND s.`Type`= 1
									   WHEN (p_typePKID > 0) THEN
										    s.TypePKID = p_typePKID AND  s.CompanyID = p_CompanyID AND s.`Type`= 1
										WHEN (p_search <> '') THEN			    				    
										    (  s.Subject LIKE CONCAT('%',p_search,'%')  OR SendorEmail LIKE CONCAT('%',p_search,'%') OR ut.Title LIKE CONCAT('%',p_search,'%') ) AND  s.CompanyID = p_CompanyID AND s.`Type`= 1				    				    
										ELSE						
											 s.CompanyID = p_CompanyID AND s.`Type`= 1
										
									END	
							;		
			
	END IF;
	
	
	
	IF (p_SettingType = 2 ) THEN  
		
		IF (p_isExport = 0) THEN
				
					
				select r.RateTableName,ut.Title,Subject,FileName,SendorEmail,r.RateTableId,ut.FileUploadTemplateID,AutoImportSettingID from tblAutoImportSetting as s
				inner join tblRateTable as r on s.TypePKID = r.RateTableId
				inner join tblFileUploadTemplate as ut on ut.FileUploadTemplateID=s.ImportFileTempleteID
				
				where 
					  CASE 
					  		WHEN (p_typePKID > 0 AND p_search <> '') THEN
							     s.TypePKID=p_typePKID AND ( p_search = ''  OR s.Subject LIKE REPLACE(p_search,'*', '%') )  AND s.CompanyID = p_CompanyID AND s.`Type`= 2				    
					  		WHEN (p_typePKID > 0) THEN
							     s.TypePKID=p_typePKID AND s.CompanyID = p_CompanyID AND s.`Type`= 2				    
							WHEN (p_search <> '') THEN

							    (  s.Subject LIKE CONCAT('%',p_search,'%')  OR SendorEmail LIKE CONCAT('%',p_search,'%') OR ut.Title LIKE CONCAT('%',p_search,'%') ) AND  s.CompanyID = p_CompanyID AND s.`Type`= 2				    				    
							ELSE						
								 s.CompanyID = p_CompanyID AND s.`Type`= 2
							
						END	
					ORDER BY
					  CASE WHEN p_lSortCol = 'RateTable' AND p_SortOrder = 'desc' THEN r.RateTableName END DESC,
					  CASE WHEN p_lSortCol = 'RateTable' THEN r.RateTableName END,
					  CASE WHEN p_lSortCol = 'Import File Template' AND p_SortOrder = 'desc' THEN ut.Title END DESC,
					  CASE WHEN p_lSortCol = 'Import File Template' THEN ut.Title END,
					  CASE WHEN p_lSortCol = 'Subject Match' AND p_SortOrder = 'desc' THEN Subject END DESC,
					  CASE WHEN p_lSortCol = 'Subject Match' THEN Subject END,
					  CASE WHEN p_lSortCol = 'Filename Match' AND p_SortOrder = 'desc' THEN FileName END DESC,
					  CASE WHEN p_lSortCol = 'Filename Match' THEN FileName END,	
					  CASE WHEN p_lSortCol = 'Sender Match' AND p_SortOrder = 'desc' THEN SendorEmail END DESC,
					  CASE WHEN p_lSortCol = 'Sender Match' THEN SendorEmail END
					  
				LIMIT p_RowspPage OFFSET v_OffSet_;
				
		ELSE
				
				
				select r.RateTableName,ut.Title,Subject,SendorEmail,FileName from tblAutoImportSetting as s
				inner join tblRateTable as r on s.TypePKID = r.RateTableId
				inner join tblFileUploadTemplate as ut on ut.FileUploadTemplateID=s.ImportFileTempleteID
				
				where 
					  CASE 
					  		WHEN (p_typePKID > 0 AND p_search <> '') THEN
							     s.TypePKID=p_typePKID AND ( p_search = ''  OR s.Subject LIKE REPLACE(p_search,'*', '%') )  AND s.CompanyID = p_CompanyID AND s.`Type`= 2				    
					  		WHEN (p_typePKID > 0) THEN
							     s.TypePKID=p_typePKID AND s.CompanyID = p_CompanyID AND s.`Type`= 2				    
							WHEN (p_search <> '') THEN

							    (  s.Subject LIKE CONCAT('%',p_search,'%')  OR SendorEmail LIKE CONCAT('%',p_search,'%') OR ut.Title LIKE CONCAT('%',p_search,'%') ) AND  s.CompanyID = p_CompanyID AND s.`Type`= 2				    				    
							ELSE						
								 s.CompanyID = p_CompanyID AND s.`Type`= 2
							
						END	
					ORDER BY
					  CASE WHEN p_lSortCol = 'RateTable' AND p_SortOrder = 'desc' THEN r.RateTableName END DESC,
					  CASE WHEN p_lSortCol = 'RateTable' THEN r.RateTableName END,
					  CASE WHEN p_lSortCol = 'Import File Template' AND p_SortOrder = 'desc' THEN ut.Title END DESC,
					  CASE WHEN p_lSortCol = 'Import File Template' THEN ut.Title END,
					  CASE WHEN p_lSortCol = 'Subject Match' AND p_SortOrder = 'desc' THEN Subject END DESC,
					  CASE WHEN p_lSortCol = 'Subject Match' THEN Subject END,
					  CASE WHEN p_lSortCol = 'Filename Match' AND p_SortOrder = 'desc' THEN FileName END DESC,
					  CASE WHEN p_lSortCol = 'Filename Match' THEN FileName END,	
					  CASE WHEN p_lSortCol = 'Sender Match' AND p_SortOrder = 'desc' THEN SendorEmail END DESC,
					  CASE WHEN p_lSortCol = 'Sender Match' THEN SendorEmail END
				;
				
		END IF;
		
	
		select COUNT(*) AS `totalcount` from tblAutoImportSetting as s
				inner join tblRateTable as r on s.TypePKID = r.RateTableId
				inner join tblFileUploadTemplate as ut on ut.FileUploadTemplateID=s.ImportFileTempleteID
				
				where 
					  CASE 
					  		WHEN (p_typePKID > 0 AND p_search <> '') THEN
							     s.TypePKID=p_typePKID AND ( p_search = ''  OR s.Subject LIKE REPLACE(p_search,'*', '%') )  AND s.CompanyID = p_CompanyID AND s.`Type`= 2				    
					  		WHEN (p_typePKID > 0) THEN
							     s.TypePKID=p_typePKID AND s.CompanyID = p_CompanyID AND s.`Type`= 2				    
							WHEN (p_search <> '') THEN
								(  s.Subject LIKE CONCAT('%',p_search,'%')  OR SendorEmail LIKE CONCAT('%',p_search,'%') OR ut.Title LIKE CONCAT('%',p_search,'%') ) AND  s.CompanyID = p_CompanyID AND s.`Type`= 2
							ELSE						
								 s.CompanyID = p_CompanyID AND s.`Type`= 2
							
						END	
				;
		

		
			
	END IF;

	
	
	
		
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getBillingAccounts` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getBillingAccounts`(
	IN `p_CompanyID` INT,
	IN `p_Today` DATE,
	IN `p_skip_accounts` TEXT,
	IN `p_singleinvoice_accounts` TEXT
)
BEGIN
   
--	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

IF (p_singleinvoice_accounts = 0)
THEN
	SELECT 
		DISTINCT
		tblAccount.AccountID, 
		tblAccountBilling.NextInvoiceDate,
		AccountName, 
		tblAccountBilling.ServiceID
	FROM tblAccount 
	LEFT JOIN tblAccountService 
		ON tblAccountService.AccountID = tblAccount.AccountID
	LEFT JOIN tblAccountBilling 
		ON tblAccountBilling.AccountID = tblAccount.AccountID
		AND (( tblAccountBilling.ServiceID = 0  ) OR ( tblAccountService.ServiceID > 0 AND tblAccountBilling.ServiceID = tblAccountService.ServiceID AND tblAccountService.Status = 1)  ) 
	WHERE tblAccount.CompanyId = p_CompanyID 
	AND tblAccount.Status = 1 
	AND AccountType = 1 
	AND Billing = 1	
	AND tblAccountBilling.NextInvoiceDate <= p_Today
	AND (tblAccountBilling.BillingCycleType IS NOT NULL AND tblAccountBilling.BillingCycleType <> 'manual') 
	AND FIND_IN_SET(tblAccount.AccountID,p_skip_accounts) = 0	
	ORDER BY tblAccount.AccountID ASC;
	
ELSE

	SELECT 
		DISTINCT
		tblAccount.AccountID, 
		tblAccountBilling.NextInvoiceDate,
		AccountName, 
		tblAccountBilling.ServiceID
	FROM tblAccount 
	LEFT JOIN tblAccountService 
		ON tblAccountService.AccountID = tblAccount.AccountID
	LEFT JOIN tblAccountBilling 
		ON tblAccountBilling.AccountID = tblAccount.AccountID
		AND (( tblAccountBilling.ServiceID = 0  ) OR ( tblAccountService.ServiceID > 0 AND tblAccountBilling.ServiceID = tblAccountService.ServiceID AND tblAccountService.Status = 1)  ) 
	WHERE tblAccount.CompanyId = p_CompanyID 
	AND tblAccount.Status = 1 
	AND AccountType = 1 
	AND Billing = 1	
	AND tblAccountBilling.NextInvoiceDate <= p_Today
	AND (tblAccountBilling.BillingCycleType IS NOT NULL AND tblAccountBilling.BillingCycleType <> 'manual') 
	AND FIND_IN_SET(tblAccount.AccountID,p_singleinvoice_accounts) != 0	
	AND FIND_IN_SET(tblAccount.AccountID,p_skip_accounts) = 0	
	ORDER BY tblAccount.AccountID ASC;

END IF;	

--	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
	
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getBillingClass` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getBillingClass`(IN `p_CompanyID` INT, IN `p_Name` VARCHAR(50), IN `p_PageNumber` INT, IN `p_RowspPage` INT, IN `p_lSortCol` VARCHAR(50), IN `p_SortOrder` VARCHAR(5), IN `p_isExport` INT)
BEGIN

	DECLARE v_OffSet_ int;
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

	IF p_isExport = 0
	THEN

		SELECT
			Name,
			UpdatedBy,
			updated_at,
			BillingClassID,
			(SELECT COUNT(*) FROM tblAccountBilling a WHERE a.BillingClassID =  tblBillingClass.BillingClassID) as Applied
		FROM tblBillingClass
		WHERE  CompanyID = p_CompanyID 
			AND (p_Name = '' OR Name LIKE REPLACE(p_Name, '*', '%'))
		ORDER BY
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'NameDESC') THEN Name
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'NameASC') THEN Name
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UpdatedByDESC') THEN UpdatedBy
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'UpdatedByASC') THEN UpdatedBy
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_atDESC') THEN updated_at
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_atASC') THEN updated_at
			END ASC
		LIMIT p_RowspPage OFFSET v_OffSet_;

		SELECT
			COUNT(BillingClassID) AS totalcount
		FROM tblBillingClass
		WHERE  CompanyID = p_CompanyID 
			AND (p_Name = '' OR Name LIKE REPLACE(p_Name, '*', '%'));

	END IF;

	IF p_isExport = 1
	THEN
	
		SELECT
			Name,
			UpdatedBy,
			updated_at
		FROM tblBillingClass
		WHERE  CompanyID = p_CompanyID 
			AND (p_Name = '' OR Name LIKE REPLACE(p_Name, '*', '%'));
	
	END IF;
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetBlockUnblockAccount` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetBlockUnblockAccount`(
	IN `p_CompanyID` INT,
	IN `p_CompanyGatewayID` INT

)
BEGIN

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	SELECT
		DISTINCT
		a.AccountID,
		a.Number,
		a.AccountName,
		(COALESCE(ab.BalanceAmount,0) - COALESCE(ab.PermanentCredit,0)) as Balance,
		IF((COALESCE(ab.BalanceAmount,0) - COALESCE(ab.PermanentCredit,0)) > 0 AND a.`Status` = 1 ,1,0) as BlockStatus,
		a.`Status`,
		a.BillingEmail,
		a.Blocked
	FROM tblAccountBalance ab 
	INNER JOIN tblAccount a 
		ON a.AccountID = ab.AccountID
	INNER JOIN telsomespainBilling.tblGatewayAccount ga
		ON ga.AccountID = a.AccountID
	WHERE a.CompanyId = p_CompanyID
	AND a.AccountType = 1
	AND ( p_CompanyGatewayID = 0 OR ga.CompanyGatewayID = p_CompanyGatewayID)
	ORDER BY BlockStatus,a.AccountID;
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetBlockUnblockVendor` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_GetBlockUnblockVendor`(
	IN `p_companyid` INT,
	IN `p_UserID` int ,
	IN `p_TrunkID` INT,
	IN `p_TimezonesID` INT,
	IN `p_CountryIDs` TEXT,
	IN `p_CountryCodes` TEXT,
	IN `p_isCountry` int ,
	IN `p_action` VARCHAR(10),
	IN `p_isAllCountry` int ,
	IN `p_criteria` INT
)
BEGIN

    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;



		IF p_isCountry = 0
	THEN
		DROP TEMPORARY TABLE IF EXISTS tmp_codes_;
	   CREATE TEMPORARY TABLE IF NOT EXISTS tmp_codes_(
				Code varchar(20),
			INDEX tmp_Code (`Code`)
		);
	END IF;
   		IF p_criteria = 0 AND p_isCountry = 0
		THEN
   		insert into tmp_codes_
		   SELECT  distinct tblRate.Code
            FROM    tblRate
           WHERE    tblRate.CompanyID = p_companyid  AND ( p_CountryCodes  = '' OR FIND_IN_SET(tblRate.Code,p_CountryCodes) != 0 );
        END IF;

        IF p_criteria = 1 AND  p_isCountry = 0
		THEN
   		insert into tmp_codes_
		   SELECT  distinct tblRate.Code
            FROM    tblRate
           WHERE    tblRate.CompanyID = p_companyid  AND ( p_CountryCodes  = '' OR Code LIKE REPLACE(p_CountryCodes,'*', '%') );
        END IF;

		IF p_criteria =2 AND p_isCountry = 0
		THEN

			insert into tmp_codes_
			SELECT  distinct tblRate.Code
            FROM    tblRate
           WHERE    tblRate.CompanyID = p_companyid
		   AND ( FIND_IN_SET(tblRate.CountryID,p_CountryIDs) != 0 );

		END IF;

		IF p_criteria =3 AND p_isCountry = 0
		THEN

			insert into tmp_codes_
			SELECT  distinct tblRate.Code
            FROM    tblRate
           WHERE    tblRate.CompanyID = p_companyid;

		END IF;

	if p_isCountry  = 0 AND p_action = 0
	Then
			SELECT SQL_CALC_FOUND_ROWS DISTINCT tblVendorRate.AccountId , tblAccount.AccountName
				from tblVendorRate
				inner join tblAccount on tblVendorRate.AccountId = tblAccount.AccountID
						and tblAccount.Status = 1
						and tblAccount.CompanyID = p_companyid
						AND tblAccount.IsVendor = 1
						and tblAccount.AccountType = 1
				inner join tblRate on tblVendorRate.RateId  = tblRate.RateId
					and tblVendorRate.TrunkID = p_TrunkID
					and tblVendorRate.TimezonesID = p_TimezonesID
				Inner join tmp_codes_ c on c.Code = tblRate.Code
				inner join tblVendorTrunk on tblVendorTrunk.CompanyID = p_companyid
					and tblVendorTrunk.AccountID =	tblVendorRate.AccountID
					and tblVendorTrunk.Status = 1
					and tblVendorTrunk.TrunkID = p_TrunkID
				LEFT OUTER JOIN tblVendorBlocking
					ON tblVendorRate.AccountId = tblVendorBlocking.AccountId
						AND tblVendorTrunk.TrunkID = tblVendorBlocking.TrunkID
						AND tblVendorRate.TimezonesID = tblVendorBlocking.TimezonesID
						AND tblRate.RateID = tblVendorBlocking.RateId
			WHERE tblVendorBlocking.VendorBlockingId IS NULL
			ORDER BY tblAccount.AccountName;

			SELECT FOUND_ROWS() as totalcount ;

	END IF;

	if p_isCountry = 0 AND p_action = 1

	Then
		select SQL_CALC_FOUND_ROWS DISTINCT tblVendorBlocking.AccountId, tblAccount.AccountName
			from tblVendorBlocking
			inner join tblAccount on tblVendorBlocking.AccountId = tblAccount.AccountID
								and tblAccount.Status = 1
								and tblAccount.CompanyID = p_companyid
								AND tblAccount.IsVendor = 1
								and tblAccount.AccountType = 1
			inner join tblRate on tblVendorBlocking.RateId  = tblRate.RateId
				and tblVendorBlocking.TrunkID = p_TrunkID
					and tblVendorBlocking.TimezonesID = p_TimezonesID
			Inner join tmp_codes_ c on c.Code = tblRate.Code
			inner join tblVendorTrunk on tblVendorTrunk.CompanyID = p_companyid
				and tblVendorTrunk.AccountID = tblVendorBlocking.AccountID
				and tblVendorTrunk.Status = 1
				and tblVendorTrunk.TrunkID = p_TrunkID
			inner join tblVendorRate on tblVendorRate.RateId = tblRate.RateId
				and tblVendorRate.AccountID = tblVendorBlocking.AccountID
				and tblVendorRate.TrunkID = p_TrunkID
				and tblVendorRate.TimezonesID = p_TimezonesID
		ORDER BY tblAccount.AccountName;

		SELECT FOUND_ROWS() as totalcount;

	END IF;



	if p_isCountry = 1 AND p_action = 0
	Then

		SELECT SQL_CALC_FOUND_ROWS DISTINCT  tblVendorRate.AccountId , tblAccount.AccountName
			from tblVendorRate
			inner join tblAccount on tblVendorRate.AccountId = tblAccount.AccountID
					and tblAccount.Status = 1
					and tblAccount.CompanyID = p_companyid
					AND tblAccount.IsVendor = 1
					and tblAccount.AccountType = 1
			inner join tblRate on tblVendorRate.RateId  = tblRate.RateId
				and  (
						(p_isAllCountry = 1 and p_isCountry = 1 and  tblRate.CountryID in  (SELECT CountryID FROM tblCountry) )
						OR
						(FIND_IN_SET(tblRate.CountryID,p_CountryIDs) != 0 )

					)
				and tblVendorRate.TrunkID = p_TrunkID
				and tblVendorRate.TimezonesID = p_TimezonesID
			inner join tblVendorTrunk on tblVendorTrunk.CompanyID = p_companyid
				and tblVendorTrunk.AccountID =	tblVendorRate.AccountID
				and tblVendorTrunk.Status = 1
				and tblVendorTrunk.TrunkID = p_TrunkID
			LEFT OUTER JOIN tblVendorBlocking
				ON tblVendorRate.AccountId = tblVendorBlocking.AccountId
					AND tblVendorTrunk.TrunkID = tblVendorBlocking.TrunkID
					AND tblVendorRate.TimezonesID = tblVendorBlocking.TimezonesID
					AND tblRate.CountryId = tblVendorBlocking.CountryId
		WHERE tblVendorBlocking.VendorBlockingId IS NULL
			ORDER BY tblAccount.AccountName;

			SELECT FOUND_ROWS() as totalcount;

	END IF;

	if p_isCountry = 1 AND p_action = 1

	Then
		select SQL_CALC_FOUND_ROWS DISTINCT tblVendorBlocking.AccountId , tblAccount.AccountName
			from tblVendorBlocking
				inner join tblAccount on tblVendorBlocking.AccountId = tblAccount.AccountID
								and tblAccount.Status = 1
								and tblAccount.CompanyID = p_companyid
								AND tblAccount.IsVendor = 1
								and tblAccount.AccountType = 1
			inner join tblRate on tblVendorBlocking.CountryId  = tblRate.CountryId
				and  (
						(p_isAllCountry = 1 and p_isCountry = 1 and tblRate.CountryID in(SELECT CountryID FROM tblCountry) )
						OR
						( FIND_IN_SET(tblRate.CountryID,p_CountryIDs) != 0 )

					)
 				and tblVendorBlocking.TrunkID = p_TrunkID
				and tblVendorBlocking.TimezonesID = p_TimezonesID
			inner join tblVendorTrunk on tblVendorTrunk.CompanyID = p_companyid
				and tblVendorTrunk.AccountID = tblVendorBlocking.AccountID
				and tblVendorTrunk.Status = 1
				and tblVendorTrunk.TrunkID = p_TrunkID
			inner join tblVendorRate on tblVendorRate.RateId = tblRate.RateId
				and tblVendorRate.AccountID = tblVendorBlocking.AccountID
				and tblVendorRate.TrunkID = p_TrunkID
				and tblVendorRate.TimezonesID = p_TimezonesID
			ORDER BY tblAccount.AccountName;

		SELECT FOUND_ROWS() as totalcount;

	END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetCodeDeck` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetCodeDeck`(IN `p_companyid` int, IN `p_codedeckid` int, IN `p_contryid` int, IN `p_code` varchar(50), IN `p_description` varchar(50), IN `p_PageNumber` int, IN `p_RowspPage` int, IN `p_lSortCol` VARCHAR(50), IN `p_SortOrder` VARCHAR(5), IN `p_isExport` int )
BEGIN

   DECLARE v_OffSet_ int;
   SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	           
	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
    

    IF p_isExport = 0
    THEN


        SELECT
            RateID,
            tblCountry.ISO2,
            tblCountry.Country,
            Code,
            Description,
            Interval1,
            IntervalN
        FROM tblRate
        LEFT JOIN tblCountry
            ON tblCountry.CountryID = tblRate.CountryID
        WHERE   (p_contryid = 0 OR tblCountry.CountryID = p_contryid)
            AND (p_code IS NULL OR Code LIKE REPLACE(p_code, '*', '%'))
            AND (p_description IS NULL OR Description LIKE REPLACE(p_description, '*', '%'))
            AND (CompanyID = p_companyid AND CodeDeckId = p_codedeckid)
        ORDER BY
            CASE
                WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeDESC') THEN Code
            END DESC,
            CASE
                WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeASC') THEN Code
            END ASC,
            CASE
                WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CountryDESC') THEN Country
            END DESC,
            CASE
                WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CountryASC') THEN Country
            END ASC,
            CASE
                WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionDESC') THEN Description
            END DESC,
            CASE
                WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionASC') THEN Description
            END ASC,
            CASE
                WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ISO2DESC') THEN ISO2
            END DESC,
            CASE
                WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ISO2ASC') THEN ISO2
            END ASC,
            CASE
                WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1DESC') THEN Interval1
            END DESC,
            CASE
                WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1ASC') THEN Interval1
            END ASC,
            CASE
                WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNDESC') THEN IntervalN
            END DESC,
            CASE
                WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNASC') THEN IntervalN
            END ASC
        LIMIT p_RowspPage OFFSET v_OffSet_;

        SELECT
            COUNT(RateID) AS totalcount
        FROM tblRate
        LEFT JOIN tblCountry
            ON tblCountry.CountryID = tblRate.CountryID
        WHERE   (p_contryid = 0 OR tblCountry.CountryID = p_contryid)
            AND (p_code IS NULL OR Code LIKE REPLACE(p_code, '*', '%'))
            AND (p_description IS NULL OR Description LIKE REPLACE(p_description, '*', '%'))
            AND (CompanyID = p_companyid AND CodeDeckId = p_codedeckid);

    END IF;

    IF p_isExport = 1
    THEN

        SELECT            
            tblCountry.Country,
            Code,
            tblCountry.ISO2 as 'ISO Code',
            Description,
            Interval1,
            IntervalN
        FROM tblRate
        LEFT JOIN tblCountry
            ON tblCountry.CountryID = tblRate.CountryID
        WHERE   (p_contryid  = 0 OR tblCountry.CountryID = p_contryid)
            AND (p_code IS NULL OR Code LIKE REPLACE(p_code, '*', '%'))
            AND (p_description IS NULL OR Description LIKE REPLACE(p_description, '*', '%'))
            AND (CompanyID = p_companyid AND CodeDeckId = p_codedeckid);

    END IF;
    IF p_isExport = 2
    THEN

        SELECT
	        RateID,
	         tblCountry.ISO2,
            tblCountry.Country,
            Code,
            Description,
            Interval1,
            IntervalN            
        FROM tblRate
        LEFT JOIN tblCountry
            ON tblCountry.CountryID = tblRate.CountryID
        WHERE   (p_contryid  = 0 OR tblCountry.CountryID = p_contryid)
            AND (p_code IS NULL OR Code LIKE REPLACE(p_code, '*', '%'))
            AND (p_description IS NULL OR Description LIKE REPLACE(p_description, '*', '%'))
            AND (CompanyID = p_companyid AND CodeDeckId = p_codedeckid);

    END IF;
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getContactTimeLine` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getContactTimeLine`(
	IN `p_ContactID` INT,
	IN `p_CompanyID` INT,
	IN `p_TicketType` INT,
	IN `p_GUID` VARCHAR(100),
	IN `p_Start` INT,
	IN `p_RowspPage` INT



)
BEGIN
DECLARE v_OffSet_ int;
DECLARE v_ActiveSupportDesk int;
SET v_OffSet_ = p_Start;
SET sql_mode = 'ALLOW_INVALID_DATES';
	
	DROP TEMPORARY TABLE IF EXISTS tmp_actvity_timeline_;
   CREATE TEMPORARY TABLE IF NOT EXISTS tmp_actvity_timeline_(
		`Timeline_type` int(11),		
		Emailfrom varchar(50),
		EmailTo varchar(50),
		EmailToName varchar(50),
		EmailSubject varchar(200),
		EmailMessage LONGTEXT,
		EmailCc varchar(500),
		EmailBcc varchar(500),
		EmailAttachments LONGTEXT,
		AccountEmailLogID int(11),
	    NoteID int(11),
		Note longtext,		
		TicketID int(11),
		TicketSubject varchar(200),
		TicketStatus varchar(100),
		RequestEmail varchar(100),
		TicketPriority varchar(100),
		TicketType varchar(100),
		TicketGroup varchar(100),
		TicketDescription LONGTEXT,		
		CreatedBy varchar(50),
		created_at datetime,
		updated_at datetime		
	);
	
		
	
	
	INSERT INTO tmp_actvity_timeline_
	select 2 as Timeline_type, Emailfrom, EmailTo,	
	case when concat(tu.FirstName,' ',tu.LastName) IS NULL or concat(tu.FirstName,' ',tu.LastName) = ''
            then ael.EmailTo
            else concat(tu.FirstName,' ',tu.LastName)
       end as EmailToName, 
	Subject,Message,Cc,Bcc,AttachmentPaths as EmailAttachments,AccountEmailLogID,0 as NoteID,'' as Note ,0 as TicketID, '' as 	TicketSubject,	'' as	TicketStatus,	'' as 	RequestEmail,	'' as 	TicketPriority,	'' as 	TicketType,	'' as 	TicketGroup,	'' as TicketDescription,ael.CreatedBy,ael.created_at, ael.updated_at 
	from `AccountEmailLog` ael
	left JOIN tblUser tu
		ON tu.EmailAddress = ael.EmailTo
	where 
	ael.ContactID = p_ContactID and
	ael.CompanyID = p_CompanyID and 
	ael.UserType=1 and
	ael.EmailParent=0 and
	
	
	ael.TicketID = 0
	order by ael.created_at desc;
	
	INSERT INTO tmp_actvity_timeline_
	select 3 as Timeline_type, '' as Emailfrom ,'' as EmailTo,'' as EmailToName,'' as EmailSubject,'' as Message,''as EmailCc,''as EmailBcc,''as EmailAttachments,0 as AccountEmailLogID,NoteID,Note,0 as TicketID, '' as 	TicketSubject,	'' as	TicketStatus,	'' as 	RequestEmail,	'' as 	TicketPriority,	'' as 	TicketType,	'' as 	TicketGroup,	'' as TicketDescription,created_by,created_at,updated_at 
	from `tblContactNote` where (`CompanyID` = p_CompanyID and `ContactID` = p_ContactID) order by created_at desc;
	

	IF p_TicketType=2 
	THEN
	INSERT INTO tmp_actvity_timeline_
	select 4 as Timeline_type, '' as Emailfrom ,'' as EmailTo,'' as EmailToName,'' as EmailSubject,'' as Message,''as EmailCc,''as EmailBcc,''as EmailAttachments,0 as AccountEmailLogID, 0 as NoteID,'' as Note,
	TAT.TicketID,	TAT.Subject as 	TicketSubject,	TAT.Status as	TicketStatus,	TAT.RequestEmail as 	RequestEmail,	TAT.Priority as 	TicketPriority,	TAT.`Type` as 	TicketType,	TAT.`Group` as 	TicketGroup,	TAT.`Description` as TicketDescription,created_by,ApiCreatedDate as created_at,ApiUpdateDate as updated_at from `tblHelpDeskTickets` TAT where (TAT.`CompanyID` = p_CompanyID and TAT.`ContactID` = p_ContactID and TAT.GUID = p_GUID);
	END IF;

	IF p_TicketType=1 
	THEN
	INSERT INTO tmp_actvity_timeline_
		select 4 as Timeline_type, '' as Emailfrom ,'' as EmailTo,'' as EmailToName,'' as EmailSubject,'' as Message,''as EmailCc,''as EmailBcc,''as EmailAttachments,0 as AccountEmailLogID, 0 as NoteID,'' as Note,
		TT.TicketID,TT.Subject as 	TicketSubject,	TFV.FieldValueAgent  as	TicketStatus,	TT.Requester as 	RequestEmail,TP.PriorityValue as TicketPriority,	TFVV.FieldValueAgent as 	TicketType,	TG.GroupName as TicketGroup,	TT.`Description` as TicketDescription,TT.created_by,TT.created_at,TT.updated_at 
	from 
		`tblTickets` TT
	LEFT JOIN tblTicketfieldsValues TFV
		ON TFV.ValuesID = TT.Status		
	LEFT JOIN tblTicketPriority TP
		ON TP.PriorityID = TT.Priority
	LEFT JOIN tblTicketGroups TG
		ON TG.GroupID = TT.`Group`
	LEFT JOIN tblTicketfieldsValues TFVV
		ON TFVV.ValuesID = TT.Type
	LEFT JOIN tblContact TC
		ON TC.Email = TT.Requester		
	where 			
		(TT.`CompanyID` = p_CompanyID and TC.`ContactID` = p_ContactID);	
	END IF;
	
	select * from tmp_actvity_timeline_ order by created_at desc LIMIT p_RowspPage OFFSET v_OffSet_ ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetCRMBoard` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetCRMBoard`(IN `p_CompanyID` INT, IN `p_Status` INT, IN `p_BoardName` VARCHAR(30), IN `p_BoardType` INT, IN `p_PageNumber` INT, IN `p_RowspPage` INT, IN `p_lSortCol` VARCHAR(30), IN `p_SortOrder` VARCHAR(10), IN `p_isExport` INT)
BEGIN

DECLARE v_OffSet_ int;

   SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
 
	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
	
	IF p_isExport = 0
	THEN
		SELECT BoardName, `Status`, CreatedBy, BoardID 
		FROM tblCRMBoards op 
		WHERE (op.CompanyID = p_CompanyID) 
			AND (op.BoardType = p_BoardType)
			AND ( p_Status = 2 OR op.`Status` = p_Status) 
			AND (p_BoardName = '' OR op.BoardName like Concat('%',p_BoardName,'%'))
			ORDER BY
				CASE
               WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'BoardNameASC') THEN op.BoardName
            END ASC,
				CASE
               WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'BoardNameDESC') THEN op.BoardName
            END DESC,
				CASE
               WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'StatusASC') THEN op.`Status`
            END ASC,
				CASE
               WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'StatusDESC') THEN op.`Status`
            END DESC,
				CASE
               WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CreatedByASC') THEN op.CreatedBy
            END ASC,
				CASE
               WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CreatedByDESC') THEN op.CreatedBy
            END DESC
				                     
		LIMIT p_RowspPage OFFSET v_OffSet_;
				
		SELECT COUNT(*) AS totalcount
		FROM tblCRMBoards op 
		WHERE (op.CompanyID = p_CompanyID) 
			AND (op.BoardType = p_BoardType)
			AND ( p_Status = 2 OR op.`Status` = p_Status)
			AND (p_BoardName ='' OR `BoardName` like Concat('%',p_BoardName,'%'));
	END IF;
	
	IF p_isExport = 1
	THEN
	SELECT BoardName, Status, CreatedBy, BoardID 
		FROM tblCRMBoards op 
		WHERE (op.CompanyID = p_CompanyID)
			AND (op.BoardType=p_BoardType) 
			AND ( p_Status = 2 OR op.`Status` = p_Status)
			AND (p_BoardName ='' OR `BoardName` like Concat('%',p_BoardName,'%'));
	END IF;
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetCRMBoardColumns` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetCRMBoardColumns`(IN `p_CompanyID` INT, IN `p_BoardID` INT)
BEGIN
SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
SELECT `BoardColumnName`, `Order`,`Height`,`Width`,`SetCompleted`,`BoardColumnID`
FROM `tblCRMBoardColumn` 
WHERE (`CompanyID` = p_CompanyID 
	AND `BoardID` = p_BoardID) 
ORDER BY `Order` ASC;
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetCrmDashboardForecast` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetCrmDashboardForecast`(IN `p_CompanyID` INT, IN `p_OwnerID` VARCHAR(500), IN `p_Status` INT, IN `p_CurrencyID` INT, IN `p_Start` DATE, IN `p_End` DATE)
BEGIN
	DECLARE v_CurrencyCode_ VARCHAR(50);
	DECLARE v_Round_ int;
	
	SELECT cr.Symbol INTO v_CurrencyCode_ from tblCurrency cr where cr.CurrencyId =p_CurrencyID;
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;
		
	 DROP TEMPORARY TABLE IF EXISTS tmp_Dashboard_Oppertunites_Forecast_;
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Dashboard_Oppertunites_Forecast_(
		   `Status` int,
		   `Worth` decimal(18,8),
			`Year` int,
			`Month` int,
		
			`AssignedUserText` varchar(100),
			`Opportunitescount`	int
	);
	  
		insert into tmp_Dashboard_Oppertunites_Forecast_
		SELECT 		
			   MAX(o.`Status`),
			   SUM(o.Worth),
			   YEAR(IFNULL(o.ExpectedClosing,now())) as Year,
			   MONTH(IFNULL(o.ExpectedClosing,now())) as Month,
				
			   CONCAT(tu.FirstName,' ',tu.LastName) as AssignedUserText,
			   COUNT(*) as Opportunitescount
		FROM tblOpportunity o
		INNER JOIN tblAccount ac on ac.AccountID = o.AccountID
					AND ac.`Status` = 1
		INNER join tblUser tu on o.UserID = tu.UserID
						AND tu.`Status` = 1						
		WHERE
					 o.CompanyID = p_CompanyID
					AND o.OpportunityClosed=0
					AND (p_OwnerID = '' OR find_in_set(o.`UserID`,p_OwnerID))
					AND (p_Status = '' OR o.`Status` = p_Status)		
					AND (IFNULL(o.ExpectedClosing,now()) between p_Start and p_End)
					AND (p_CurrencyID = '' OR ( p_CurrencyID != ''  and ac.CurrencyId = p_CurrencyID))
		GROUP BY 
					YEAR(IFNULL(o.ExpectedClosing,now()))
					,MONTH(IFNULL(o.ExpectedClosing,now()))			
					,CONCAT(tu.FirstName,' ',tu.LastName);
			
		SELECT	ROUND(td.Worth,v_Round_) as TotalWorth,
				v_CurrencyCode_ as CurrencyCode,			
				CONCAT(CONCAT(case when td.Month <10 then concat('0',td.Month) else td.Month End, '/'), td.Year) AS MonthName ,
				td.`Status` as `Status`,
				td.AssignedUserText,
				v_Round_ as round_number,
				Opportunitescount	
	    FROM tmp_Dashboard_Oppertunites_Forecast_ td;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetCrmDashboardPipeLine` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetCrmDashboardPipeLine`(IN `p_CompanyID` INT, IN `p_OwnerID` VARCHAR(500), IN `p_CurrencyID` INT)
BEGIN
	DECLARE v_CurrencyCode_ VARCHAR(50);
	DECLARE v_Round_ int;
	
	SELECT cr.Symbol INTO v_CurrencyCode_ from tblCurrency cr where cr.CurrencyId =p_CurrencyID;
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;
		
 DROP TEMPORARY TABLE IF EXISTS tmp_Dashboard_Oppertunites_;
CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Dashboard_Oppertunites_(
 	   Worth decimal(18,8),
	   AssignedUserText varchar(100)
		
);  

insert into tmp_Dashboard_Oppertunites_
SELECT 		
 	   o.Worth,
	   concat(tu.FirstName,' ',tu.LastName) as AssignedUserText
FROM tblOpportunity o
Inner JOIN tblAccount ac on ac.AccountID = o.AccountID
inner join tblUser tu on o.UserID = tu.UserID
where
			ac.`Status` = 1
			AND (p_CurrencyID = '' OR ( p_CurrencyID !=''  and ac.CurrencyId = p_CurrencyID))
		   AND o.CompanyID = p_CompanyID
		   AND o.OpportunityClosed =0
		   and o.`Status` = 1
			AND (p_OwnerID = '' OR find_in_set(o.`UserID`,p_OwnerID));

 SELECT			           
			ROUND(sum(Worth),v_Round_) as TotalWorth,
			v_CurrencyCode_,
			v_Round_ as RoundVal,
			AssignedUserText,			
			count(*) as TotalOpportunites	
         FROM tmp_Dashboard_Oppertunites_ 
         group by `AssignedUserText` asc;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetCrmDashboardSales` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetCrmDashboardSales`(IN `p_CompanyID` INT, IN `p_OwnerID` VARCHAR(500), IN `p_Status` VARCHAR(50), IN `p_CurrencyID` INT, IN `p_Start` DATE, IN `p_End` DATE)
BEGIN
	DECLARE v_CurrencyCode_ VARCHAR(50);
	DECLARE v_Round_ int;
	
	SELECT cr.Symbol INTO v_CurrencyCode_ from tblCurrency cr where cr.CurrencyId =p_CurrencyID;
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;
		
	 DROP TEMPORARY TABLE IF EXISTS tmp_Dashboard_Oppertunites_Sales_;
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Dashboard_Oppertunites_Sales_(
		   `Status` int,
		   `Worth` decimal(18,8),
			`Year` int,
			`Month` int,		
			`AssignedUserText` varchar(100),
			`Opportunitescount`	int
	);
	  
			insert into tmp_Dashboard_Oppertunites_Sales_
	SELECT 		
			MAX(o.`Status`),
			SUM(o.Worth), 	   
			YEAR(o.ClosingDate) as Year,
			MONTH(o.ClosingDate) as Month,			   
			concat(tu.FirstName,' ',tu.LastName) as AssignedUserText,
			count(*) as Opportunitescount
	FROM tblOpportunity o
	INNER JOIN tblAccount ac on ac.AccountID = o.AccountID
			AND ac.`Status` = 1
	INNER join tblUser tu on o.UserID = tu.UserID
			and tu.`Status` = 1 					 
	WHERE
				o.CompanyID = p_CompanyID
			
				AND (p_OwnerID = '' OR find_in_set(o.`UserID`,p_OwnerID))
				AND (p_Status = '' OR find_in_set(o.`Status`,p_Status))
				AND (ClosingDate between p_Start and p_End)
				AND (p_CurrencyID = '' OR ( p_CurrencyID != ''  and ac.CurrencyId = p_CurrencyID))	
	GROUP BY 
			YEAR(o.ClosingDate) 
			,MONTH(o.ClosingDate)
			,CONCAT(tu.FirstName,' ',tu.LastName);
			
	 SELECT	ROUND(td.Worth,v_Round_) as TotalWorth,
				v_CurrencyCode_,
				CONCAT(CONCAT(case when td.Month <10 then concat('0',td.Month) else td.Month End, '/'), td.Year) AS MonthName ,
				td.`Status` as `Status`,
				td.AssignedUserText,
				v_Round_	 as round_number,
				Opportunitescount		
	 FROM tmp_Dashboard_Oppertunites_Sales_  td;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetCrmDashboardSalesManager` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetCrmDashboardSalesManager`(
	IN `p_CompanyID` INT,
	IN `p_OwnerID` VARCHAR(500),
	IN `p_CurrencyID` INT,
	IN `p_ListType` VARCHAR(50),
	IN `p_Start` DATETIME,
	IN `p_End` DATETIME
)
BEGIN
	DECLARE v_CurrencyCode_ VARCHAR(50);
	DECLARE v_Round_ INT;

	SELECT cr.Symbol INTO v_CurrencyCode_ from tblCurrency cr where cr.CurrencyId =p_CurrencyID;
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;

	DROP TEMPORARY TABLE IF EXISTS tmp_Dashboard_invoices_;
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Dashboard_invoices_(
		AssignedUserText VARCHAR(100),
		AssignedUserID INT,
		Revenue decimal(18,8),
		`Year` INT,
		`Month` INT,
		`Week` INT
	);

	CALL telsomespainReport.fnGetCRMUnBilledData(p_CompanyID,p_OwnerID,p_CurrencyID,p_ListType,p_Start,p_End);

	INSERT INTO tmp_Dashboard_invoices_
	SELECT
		CONCAT(tu.FirstName,' ',tu.LastName) AS `AssignedUserText`,
		 tu.UserID AS  AssignedUserID,
		sum(`inv`.`GrandTotal`) AS `Revenue`,
		YEAR(inv.IssueDate) AS Year,
		MONTH(inv.IssueDate) AS Month,
		WEEK(inv.IssueDate)	 AS `Week`
	FROM telsomespainBilling.tblInvoice inv
	Inner JOIN tblAccount ac 
		ON ac.AccountID = inv.AccountID 
	INNER JOIN tblUser tu 
		ON tu.UserID = ac.Owner
	WHERE
		ac.`Status` = 1
	AND tu.`Status` = 1 
	AND (p_CurrencyID = '' OR ( p_CurrencyID !=''  AND ac.CurrencyId = p_CurrencyID))
	AND ac.CompanyID = p_CompanyID
	AND (p_OwnerID = '' OR   FIND_IN_SET(tu.UserID,p_OwnerID))
	AND `inv`.`InvoiceType` = 1
	AND `inv`.GrandTotal != 0
	AND (inv.IssueDate BETWEEN p_Start AND p_End)
	GROUP BY
		YEAR(inv.IssueDate) 
		,MONTH(inv.IssueDate)
		,WEEK(inv.IssueDate)
		,CONCAT(tu.FirstName,' ',tu.LastName)
		,tu.UserID;

	IF p_ListType = 'Monthly'
	THEN

		SELECT
			td.AssignedUserText AS AssignedUserText,
			td.AssignedUserID AS AssignedUserID,
			ROUND(sum(td.Revenue),v_Round_) AS Revenue,
			v_CurrencyCode_,
			CONCAT(CONCAT(case when td.Month <10 then concat('0',td.Month) else td.Month End, '/'), td.Year) AS MonthName,
			v_Round_ AS round_number
		FROM tmp_Dashboard_invoices_  td
		GROUP BY 
			td.Month,
			td.Year,
			td.AssignedUserID,
			td.AssignedUserText;

	END IF;

	IF p_ListType = 'Weekly'
	THEN
		SELECT
			td.AssignedUserText AS AssignedUserText,
			td.AssignedUserID,
			ROUND(sum(td.Revenue),v_Round_) AS Revenue,
			v_CurrencyCode_,
			CONCAT(td.`Week`,'-',MAX( td.Year)) AS `Week`,
			MAX( td.Year) AS `Year`,
			td.`Week` AS `Weekday`,
			v_Round_ AS round_number
		FROM  tmp_Dashboard_invoices_  td 
		GROUP BY
			td.`Week`
			,td.AssignedUserText
			,td.AssignedUserID
		ORDER BY
			`Year`,
			`Weekday` ASC;
	END IF;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetCrmDashboardSalesUser` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetCrmDashboardSalesUser`(
	IN `p_CompanyID` INT,
	IN `p_OwnerID` VARCHAR(500),
	IN `p_CurrencyID` INT,
	IN `p_ListType` VARCHAR(50),
	IN `p_Start` DATETIME,
	IN `p_End` VARCHAR(50),
	IN `p_WeekOrMonth` INT,
	IN `p_Year` INT
)
BEGIN
	DECLARE v_CurrencyCode_ VARCHAR(50);
	DECLARE v_Round_ int;

	SELECT cr.Symbol INTO v_CurrencyCode_ from tblCurrency cr where cr.CurrencyId =p_CurrencyID;
	SELECT fnGetRoundingPoint(p_CompanyID) INTO v_Round_;
	
	DROP TEMPORARY TABLE IF EXISTS tmp_Dashboard_invoices_;
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Dashboard_invoices_(
		AssignedUserText VARCHAR(100),
		AssignedUserID INT,
		Revenue decimal(18,8),
		`Year` INT,
		`Month` INT,
		`Week` INT
	);

	DROP TEMPORARY TABLE IF EXISTS tmp_Dashboard_user_invoices_;
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Dashboard_user_invoices_(
		AssignedUserText varchar(100),
		Revenue decimal(18,8)
	);

	CALL telsomespainReport.fnGetCRMUnBilledDataByAccount(p_CompanyID,p_OwnerID,p_CurrencyID,p_ListType,p_Start,p_End,p_WeekOrMonth,p_Year);

	INSERT INTO tmp_Dashboard_user_invoices_
	SELECT
		ac.AccountName  AS `AssignedUserText`,
		SUM(`inv`.`GrandTotal`) AS `Revenue`
	FROM telsomespainBilling.tblInvoice inv
	INNER JOIN  tblAccount ac 
		ON ac.AccountID = inv.AccountID
	INNER JOIN tblUser tu 
		ON tu.UserID = ac.Owner
	WHERE
		ac.`Status` = 1
	AND tu.`Status` = 1
	AND (p_CurrencyID = '' OR ( p_CurrencyID !=''  AND ac.CurrencyId = p_CurrencyID))
	AND ac.CompanyID = p_CompanyID
	AND (p_OwnerID = '' OR   FIND_IN_SET(tu.UserID,p_OwnerID))
	AND `inv`.`InvoiceType` = 1
	AND (inv.IssueDate BETWEEN p_Start AND p_End)
	AND (( p_ListType = 'Weekly' AND WEEK(inv.IssueDate) = p_WeekOrMonth AND YEAR(inv.IssueDate) = p_Year) OR ( p_ListType = 'Monthly' AND MONTH(inv.IssueDate) = p_WeekOrMonth AND YEAR(inv.IssueDate) = p_Year))
	GROUP BY
		ac.AccountName;

	SELECT
		td.AssignedUserText,
		ROUND(SUM(td.Revenue),v_Round_) AS Revenue,
		v_CurrencyCode_ AS CurrencyCode,
		v_Round_ AS round_number
	FROM  tmp_Dashboard_user_invoices_  td
	GROUP BY AssignedUserText;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetCronJob` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetCronJob`(IN `p_companyid` INT, IN `p_Status` INT, IN `p_PageNumber` INT, IN `p_RowspPage` INT, IN `p_lSortCol` VARCHAR(50), IN `p_SortOrder` VARCHAR(5), IN `p_isExport` INT)
BEGIN

   DECLARE v_OffSet_ int;
   SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
          
	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

    IF p_isExport = 0
    THEN
          
            SELECT
				tblCronJob.JobTitle,
                tblCronJobCommand.Title,
                tblCronJob.Status,
                tblCronJob.CronJobID,
                tblCronJob.CronJobCommandID,
                tblCronJob.Settings
            FROM tblCronJob
            INNER JOIN tblCronJobCommand
                ON tblCronJobCommand.CronJobCommandID = tblCronJob.CronJobCommandID
            WHERE tblCronJob.CompanyID = p_companyid
            AND (p_Status =2 OR tblCronJob.`Status`=p_Status)
            ORDER BY
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TitleDESC') THEN tblCronJobCommand.Title
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TitleASC') THEN tblCronJobCommand.Title
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'StatusDESC') THEN tblCronJob.Status
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'StatusASC') THEN tblCronJob.Status
                END ASC,
				CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'JobTitleDESC') THEN tblCronJob.JobTitle
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'JobTitleASC') THEN tblCronJob.JobTitle
                END ASC
            LIMIT p_RowspPage OFFSET v_OffSet_;

        SELECT
            COUNT(tblCronJob.CronJobID) as totalcount
        FROM tblCronJob
            INNER JOIN tblCronJobCommand
                ON tblCronJobCommand.CronJobCommandID = tblCronJob.CronJobCommandID
            WHERE tblCronJob.CompanyID = p_companyid
            AND (p_Status =2 OR tblCronJob.`Status`=p_Status);
    END IF;

    IF p_isExport = 1
    THEN
        SELECT
			tblCronJob.JobTitle,
            tblCronJobCommand.Title,
            tblCronJob.Status
        FROM tblCronJob
        INNER JOIN tblCronJobCommand
            ON tblCronJobCommand.CronJobCommandID = tblCronJob.CronJobCommandID
        WHERE tblCronJob.CompanyID = p_companyid
		  AND (p_Status =2 OR tblCronJob.`Status`=p_Status);
    END IF;
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetCronJobHistory` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetCronJobHistory`(
	IN `p_CronJobID` INT,
	IN `p_StartDate` DATETIME,
	IN `p_EndDate` DATETIME,
	IN `p_SearchText` VARCHAR(50),
	IN `p_Status` VARCHAR(50),
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT
)
BEGIN

   DECLARE v_OffSet_ int;
   SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;


	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

    IF p_isExport = 0
    THEN
            SELECT
                tblCronJobCommand.Title,
                tblCronJobLog.CronJobStatus,
                tblCronJobLog.Message,
                tblCronJobLog.created_at
            FROM tblCronJob
            INNER JOIN tblCronJobLog
                ON tblCronJob.CronJobID = tblCronJobLog.CronJobID
                AND tblCronJobLog.CronJobID = p_CronJobID
                AND (p_Status = '' OR tblCronJobLog.CronJobStatus = p_Status)
                AND tblCronJobLog.created_at between p_StartDate and p_EndDate
                AND (p_SearchText='' OR tblCronJobLog.Message like Concat('%',p_SearchText,'%'))
            INNER JOIN tblCronJobCommand
                ON tblCronJobCommand.CronJobCommandID = tblCronJob.CronJobCommandID
            ORDER BY
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TitleDESC') THEN tblCronJobCommand.Title
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TitleASC') THEN tblCronJobCommand.Title
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CronJobStatusDESC') THEN tblCronJobLog.CronJobStatus
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CronJobStatusASC') THEN tblCronJobLog.CronJobStatus
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MessageDESC') THEN tblCronJobLog.Message
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'MessageASC') THEN tblCronJobLog.Message
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atDESC') THEN tblCronJobLog.created_at
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atASC') THEN tblCronJobLog.created_at
                END ASC
           LIMIT p_RowspPage OFFSET v_OffSet_;

        SELECT
            COUNT(tblCronJobLog.CronJobID) as totalcount
        FROM tblCronJob
            INNER JOIN tblCronJobLog
                ON tblCronJob.CronJobID = tblCronJobLog.CronJobID
                AND tblCronJobLog.CronJobID = p_CronJobID
                AND (p_Status = '' OR tblCronJobLog.CronJobStatus = p_Status)
                AND tblCronJobLog.created_at between p_StartDate and p_EndDate
                AND (p_SearchText='' OR tblCronJobLog.Message like Concat('%',p_SearchText,'%'))
            INNER JOIN tblCronJobCommand
                ON tblCronJobCommand.CronJobCommandID = tblCronJob.CronJobCommandID;
    END IF;

    IF p_isExport = 1
    THEN
        SELECT
            tblCronJobCommand.Title,
            tblCronJobLog.CronJobStatus,
            tblCronJobLog.Message,
            tblCronJobLog.created_at
        FROM tblCronJob
        INNER JOIN tblCronJobLog
                ON tblCronJob.CronJobID = tblCronJobLog.CronJobID
                AND tblCronJobLog.CronJobID = p_CronJobID
                AND (p_Status = '' OR tblCronJobLog.CronJobStatus = p_Status)
                AND tblCronJobLog.created_at between p_StartDate and p_EndDate
                AND (p_SearchText='' OR tblCronJobLog.Message like Concat('%',p_SearchText,'%'))
        INNER JOIN tblCronJobCommand
            ON tblCronJobCommand.CronJobCommandID = tblCronJob.CronJobCommandID;
    END IF;
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetCronJobSetting` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetCronJobSetting`(IN `p_CronJobID` INT)
BEGIN

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	select Settings from tblCronJob where CronJobID=p_CronJobID;
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
	
	
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getCustomerCodeRate` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getCustomerCodeRate`(
	IN `p_AccountID` INT,
	IN `p_trunkID` INT,
	IN `p_RateCDR` INT,
	IN `p_RateMethod` VARCHAR(50),
	IN `p_SpecifyRate` DECIMAL(18,6),
	IN `p_RateTableID` INT
)
BEGIN
	DECLARE v_codedeckid_ INT;
	DECLARE v_ratetableid_ INT;
	DECLARE v_CompanyID_ INT;

	IF p_RateTableID > 0
	THEN

		SELECT
			CodeDeckId,
			RateTableId
		INTO
			v_codedeckid_,
			v_ratetableid_
		FROM tblRateTable
		WHERE RateTableId = p_RateTableID;

	ELSE

		SELECT
			CodeDeckId,
			RateTableID
		INTO
			v_codedeckid_,
			v_ratetableid_
		FROM tblCustomerTrunk
		WHERE tblCustomerTrunk.TrunkID = p_trunkID
		AND tblCustomerTrunk.AccountID = p_AccountID
		AND tblCustomerTrunk.Status = 1;

	END IF;



	IF p_RateCDR = 0
	THEN

		DROP TEMPORARY TABLE IF EXISTS tmp_codes_;
		CREATE TEMPORARY TABLE tmp_codes_ (
			RateID INT,
			Code VARCHAR(50),
			INDEX tmp_codes_RateID (`RateID`),
			INDEX tmp_codes_Code (`Code`)
		);
		DROP TEMPORARY TABLE IF EXISTS tmp_codes2_;
		CREATE TEMPORARY TABLE tmp_codes2_ (
			RateID INT,
			Code VARCHAR(50),
			INDEX tmp_codes2_RateID (`RateID`),
			INDEX tmp_codes2_Code (`Code`)
		);

		INSERT INTO tmp_codes_
		SELECT
		DISTINCT
			tblRate.RateID,
			tblRate.Code
		FROM tblRate
		INNER JOIN tblCustomerRate
		ON tblCustomerRate.RateID = tblRate.RateID
		WHERE
			 tblRate.CodeDeckId = v_codedeckid_
		AND CustomerID = p_AccountID
		AND tblCustomerRate.TrunkID = p_trunkID
		AND tblCustomerRate.EffectiveDate <= NOW();

		INSERT INTO tmp_codes2_
		SELECT * FROM tmp_codes_;

		INSERT INTO tmp_codes_
		SELECT
			DISTINCT
			tblRate.RateID,
			tblRate.Code
		FROM tblRate
		INNER JOIN tblRateTableRate
			ON tblRateTableRate.RateID = tblRate.RateID
		LEFT JOIN  tmp_codes2_ c ON c.RateID = tblRate.RateID
		WHERE
			 tblRate.CodeDeckId = v_codedeckid_
		AND RateTableID = v_ratetableid_
		AND c.RateID IS NULL
		AND tblRateTableRate.EffectiveDate <= NOW();

	END IF;

	IF p_RateCDR = 1
	THEN

		DROP TEMPORARY TABLE IF EXISTS tmp_codes_;
		CREATE TEMPORARY TABLE tmp_codes_ (
			RateID INT,
			Code VARCHAR(50),
			Rate Decimal(18,6),
			ConnectionFee Decimal(18,6),
			Interval1 INT,
			IntervalN INT,
			INDEX tmp_codes_RateID (`RateID`),
			INDEX tmp_codes_Code (`Code`)
		);
		DROP TEMPORARY TABLE IF EXISTS tmp_codes2_;
		CREATE TEMPORARY TABLE tmp_codes2_ (
			RateID INT,
			Code VARCHAR(50),
			Rate Decimal(18,6),
			ConnectionFee Decimal(18,6),
			Interval1 INT,
			IntervalN INT,
			INDEX tmp_codes2_RateID (`RateID`),
			INDEX tmp_codes2_Code (`Code`)
		);

		INSERT INTO tmp_codes_
		SELECT
		DISTINCT
			tblRate.RateID,
			tblRate.Code,
			tblCustomerRate.Rate,
			tblCustomerRate.ConnectionFee,
			tblCustomerRate.Interval1,
			tblCustomerRate.IntervalN
		FROM tblRate
		INNER JOIN tblCustomerRate
		ON tblCustomerRate.RateID = tblRate.RateID
		WHERE
			 tblRate.CodeDeckId = v_codedeckid_
		AND CustomerID = p_AccountID
		AND tblCustomerRate.TrunkID = p_trunkID
		AND tblCustomerRate.EffectiveDate <= NOW();

		INSERT INTO tmp_codes2_
		SELECT * FROM tmp_codes_;

		INSERT INTO tmp_codes_
		SELECT
			DISTINCT
			tblRate.RateID,
			tblRate.Code,
			tblRateTableRate.Rate,
			tblRateTableRate.ConnectionFee,
			tblRateTableRate.Interval1,
			tblRateTableRate.IntervalN
		FROM tblRate
		INNER JOIN tblRateTableRate
			ON tblRateTableRate.RateID = tblRate.RateID
		LEFT JOIN  tmp_codes2_ c ON c.RateID = tblRate.RateID
		WHERE
			 tblRate.CodeDeckId = v_codedeckid_
		AND RateTableID = v_ratetableid_
		AND c.RateID IS NULL
		AND tblRateTableRate.EffectiveDate <= NOW();

		
		IF p_RateMethod = 'SpecifyRate'
		THEN


			IF (SELECT COUNT(*) FROM tmp_codes_) = 0
			THEN

				SET v_CompanyID_ = (SELECT CompanyId FROM tblAccount WHERE AccountID = p_AccountID);
				INSERT INTO tmp_codes_
				SELECT
					DISTINCT
					tblRate.RateID,
					tblRate.Code,
					p_SpecifyRate,
					0,
					IFNULL(tblRate.Interval1,1),
					IFNULL(tblRate.IntervalN,1)
				FROM tblRate
				INNER JOIN tblCodeDeck
					ON tblCodeDeck.CodeDeckId = tblRate.CodeDeckId
				WHERE tblCodeDeck.CompanyId = v_CompanyID_
				AND tblCodeDeck.DefaultCodedeck = 1 ;

			END IF;

			UPDATE tmp_codes_ SET Rate=p_SpecifyRate;

		END IF;

	END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getCustomerInboundRate` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getCustomerInboundRate`(
	IN `p_AccountID` INT,
	IN `p_RateCDR` INT,
	IN `p_RateMethod` VARCHAR(50),
	IN `p_SpecifyRate` DECIMAL(18,6),
	IN `p_CLD` VARCHAR(500),
	IN `p_InboundTableID` INT
)
BEGIN

	DECLARE v_inboundratetableid_ INT;
	DECLARE v_CompanyID_ INT;

	IF p_CLD != ''
	THEN

		SELECT
			RateTableID INTO v_inboundratetableid_
		FROM tblCLIRateTable
		WHERE AccountID = p_AccountID AND CLI = p_CLD;

	ELSEIF p_InboundTableID > 0
	THEN

		SET v_inboundratetableid_ = p_InboundTableID;

	ELSE

		SELECT
			InboudRateTableID INTO v_inboundratetableid_
		FROM tblAccount
		WHERE AccountID = p_AccountID;

	END IF;

	IF p_RateCDR = 1
	THEN

		DROP TEMPORARY TABLE IF EXISTS tmp_inboundcodes_;
		CREATE TEMPORARY TABLE tmp_inboundcodes_ (
			RateID INT,
			Code VARCHAR(50),
			Rate Decimal(18,6),
			ConnectionFee Decimal(18,6),
			Interval1 INT,
			IntervalN INT,
			INDEX tmp_inboundcodes_RateID (`RateID`),
			INDEX tmp_inboundcodes_Code (`Code`)
		);
		INSERT INTO tmp_inboundcodes_
		SELECT
			DISTINCT
			tblRate.RateID,
			tblRate.Code,
			tblRateTableRate.Rate,
			tblRateTableRate.ConnectionFee,
			tblRateTableRate.Interval1,
			tblRateTableRate.IntervalN
		FROM tblRate
		INNER JOIN tblRateTableRate
			ON tblRateTableRate.RateID = tblRate.RateID
		WHERE RateTableID = v_inboundratetableid_
		AND tblRateTableRate.EffectiveDate <= NOW();

		
		IF p_RateMethod = 'SpecifyRate'
		THEN

			IF (SELECT COUNT(*) FROM tmp_inboundcodes_) = 0
			THEN

				SET v_CompanyID_ = (SELECT CompanyId FROM tblAccount WHERE AccountID = p_AccountID);
				INSERT INTO tmp_inboundcodes_
				SELECT
					DISTINCT
					tblRate.RateID,
					tblRate.Code,
					p_SpecifyRate,
					0,
					IFNULL(tblRate.Interval1,1),
					IFNULL(tblRate.IntervalN,1)
				FROM tblRate
				INNER JOIN tblCodeDeck
					ON tblCodeDeck.CodeDeckId = tblRate.CodeDeckId
				WHERE tblCodeDeck.CompanyId = v_CompanyID_
				AND tblCodeDeck.DefaultCodedeck = 1 ;

			END IF;

			UPDATE tmp_inboundcodes_ SET Rate=p_SpecifyRate;

		END IF;

	END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetCustomerRate` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_GetCustomerRate`(
	IN `p_companyid` INT,
	IN `p_AccountID` INT,
	IN `p_trunkID` INT,
	IN `p_TimezonesID` INT,
	IN `p_contryID` INT,
	IN `p_code` VARCHAR(50),
	IN `p_description` VARCHAR(50),
	IN `p_Effective` VARCHAR(50),
	IN `p_CustomDate` DATE,
	IN `p_effectedRates` INT,
	IN `p_RoutinePlan` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT
)
ThisSP:BEGIN
   DECLARE v_codedeckid_ INT;
   DECLARE v_ratetableid_ INT;
   DECLARE v_RateTableAssignDate_ DATETIME;
   DECLARE v_NewA2ZAssign_ INT;
   DECLARE v_OffSet_ int;
   DECLARE v_IncludePrefix_ INT;
   DECLARE v_Prefix_ VARCHAR(50);
   DECLARE v_RatePrefix_ VARCHAR(50);
   DECLARE v_AreaPrefix_ VARCHAR(50);

   -- set custome date = current date if custom date is past date
   IF(p_CustomDate < DATE(NOW()))
	THEN
		SET p_CustomDate=DATE(NOW());
	END IF;

   SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
   SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

    SELECT
        CodeDeckId,
        RateTableID,
        RateTableAssignDate,IncludePrefix INTO v_codedeckid_, v_ratetableid_, v_RateTableAssignDate_,v_IncludePrefix_
    FROM tblCustomerTrunk
    WHERE CompanyID = p_companyid
    AND tblCustomerTrunk.TrunkID = p_trunkID
    AND tblCustomerTrunk.AccountID = p_AccountID
    AND tblCustomerTrunk.Status = 1;

    SELECT
        Prefix,RatePrefix,AreaPrefix INTO v_Prefix_,v_RatePrefix_,v_AreaPrefix_
    FROM tblTrunk
    WHERE CompanyID = p_companyid
    AND tblTrunk.TrunkID = p_trunkID
    AND tblTrunk.Status = 1;



    DROP TEMPORARY TABLE IF EXISTS tmp_CustomerRates_;
    CREATE TEMPORARY TABLE tmp_CustomerRates_ (
        RateID INT,
        Interval1 INT,
        IntervalN  INT,
        Rate DECIMAL(18, 6),
        RateN DECIMAL(18, 6),
        ConnectionFee DECIMAL(18, 6),
        EffectiveDate DATE,
        EndDate DATE,
        LastModifiedDate DATETIME,
        LastModifiedBy VARCHAR(50),
        CustomerRateId INT,
        RateTableRateID INT,
        TrunkID INT,
        TimezonesID INT,
        RoutinePlan INT,
        INDEX tmp_CustomerRates__RateID (`RateID`),
        INDEX tmp_CustomerRates__TrunkID (`TrunkID`),
        INDEX tmp_CustomerRates__EffectiveDate (`EffectiveDate`)
    );
    DROP TEMPORARY TABLE IF EXISTS tmp_RateTableRate_;
    CREATE TEMPORARY TABLE tmp_RateTableRate_ (
        RateID INT,
        Interval1 INT,
        IntervalN INT,
        Rate DECIMAL(18, 6),
        RateN DECIMAL(18, 6),
        ConnectionFee DECIMAL(18, 6),
        EffectiveDate DATE,
        EndDate DATE,
        LastModifiedDate DATETIME,
        LastModifiedBy VARCHAR(50),
        CustomerRateId INT,
        RateTableRateID INT,
        TrunkID INT,
        TimezonesID INT,
        INDEX tmp_RateTableRate__RateID (`RateID`),
        INDEX tmp_RateTableRate__TrunkID (`TrunkID`),
        INDEX tmp_RateTableRate__EffectiveDate (`EffectiveDate`)

    );

    DROP TEMPORARY TABLE IF EXISTS tmp_customerrate_;
    CREATE TEMPORARY TABLE tmp_customerrate_ (
        RateID INT,
        Code VARCHAR(50),
        Description VARCHAR(200),
        Interval1 INT,
        IntervalN INT,
        ConnectionFee DECIMAL(18, 6),
        RoutinePlanName VARCHAR(50),
        Rate DECIMAL(18, 6),
        RateN DECIMAL(18, 6),
        EffectiveDate DATE,
        EndDate DATE,
        LastModifiedDate DATETIME,
        LastModifiedBy VARCHAR(50),
        CustomerRateId INT,
        TrunkID INT,
        RateTableRateId INT,
        IncludePrefix TINYINT,
        Prefix VARCHAR(50),
        RatePrefix VARCHAR(50),
        AreaPrefix VARCHAR(50)
    );


    INSERT INTO tmp_CustomerRates_

            SELECT
                tblCustomerRate.RateID,
                tblCustomerRate.Interval1,
                tblCustomerRate.IntervalN,
                tblCustomerRate.Rate,
                tblCustomerRate.RateN,
                tblCustomerRate.ConnectionFee,
                tblCustomerRate.EffectiveDate,
                tblCustomerRate.EndDate,
                tblCustomerRate.LastModifiedDate,
                tblCustomerRate.LastModifiedBy,
                tblCustomerRate.CustomerRateId,
                NULL AS RateTableRateID,
                p_trunkID as TrunkID,
                p_TimezonesID as TimezonesID,
                tblCustomerRate.RoutinePlan

            FROM tblCustomerRate
            INNER JOIN tblRate
                ON tblCustomerRate.RateID = tblRate.RateID
            WHERE (p_contryID IS NULL OR tblRate.CountryID = p_contryID)
            AND (p_code IS NULL OR Code LIKE REPLACE(p_code, '*', '%'))
            AND (p_description IS NULL OR tblRate.Description LIKE REPLACE(p_description, '*', '%'))
            AND (tblRate.CompanyID = p_companyid)
            AND tblRate.CodeDeckId = v_codedeckid_
            AND tblCustomerRate.TrunkID = p_trunkID
            AND (p_TimezonesID IS NULL OR tblCustomerRate.TimezonesID = p_TimezonesID)
            AND (p_RoutinePlan = 0 or tblCustomerRate.RoutinePlan = p_RoutinePlan)
            AND CustomerID = p_AccountID

            ORDER BY
                tblCustomerRate.TrunkId, tblCustomerRate.CustomerId,tblCustomerRate.RateID,tblCustomerRate.EffectiveDate DESC;







	 	DROP TEMPORARY TABLE IF EXISTS tmp_CustomerRates4_;
			CREATE TEMPORARY TABLE IF NOT EXISTS tmp_CustomerRates4_ as (select * from tmp_CustomerRates_);
			DELETE n1 FROM tmp_CustomerRates_ n1, tmp_CustomerRates4_ n2 WHERE n1.EffectiveDate < n2.EffectiveDate
			AND n1.TrunkID = n2.TrunkID
         AND (p_TimezonesID IS NULL OR n1.TimezonesID = n2.TimezonesID)
			AND  n1.RateID = n2.RateID
			AND
			(
				(p_Effective = 'CustomDate' AND n1.EffectiveDate <= p_CustomDate AND n2.EffectiveDate <= p_CustomDate)
				OR
				(p_Effective != 'CustomDate' AND n1.EffectiveDate <= NOW() AND n2.EffectiveDate <= NOW())
			);

	 	DROP TEMPORARY TABLE IF EXISTS tmp_CustomerRates2_;
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_CustomerRates2_ as (select * from tmp_CustomerRates_);
		DROP TEMPORARY TABLE IF EXISTS tmp_CustomerRates3_;
	   CREATE TEMPORARY TABLE IF NOT EXISTS tmp_CustomerRates3_ as (select * from tmp_CustomerRates_);
	   DROP TEMPORARY TABLE IF EXISTS tmp_CustomerRates5_;
	   CREATE TEMPORARY TABLE IF NOT EXISTS tmp_CustomerRates5_ as (select * from tmp_CustomerRates_);

	   ALTER TABLE tmp_CustomerRates2_ ADD  INDEX tmp_CustomerRatesRateID (`RateID`);
	   ALTER TABLE tmp_CustomerRates3_ ADD  INDEX tmp_CustomerRatesRateID (`RateID`);
	   ALTER TABLE tmp_CustomerRates5_ ADD  INDEX tmp_CustomerRatesRateID (`RateID`);

	   ALTER TABLE tmp_CustomerRates2_ ADD  INDEX tmp_CustomerRatesEffectiveDate (`EffectiveDate`);
	   ALTER TABLE tmp_CustomerRates3_ ADD  INDEX tmp_CustomerRatesEffectiveDate (`EffectiveDate`);
	   ALTER TABLE tmp_CustomerRates5_ ADD  INDEX tmp_CustomerRatesEffectiveDate (`EffectiveDate`);

    INSERT INTO tmp_RateTableRate_
            SELECT
                tblRateTableRate.RateID,
                tblRateTableRate.Interval1,
                tblRateTableRate.IntervalN,
                tblRateTableRate.Rate,
                tblRateTableRate.RateN,
                tblRateTableRate.ConnectionFee,
      			 tblRateTableRate.EffectiveDate,
      			 tblRateTableRate.EndDate,
                NULL AS LastModifiedDate,
                NULL AS LastModifiedBy,
                NULL AS CustomerRateId,
                tblRateTableRate.RateTableRateID,
                p_trunkID as TrunkID,
                p_TimezonesID as TimezonesID
            FROM tblRateTableRate
            INNER JOIN tblRate
                ON tblRateTableRate.RateID = tblRate.RateID
            WHERE (p_contryID IS NULL OR tblRate.CountryID = p_contryID)
            AND (p_code IS NULL OR Code LIKE REPLACE(p_code, '*', '%'))
            AND (p_description IS NULL OR tblRate.Description LIKE REPLACE(p_description, '*', '%'))
            AND (tblRate.CompanyID = p_companyid)
            AND tblRate.CodeDeckId = v_codedeckid_
            AND RateTableID = v_ratetableid_
            AND (p_TimezonesID IS NULL OR tblRateTableRate.TimezonesID = p_TimezonesID)
            AND (
						(
							(SELECT count(*) from tmp_CustomerRates2_ cr where cr.RateID = tblRateTableRate.RateID) >0
							AND tblRateTableRate.EffectiveDate <
								( SELECT MIN(cr.EffectiveDate)
                          FROM tmp_CustomerRates_ as cr
                          WHERE cr.RateID = tblRateTableRate.RateID
								)
							AND (SELECT count(*) from tmp_CustomerRates5_ cr where cr.RateID = tblRateTableRate.RateID AND cr.EffectiveDate <= NOW() ) = 0
						)
						or  (  SELECT count(*) from tmp_CustomerRates3_ cr where cr.RateID = tblRateTableRate.RateID ) = 0
					)

                ORDER BY tblRateTableRate.RateTableId,tblRateTableRate.RateID,tblRateTableRate.effectivedate DESC;




		  DROP TEMPORARY TABLE IF EXISTS tmp_RateTableRate4_;
		  CREATE TEMPORARY TABLE IF NOT EXISTS tmp_RateTableRate4_ as (select * from tmp_RateTableRate_);
        DELETE n1 FROM tmp_RateTableRate_ n1, tmp_RateTableRate4_ n2 WHERE n1.EffectiveDate < n2.EffectiveDate
	 	  AND n1.TrunkID = n2.TrunkID
		  AND  n1.RateID = n2.RateID
		  AND (p_TimezonesID IS NULL OR n1.TimezonesID = n2.TimezonesID)
		  AND
			(
				(p_Effective = 'CustomDate' AND n1.EffectiveDate <= p_CustomDate AND n2.EffectiveDate <= p_CustomDate)
				OR
				(p_Effective != 'CustomDate' AND n1.EffectiveDate <= NOW() AND n2.EffectiveDate <= NOW())
			);





		  INSERT INTO tmp_customerrate_
        SELECT
        			 r.RateID,
                r.Code,
                r.Description,
                CASE WHEN allRates.Interval1 IS NULL
                THEN
                    r.Interval1
                ELSE
                    allRates.Interval1
                END as Interval1,
                CASE WHEN allRates.IntervalN IS NULL
                THEN
                    r.IntervalN
                ELSE
                    allRates.IntervalN
                END  IntervalN,
                allRates.ConnectionFee,
                allRates.RoutinePlanName,
                allRates.Rate,
                allRates.RateN,
                allRates.EffectiveDate,
                allRates.EndDate,
                allRates.LastModifiedDate,
                allRates.LastModifiedBy,
                allRates.CustomerRateId,
                p_trunkID as TrunkID,
                allRates.RateTableRateId,
					v_IncludePrefix_ as IncludePrefix ,
   	         CASE  WHEN tblTrunk.TrunkID is not null
               THEN
               	tblTrunk.Prefix
               ELSE
               	v_Prefix_
					END AS Prefix,
					CASE  WHEN tblTrunk.TrunkID is not null
               THEN
               	tblTrunk.RatePrefix
               ELSE
               	v_RatePrefix_
					END AS RatePrefix,
					CASE  WHEN tblTrunk.TrunkID is not null
               THEN
               	tblTrunk.AreaPrefix
               ELSE
               	v_AreaPrefix_
					END AS AreaPrefix
        FROM tblRate r
        LEFT JOIN (SELECT
                CustomerRates.RateID,
                CustomerRates.Interval1,
                CustomerRates.IntervalN,
                tblTrunk.Trunk as RoutinePlanName,
                CustomerRates.ConnectionFee,
                CustomerRates.Rate,
                CustomerRates.RateN,
                CustomerRates.EffectiveDate,
                CustomerRates.EndDate,
                CustomerRates.LastModifiedDate,
                CustomerRates.LastModifiedBy,
                CustomerRates.CustomerRateId,
                NULL AS RateTableRateID,
                p_trunkID as TrunkID,
                RoutinePlan
            FROM tmp_CustomerRates_ CustomerRates
            LEFT JOIN tblTrunk on tblTrunk.TrunkID = CustomerRates.RoutinePlan
            WHERE
                (
					 	( p_Effective = 'Now' AND CustomerRates.EffectiveDate <= NOW() )
					 	OR
					 	( p_Effective = 'Future' AND CustomerRates.EffectiveDate > NOW() )
						OR
						( p_Effective = 'CustomDate' AND CustomerRates.EffectiveDate <= p_CustomDate AND (CustomerRates.EndDate IS NULL OR CustomerRates.EndDate > p_CustomDate) )
					 	OR
						p_Effective = 'All'
					 )


            UNION ALL

            SELECT
            DISTINCT
                rtr.RateID,
                rtr.Interval1,
                rtr.IntervalN,
                NULL,
                rtr.ConnectionFee,
                rtr.Rate,
                rtr.RateN,
                rtr.EffectiveDate,
                rtr.EndDate,
                NULL,
                NULL,
                NULL AS CustomerRateId,
                rtr.RateTableRateID,
                p_trunkID as TrunkID,
                NULL AS RoutinePlan
            FROM tmp_RateTableRate_ AS rtr
            LEFT JOIN tmp_CustomerRates2_ as cr
                ON cr.RateID = rtr.RateID AND
						 (
						 	( p_Effective = 'Now' AND cr.EffectiveDate <= NOW() )
						 	OR
						 	( p_Effective = 'Future' AND cr.EffectiveDate > NOW())
						 	OR
							( p_Effective = 'CustomDate' AND cr.EffectiveDate <= p_CustomDate AND (cr.EndDate IS NULL OR cr.EndDate > p_CustomDate) )
						 	OR
							 p_Effective = 'All'
						 )
            WHERE (
                (
                    p_Effective = 'Now' AND rtr.EffectiveDate <= NOW()
                    AND (
                            (cr.RateID IS NULL)
                            OR
                            (cr.RateID IS NOT NULL AND rtr.RateTableRateID IS NULL)
                        )

                )
                OR
                ( p_Effective = 'Future' AND rtr.EffectiveDate > NOW()
                    AND (
                            (cr.RateID IS NULL)
                            OR
                            (
                                cr.RateID IS NOT NULL AND rtr.EffectiveDate < (
                                                                                SELECT IFNULL(MIN(crr.EffectiveDate), rtr.EffectiveDate)
                                                                                FROM tmp_CustomerRates3_ as crr
                                                                                WHERE crr.RateID = rtr.RateID
                                                                                )
                            )
                        )
                )
				OR
				(
					p_Effective = 'CustomDate' AND rtr.EffectiveDate <= p_CustomDate AND (rtr.EndDate IS NULL OR rtr.EndDate > p_CustomDate)
					AND (
                            (cr.RateID IS NULL)
                            OR
                            (cr.RateID IS NOT NULL AND rtr.RateTableRateID IS NULL)
                        )
				)
            OR p_Effective = 'All'

            )

				) allRates
            ON allRates.RateID = r.RateID
         LEFT JOIN tblTrunk on tblTrunk.TrunkID = RoutinePlan
        WHERE (p_contryID IS NULL OR r.CountryID = p_contryID)
        AND (p_code IS NULL OR Code LIKE REPLACE(p_code, '*', '%'))
        AND (p_description IS NULL OR r.Description LIKE REPLACE(p_description, '*', '%'))
        AND (r.CompanyID = p_companyid)
        AND r.CodeDeckId = v_codedeckid_
        AND  ((p_effectedRates = 1 AND Rate IS NOT NULL) OR  (p_effectedRates = 0));




    IF p_isExport = 0
    THEN


         SELECT
                RateID,
                Code,
                Description,
                Interval1,
                IntervalN,
                ConnectionFee,
                RoutinePlanName,
                Rate,
                RateN,
                EffectiveDate,
                EndDate,
                LastModifiedDate,
                LastModifiedBy,
                CustomerRateId,
                TrunkID,
                RateTableRateId
            FROM tmp_customerrate_
            ORDER BY
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeDESC') THEN Code
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeASC') THEN Code
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionDESC') THEN Description
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionASC') THEN Description
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateDESC') THEN Rate
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateASC') THEN Rate
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateNDESC') THEN RateN
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateNASC') THEN RateN
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1DESC') THEN Interval1
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1ASC') THEN Interval1
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNDESC') THEN IntervalN
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNASC') THEN IntervalN
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeDESC') THEN ConnectionFee
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeASC') THEN ConnectionFee
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateDESC') THEN EffectiveDate
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateASC') THEN EffectiveDate
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateDESC') THEN EndDate
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateASC') THEN EndDate
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'LastModifiedDateDESC') THEN LastModifiedDate
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'LastModifiedDateASC') THEN LastModifiedDate
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'LastModifiedByDESC') THEN LastModifiedBy
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'LastModifiedByASC') THEN LastModifiedBy
                END ASC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CustomerRateIdDESC') THEN CustomerRateId
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CustomerRateIdASC') THEN CustomerRateId
                END ASC
            LIMIT p_RowspPage OFFSET v_OffSet_;

        SELECT
            COUNT(RateID) AS totalcount
        FROM tmp_customerrate_;

    END IF;

    IF p_isExport = 1
    THEN

          select
            Code,
            Description,
            Interval1,
            IntervalN,
            ConnectionFee,
            Rate,
            RateN,
            EffectiveDate,
            LastModifiedDate,
            LastModifiedBy from tmp_customerrate_;

    END IF;


	IF p_isExport = 2
    THEN

          select
            Code,
            Description,
            Interval1,
            IntervalN,
            ConnectionFee,
            Rate,
            RateN,
            EffectiveDate from tmp_customerrate_;

    END IF;


    SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetCustomerRatesArchiveGrid` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_GetCustomerRatesArchiveGrid`(
	IN `p_CompanyID` INT,
	IN `p_AccountID` INT,
	IN `p_TimezonesID` INT,
	IN `p_Codes` LONGTEXT
)
BEGIN
	SELECT
	--	cra.CustomerRateArchiveID,
	--	cra.CustomerRateID,
	--	cra.AccountID,
		r.Code,
		r.Description,
		IFNULL(cra.ConnectionFee,'') AS ConnectionFee,
		CASE WHEN cra.Interval1 IS NOT NULL THEN cra.Interval1 ELSE r.Interval1 END AS Interval1,
		CASE WHEN cra.IntervalN IS NOT NULL THEN cra.IntervalN ELSE r.IntervalN END AS IntervalN,
		cra.Rate,
		cra.RateN,
		cra.EffectiveDate,
		IFNULL(cra.EndDate,'') AS EndDate,
		IFNULL(cra.created_at,'') AS ModifiedDate,
		IFNULL(cra.created_by,'') AS ModifiedBy
	FROM
		tblCustomerRateArchive cra
	JOIN
		tblRate r ON r.RateID=cra.RateId
	WHERE
		r.CompanyID = p_CompanyID AND
		cra.AccountId = p_AccountID AND
		cra.TimezonesID = p_TimezonesID AND
		FIND_IN_SET (r.Code, p_Codes) != 0
	ORDER BY
		cra.EffectiveDate DESC, cra.created_at DESC;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetDashboardDataJobs` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetDashboardDataJobs`(IN `p_companyId` int , IN `p_userId` int , IN `p_isadmin` int)
BEGIN
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	SELECT `tblJob`.`JobID`, `tblJob`.`Title`, `tblJobStatus`.`Title` AS `Status`, `tblJob`.`HasRead`, `tblJob`.`CreatedBy`, `tblJob`.`created_at`
	FROM tblJob INNER JOIN tblJobStatus ON `tblJob`.`JobStatusID` = `tblJobStatus`.`JobStatusID` INNER JOIN tblJobType ON `tblJob`.`JobTypeID` = `tblJobType`.`JobTypeID`
	WHERE `tblJob`.`CompanyID` = p_companyId AND ( p_isadmin = 1 OR (p_isadmin = 0 AND tblJob.JobLoggedUserID = p_userId) )
	ORDER BY `tblJob`.`ShowInCounter` DESC, `tblJob`.`updated_at` DESC,tblJob.JobID DESC
	LIMIT 10;


	
	SELECT count(*) AS totalpending FROM tblJob INNER JOIN tblJobStatus ON `tblJob`.`JobStatusID` = `tblJobStatus`.`JobStatusID`
	WHERE `tblJobStatus`.`Title` = 'Pending' AND `tblJob`.`CompanyID` = p_companyId AND
	( p_isadmin = 1 OR ( p_isadmin = 0 AND tblJob.JobLoggedUserID = p_userId) );
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
	
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetDashboardDataRecentDueRateSheet` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetDashboardDataRecentDueRateSheet`(IN `p_companyId` int)
BEGIN
 SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
        SELECT count(*) as TotalDueCustomer,DAYSDIFF from (
			SELECT distinct  a.AccountName,a.AccountID,cr.TrunkID,cr.EffectiveDate,TIMESTAMPDIFF(DAY,cr.EffectiveDate, NOW()) as DAYSDIFF
			FROM tblCustomerRate cr
			INNER JOIN tblRate  r on r.RateID =cr.RateID
			INNER JOIN tblCountry c on c.CountryID = r.CountryID
			INNER JOIN tblAccount a on a.AccountID = cr.CustomerID
			WHERE a.CompanyId =@companyId
			AND TIMESTAMPDIFF(DAY, cr.EffectiveDate, DATE_FORMAT (NOW(),120)) BETWEEN -1 AND 1

		) as tbl
		LEFT JOIN tblJob ON tblJob.AccountID = tbl.AccountID
					AND tblJob.JobID IN(select JobID from tblJob where JobTypeID = (select JobTypeID from tblJobType where Code='CD'))
					AND FIND_IN_SET (tbl.TrunkID,JSON_EXTRACT(tblJob.Options, '$.Trunks')) != 0

					AND ( TIMESTAMPDIFF(DAY, tblJob.created_at, NOW()) = DAYSDIFF or TIMESTAMPDIFF(DAY, tblJob.created_at, EffectiveDate)  BETWEEN -1 AND 0)

		where JobStatusID is null or JobStatusID <> (select JobStatusID from tblJobStatus where Code='S')
		group by DAYSDIFF
		order by DAYSDIFF desc;

 
        

        SELECT count(*) as TotalDueVendor ,DAYSDIFF from (
				SELECT  DISTINCT a.AccountName,a.AccountID,vr.TrunkID,vr.EffectiveDate,TIMESTAMPDIFF(DAY,vr.EffectiveDate, NOW()) as DAYSDIFF
			FROM tblVendorRate vr
			INNER JOIN tblRate  r on r.RateID =vr.RateID
			INNER JOIN tblCountry c on c.CountryID = r.CountryID
			INNER JOIN tblAccount a on a.AccountID = vr.AccountId
			WHERE a.CompanyId = @companyId
			AND TIMESTAMPDIFF(DAY,vr.EffectiveDate, NOW()) BETWEEN -1 AND 1
	   ) as tbl
		LEFT JOIN tblJob ON tblJob.AccountID = tbl.AccountID
					AND tblJob.JobID IN(select JobID from tblJob where JobTypeID = (select JobTypeID from tblJobType where Code='VD'))
					AND FIND_IN_SET (tbl.TrunkID,JSON_EXTRACT(tblJob.Options, '$.Trunks')) != 0
					AND ( TIMESTAMPDIFF(DAY, tblJob.created_at, NOW()) = DAYSDIFF or TIMESTAMPDIFF(DAY, tblJob.created_at, EffectiveDate)  BETWEEN -1 AND 0)

		where JobStatusID is null or JobStatusID <> (select JobStatusID from tblJobStatus where Code='S')
		group by DAYSDIFF
		order by DAYSDIFF desc;
		
		SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ; 
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetDashboardProcessedFiles` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetDashboardProcessedFiles`(IN `p_companyId` int , IN `p_userId` int , IN `p_isadmin` int)
BEGIN
    select `tblJob`.`JobID`, `tblJob`.`Title`, `tblJobStatus`.`Title` as Status, `tblJob`.`CreatedBy`, `tblJob`.`created_at` from tblJob inner join tblJobStatus on `tblJob`.`JobStatusID` = `tblJobStatus`.`JobStatusID` inner join tblJobType on `tblJob`.`JobTypeID` = `tblJobType`.`JobTypeID`
        where ( tblJobStatus.Title = 'Success' OR tblJobStatus.Title = 'Completed' ) and `tblJob`.`CompanyID` = p_companyId and
        ( p_isadmin = 1 OR ( p_isadmin = 0 and `tblJob`.`JobLoggedUserID` = p_userId))  and `tblJob`.`updated_at` >= DATE_ADD(NOW(),INTERVAL -7 DAY)
		  LIMIT 10;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetDashboardRecentAccounts` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetDashboardRecentAccounts`(
	IN `p_companyId` int ,
	IN `p_userId` VARCHAR(500),
	IN `p_AccountManager` INT

)
BEGIN
    select  AccountID,AccountName,Phone,Email,created_by,created_at from tblAccount
          where
          `AccountType` = '1' and CompanyID = p_companyId and `Status` = '1'
          AND (  p_AccountManager = 0 OR (p_AccountManager = 1 AND find_in_set(tblAccount.Owner,p_userId)) )
    order by `tblAccount`.`AccountID` desc
	 LIMIT 10;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetDashboardRecentLeads` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetDashboardRecentLeads`(IN `p_companyId` int)
BEGIN
    select AccountID,AccountName,Phone,Email,created_by,created_at from tblAccount where (`AccountType` = '0' and `CompanyID` = p_companyId and `Status` = '1') order by `tblAccount`.`AccountID` desc LIMIT 10;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getDeductCallChargeAccounts` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getDeductCallChargeAccounts`(
	IN `p_CompanyID` INT
)
BEGIN

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SELECT
		DISTINCT
		a.AccountID,
		ab.NextInvoiceDate,
		AccountName,
		ab.ServiceID
	FROM tblAccount a
	INNER JOIN tblAccountBilling ab
		ON ab.AccountID = a.AccountID and ab.ServiceID = 0
	INNER JOIN tblBillingClass bc
		ON bc.BillingClassID = ab.BillingClassID
	WHERE a.CompanyId = p_CompanyID
	AND a.Status = 1
	AND AccountType = 1
	AND Billing = 1
	AND a.AccountID IN (111)
	AND (ab.BillingCycleType IS NOT NULL AND ab.BillingCycleType <> 'manual')
	AND bc.DeductCallChargeInAdvance = 1
	ORDER BY a.AccountID ASC;


	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getDefaultCodes` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getDefaultCodes`(IN `p_CompanyID` INT)
BEGIN

	DROP TEMPORARY TABLE IF EXISTS tmp_codes_;
	CREATE TEMPORARY TABLE tmp_codes_ (
		RateID INT,
		Code VARCHAR(50),
		INDEX tmp_codes_RateID (`RateID`),
		INDEX tmp_codes_Code (`Code`)
	);

	INSERT INTO tmp_codes_
	SELECT
	DISTINCT
		tblRate.RateID,
		tblRate.Code
	FROM tblRate
	INNER JOIN tblCodeDeck
		ON tblCodeDeck.CodeDeckId = tblRate.CodeDeckId
	WHERE tblCodeDeck.CompanyId = p_CompanyID
	AND tblCodeDeck.DefaultCodedeck = 1 ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getDestinationCode` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getDestinationCode`(IN `p_DestinationGroupSetID` INT, IN `p_DestinationGroupID` INT, IN `p_CountryID` INT, IN `p_Code` VARCHAR(50), IN `p_Selected` INT, IN `p_Description` VARCHAR(50), IN `p_PageNumber` INT, IN `p_RowspPage` INT)
BEGIN
		
	DECLARE v_OffSet_ int;
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
	
	SELECT
		r.RateID,
		r.Code,
		r.Description,
		IF(DestinationGroupCodeID >0,1,0) as DestinationGroupCodeID
	FROM tblRate r
	INNER JOIN tblDestinationGroupSet dg
		ON dg.CodedeckID =r.CodeDeckId
	LEFT JOIN tblDestinationGroupCode dgc
		ON DestinationGroupID = p_DestinationGroupID
		AND dgc.RateID = r.RateID
	WHERE dg.DestinationGroupSetID = p_DestinationGroupSetID
	AND (p_Code = '' OR Code LIKE REPLACE(p_Code, '*', '%'))
	AND (p_Description = '' OR Description LIKE REPLACE(p_Description, '*', '%'))
	AND (p_CountryID = 0 OR r.CountryID = p_CountryID)
	AND (p_Selected = 0 OR (p_Selected = 1 AND DestinationGroupCodeID IS NOT NULL))
	LIMIT p_RowspPage OFFSET v_OffSet_;
	
	SELECT COUNT(*)  as totalcount
	FROM tblRate r
	INNER JOIN tblDestinationGroupSet dg
		ON dg.CodedeckID =r.CodeDeckId
	LEFT JOIN tblDestinationGroupCode dgc
		ON DestinationGroupID = p_DestinationGroupID
		AND dgc.RateID = r.RateID
	WHERE dg.DestinationGroupSetID = p_DestinationGroupSetID
	AND (p_Code = '' OR Code LIKE REPLACE(p_Code, '*', '%'))
	AND (p_Description = '' OR Description LIKE REPLACE(p_Description, '*', '%'))
	AND (p_CountryID = 0 OR r.CountryID = p_CountryID)
	AND (p_Selected = 0 OR (p_Selected = 1 AND DestinationGroupCodeID IS NOT NULL)); 

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getDestinationGroup` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getDestinationGroup`(IN `p_CompanyID` INT, IN `p_DestinationGroupSetID` INT, IN `p_Name` VARCHAR(50), IN `p_PageNumber` INT, IN `p_RowspPage` INT, IN `p_lSortCol` VARCHAR(50), IN `p_SortOrder` VARCHAR(5), IN `p_isExport` INT)
BEGIN
	DECLARE v_OffSet_ int;
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

	IF p_isExport = 0
	THEN
		SELECT   
			dg.Name,
			CONCAT(SUBSTRING_INDEX(GROUP_CONCAT(r.Code ORDER BY r.Code ASC SEPARATOR ','), ',', 10),'...') as Code,
			dg.CreatedBy,
			dg.created_at,
			dg.DestinationGroupID,
			dg.DestinationGroupSetID
		FROM tblDestinationGroup dg
		LEFT JOIN tblDestinationGroupCode dgc
		ON dg.DestinationGroupID =  dgc.DestinationGroupID
		LEFT JOIN tblRate r 
			ON r.RateID = dgc.RateID
		WHERE dg.DestinationGroupSetID = p_DestinationGroupSetID
			AND (p_Name ='' OR dg.Name like  CONCAT('%',p_Name,'%'))
		GROUP BY dg.DestinationGroupID
		ORDER BY
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'NameDESC') THEN dg.Name
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'NameASC') THEN dg.Name
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CreatedByDESC') THEN dg.CreatedBy
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CreatedByASC') THEN dg.CreatedBy
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atDESC') THEN dg.created_at
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atASC') THEN dg.created_at
			END ASC
		LIMIT p_RowspPage OFFSET v_OffSet_;

		SELECT
			COUNT(DISTINCT dg.DestinationGroupID) AS totalcount
		FROM tblDestinationGroup dg
		LEFT JOIN tblDestinationGroupCode dgc
		ON dg.DestinationGroupID =  dgc.DestinationGroupID
		LEFT JOIN tblRate r 
			ON r.RateID = dgc.RateID
		WHERE dg.DestinationGroupSetID = p_DestinationGroupSetID
			AND (p_Name ='' OR dg.Name like  CONCAT('%',p_Name,'%'));
	END IF;

	IF p_isExport = 1
	THEN
		
		SELECT
			dg.Name as `Destionatio Group Name`,
			GROUP_CONCAT(r.Code ORDER BY r.Code ASC) as `Destination Codes`,
			dg.CreatedBy,
			dg.created_at
		FROM tblDestinationGroup dg
		LEFT JOIN tblDestinationGroupCode dgc
			ON dg.DestinationGroupID =  dgc.DestinationGroupID
		LEFT JOIN tblRate r 
			ON r.RateID = dgc.RateID
		WHERE dg.DestinationGroupSetID = p_DestinationGroupSetID
			AND (p_Name ='' OR dg.Name like  CONCAT('%',p_Name,'%'))
		GROUP BY dg.DestinationGroupID;

	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getDestinationGroupSet` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getDestinationGroupSet`(IN `p_CompanyID` INT, IN `p_Name` VARCHAR(50), IN `p_CodedeckID` INT, IN `p_PageNumber` INT, IN `p_RowspPage` INT, IN `p_lSortCol` VARCHAR(50), IN `p_SortOrder` VARCHAR(5), IN `p_isExport` INT)
BEGIN
	DECLARE v_OffSet_ int;
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

	IF p_isExport = 0
	THEN
		SELECT   
			dgs.Name,
			cd.CodeDeckName,
			dgs.CreatedBy,
			dgs.created_at,
			dgs.DestinationGroupSetID,
			dgs.CodedeckID,
			dgs.CompanyID,
			(SELECT adp.DiscountPlanID FROM tblDiscountPlan dp  LEFT JOIN tblAccountDiscountPlan adp ON adp.DiscountPlanID = dp.DiscountPlanID WHERE dp.DestinationGroupSetID = dgs.DestinationGroupSetID LIMIT 1) as Applied
		FROM tblDestinationGroupSet dgs
		INNER JOIN tblCodeDeck cd 
			ON cd.CodeDeckId = dgs.CodedeckID
		WHERE dgs.CompanyID = p_CompanyID
			AND (p_Name ='' OR dgs.Name like  CONCAT('%',p_Name,'%'))
			AND (p_CodedeckID = 0 OR dgs.CodedeckID = p_CodedeckID)
		ORDER BY
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'NameDESC') THEN dgs.Name
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'NameASC') THEN dgs.Name
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CreatedByDESC') THEN dgs.CreatedBy
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CreatedByASC') THEN dgs.CreatedBy
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atDESC') THEN dgs.created_at
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atASC') THEN dgs.created_at
			END ASC
		LIMIT p_RowspPage OFFSET v_OffSet_;

		SELECT
			COUNT(dgs.DestinationGroupSetID) AS totalcount
		FROM tblDestinationGroupSet dgs
		INNER JOIN tblCodeDeck cd 
			ON cd.CodeDeckId = dgs.CodedeckID
		WHERE dgs.CompanyID = p_CompanyID
			AND (p_Name ='' OR dgs.Name like  CONCAT('%',p_Name,'%'))
			AND (p_CodedeckID = 0 OR dgs.CodedeckID = p_CodedeckID);
	END IF;

	IF p_isExport = 1
	THEN
		
		SELECT   
			dgs.Name,
			dgs.CreatedBy,
			dgs.created_at
		FROM tblDestinationGroupSet dgs
		INNER JOIN tblCodeDeck cd 
			ON cd.CodeDeckId = dgs.CodedeckID
		WHERE dgs.CompanyID = p_CompanyID
			AND (p_Name ='' OR dgs.Name like  CONCAT('%',p_Name,'%'))
			AND (p_CodedeckID = 0 OR dgs.CodedeckID = p_CodedeckID);

	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetDialStrings` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetDialStrings`(IN `p_dialstringid` int, IN `p_dialstring` varchar(250), IN `p_chargecode` varchar(250), IN `p_description` varchar(250), IN `p_forbidden` INT, IN `p_PageNumber` int, IN `p_RowspPage` int, IN `p_lSortCol` VARCHAR(50), IN `p_SortOrder` VARCHAR(5), IN `p_isExport` int )
BEGIN

   DECLARE v_OffSet_ int;
   SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	           
	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;
    

    IF p_isExport = 0
    THEN


        SELECT
            DialStringCodeID,
            DialString,
            ChargeCode,
            Description,
            Forbidden
        FROM tblDialStringCode
        WHERE  (DialStringID = p_dialstringid)
         AND (Forbidden = p_forbidden)
			AND (p_dialstring IS NULL OR DialString LIKE REPLACE(p_dialstring, '*', '%'))
            AND (p_chargecode IS NULL OR ChargeCode LIKE REPLACE(p_chargecode, '*', '%'))
            AND (p_description IS NULL OR Description LIKE REPLACE(p_description, '*', '%'))            
        ORDER BY
            CASE
                WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DialStringDESC') THEN DialString
            END DESC,
            CASE
                WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DialStringASC') THEN DialString
            END ASC,
            CASE
                WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ChargeCodeDESC') THEN ChargeCode
            END DESC,
            CASE
                WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ChargeCodeASC') THEN ChargeCode
            END ASC,
            CASE
                WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionDESC') THEN Description
            END DESC,
            CASE
                WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionASC') THEN Description
            END ASC,
            CASE
                WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ForbiddenDESC') THEN Forbidden
            END DESC,
            CASE
                WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ForbiddenASC') THEN Forbidden
            END ASC
        LIMIT p_RowspPage OFFSET v_OffSet_;

        SELECT
            COUNT(DialStringCodeID) AS totalcount
        FROM tblDialStringCode
        WHERE  (DialStringID = p_dialstringid)
         AND (Forbidden = p_forbidden) 
			AND (p_dialstring IS NULL OR DialString LIKE REPLACE(p_dialstring, '*', '%'))
            AND (p_chargecode IS NULL OR ChargeCode LIKE REPLACE(p_chargecode, '*', '%'))
            AND (p_description IS NULL OR Description LIKE REPLACE(p_description, '*', '%'));

    END IF;

    IF p_isExport = 1
    THEN

        SELECT
            DialString,
            ChargeCode,
            Description,
            Forbidden
        FROM tblDialStringCode
        WHERE  (DialStringID = p_dialstringid)
         AND (Forbidden = p_forbidden)
			AND (p_dialstring IS NULL OR DialString LIKE REPLACE(p_dialstring, '*', '%'))
            AND (p_chargecode IS NULL OR ChargeCode LIKE REPLACE(p_chargecode, '*', '%'))
            AND (p_description IS NULL OR Description LIKE REPLACE(p_description, '*', '%'));   

    END IF;
    IF p_isExport = 2
    THEN

        SELECT
            DialStringCodeID,
            DialString,
            ChargeCode,
            Description,
            Forbidden
        FROM tblDialStringCode
        WHERE  (DialStringID = p_dialstringid)
         AND (Forbidden = p_forbidden)
			AND (p_dialstring IS NULL OR DialString LIKE REPLACE(p_dialstring, '*', '%'))
            AND (p_chargecode IS NULL OR ChargeCode LIKE REPLACE(p_chargecode, '*', '%'))
            AND (p_description IS NULL OR Description LIKE REPLACE(p_description, '*', '%'));   

    END IF;
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getDiscontinuedCustomerRateGrid` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getDiscontinuedCustomerRateGrid`(
	IN `p_CompanyID` INT,
	IN `p_AccountID` INT,
	IN `p_TrunkID` INT,
	IN `p_TimezonesID` INT,
	IN `p_CountryID` INT,
	IN `p_Code` VARCHAR(50),
	IN `p_Description` VARCHAR(50),
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT
)
BEGIN
	DECLARE v_OffSet_ int;
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

	DROP TEMPORARY TABLE IF EXISTS tmp_CustomerRate_;
	CREATE TEMPORARY TABLE tmp_CustomerRate_ (
		RateID INT,
		Code VARCHAR(50),
		Description VARCHAR(200),
		Interval1 INT,
		IntervalN INT,
		ConnectionFee VARCHAR(50),
		RoutinePlanName VARCHAR(50),
		Rate DECIMAL(18, 6),
		RateN DECIMAL(18, 6),
		EffectiveDate DATE,
		EndDate DATE,
		updated_at DATETIME,
		updated_by VARCHAR(50),
		CustomerRateID INT,
		TrunkID INT,
        RateTableRateId INT,
		INDEX tmp_CustomerRate_RateID (`Code`)
	);

	INSERT INTO tmp_CustomerRate_
	SELECT
		cra.RateId,
		r.Code,
		r.Description,
		CASE WHEN cra.Interval1 IS NOT NULL THEN cra.Interval1 ELSE r.Interval1 END AS Interval1,
		CASE WHEN cra.IntervalN IS NOT NULL THEN cra.IntervalN ELSE r.IntervalN END AS IntervalN,
		'' AS ConnectionFee,
		cra.RoutinePlan AS RoutinePlanName,
		cra.Rate,
		cra.RateN,
		cra.EffectiveDate,
		cra.EndDate,
		cra.created_at AS updated_at,
		cra.created_by AS updated_by,
		cra.CustomerRateID,
		p_trunkID AS TrunkID,
		NULL AS RateTableRateID
	FROM
		tblCustomerRateArchive cra
	JOIN
		tblRate r ON r.RateID=cra.RateId
	LEFT JOIN
		tblCustomerRate cr ON cr.CustomerID = cra.AccountId AND cr.TrunkID = cra.TrunkID AND cr.RateId = cra.RateId
	WHERE
		r.CompanyID = p_CompanyID AND
		cra.TrunkID = p_TrunkID AND
		cra.TimezonesID = p_TimezonesID AND
		cra.AccountId = p_AccountID AND
		(p_CountryID IS NULL OR r.CountryID = p_CountryID) AND
		(p_code IS NULL OR r.Code LIKE REPLACE(p_code, '*', '%')) AND
		(p_description IS NULL OR r.Description LIKE REPLACE(p_description, '*', '%')) AND
		cr.CustomerRateID is NULL;

	IF p_isExport = 0
	THEN
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_CustomerRate2_ as (select * from tmp_CustomerRate_);
		DELETE
			n1
		FROM
			tmp_CustomerRate_ n1, tmp_CustomerRate2_ n2
		WHERE
			n1.Code = n2.Code AND n1.CustomerRateID < n2.CustomerRateID;

		SELECT
			RateID,
			Code,
			Description,
			Interval1,
			IntervalN,
			ConnectionFee,
			RoutinePlanName,
			Rate,
			RateN,
			EffectiveDate,
			EndDate,
			updated_at,
			updated_by,
			CustomerRateId,
			TrunkID,
			RateTableRateId
		FROM
			tmp_CustomerRate_
		ORDER BY
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeDESC') THEN Code
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeASC') THEN Code
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionDESC') THEN Description
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionASC') THEN Description
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateDESC') THEN Rate
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateASC') THEN Rate
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateNDESC') THEN RateN
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateNASC') THEN RateN
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeDESC') THEN ConnectionFee
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeASC') THEN ConnectionFee
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1DESC') THEN Interval1
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1ASC') THEN Interval1
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNDESC') THEN IntervalN
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNASC') THEN IntervalN
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateDESC') THEN EffectiveDate
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateASC') THEN EffectiveDate
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateDESC') THEN EndDate
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateASC') THEN EndDate
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_atDESC') THEN updated_at
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_atASC') THEN updated_at
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_byDESC') THEN updated_by
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_byASC') THEN updated_by
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CustomerRateIDDESC') THEN CustomerRateID
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CustomerRateIDASC') THEN CustomerRateID
			END ASC
		LIMIT
			p_RowspPage
			OFFSET
			v_OffSet_;

		SELECT
			COUNT(code) AS totalcount
		FROM tmp_CustomerRate_;

	END IF;

	IF p_isExport = 1
	THEN
		SELECT
			Code,
			Description,
			Rate,
			RateN,
			EffectiveDate,
			EndDate,
			updated_at AS `Modified Date`,
			updated_by AS `Modified By`
		FROM tmp_CustomerRate_;
	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getDiscontinuedRateTableRateGrid` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getDiscontinuedRateTableRateGrid`(
	IN `p_CompanyID` INT,
	IN `p_RateTableID` INT,
	IN `p_TimezonesID` INT,
	IN `p_CountryID` INT,
	IN `p_Code` VARCHAR(50),
	IN `p_Description` VARCHAR(50),
	IN `p_View` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT
)
BEGIN
	DECLARE v_OffSet_ int;
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

	DROP TEMPORARY TABLE IF EXISTS tmp_RateTableRate_;
	CREATE TEMPORARY TABLE tmp_RateTableRate_ (
		RateTableRateID INT,
		Code VARCHAR(50),
		Description VARCHAR(200),
		Interval1 INT,
		IntervalN INT,
		ConnectionFee VARCHAR(50),
		PreviousRate DECIMAL(18, 6),
		Rate DECIMAL(18, 6),
		RateN DECIMAL(18, 6),
		EffectiveDate DATE,
		EndDate DATE,
		updated_at DATETIME,
		updated_by VARCHAR(50),
		INDEX tmp_RateTableRate_RateID (`Code`)
	);

	INSERT INTO tmp_RateTableRate_
	SELECT
		vra.RateTableRateID,
		r.Code,
		r.Description,
		CASE WHEN vra.Interval1 IS NOT NULL THEN vra.Interval1 ELSE r.Interval1 END AS Interval1,
		CASE WHEN vra.IntervalN IS NOT NULL THEN vra.IntervalN ELSE r.IntervalN END AS IntervalN,
		'' AS ConnectionFee,
		null AS PreviousRate,
		vra.Rate,
		vra.RateN,
		vra.EffectiveDate,
		vra.EndDate,
		vra.created_at AS updated_at,
		vra.created_by AS updated_by
	FROM
		tblRateTableRateArchive vra
	JOIN
		tblRate r ON r.RateID=vra.RateId
	LEFT JOIN
		tblRateTableRate vr ON vr.RateTableId = vra.RateTableId AND vr.RateId = vra.RateId AND vr.TimezonesID = vra.TimezonesID
	WHERE
		r.CompanyID = p_CompanyID AND
		vra.RateTableId = p_RateTableID AND
		vra.TimezonesID = p_TimezonesID AND
		(p_CountryID IS NULL OR r.CountryID = p_CountryID) AND
		(p_code IS NULL OR r.Code LIKE REPLACE(p_code, '*', '%')) AND
		(p_description IS NULL OR r.Description LIKE REPLACE(p_description, '*', '%')) AND
		vr.RateTableRateID is NULL;

	IF p_isExport = 0
	THEN
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_RateTableRate2_ as (select * from tmp_RateTableRate_);
		DELETE
			n1
		FROM
			tmp_RateTableRate_ n1, tmp_RateTableRate2_ n2
		WHERE
			n1.Code = n2.Code AND n1.RateTableRateID < n2.RateTableRateID;

		IF p_view = 1
		THEN
			SELECT
				RateTableRateID,
				Code,
				Description,
				Interval1,
				IntervalN,
				ConnectionFee,
				PreviousRate,
				Rate,
				RateN,
				EffectiveDate,
				EndDate,
				updated_at,
				updated_by
			FROM
				tmp_RateTableRate_
			ORDER BY
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeDESC') THEN Code
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeASC') THEN Code
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionDESC') THEN Description
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionASC') THEN Description
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateDESC') THEN Rate
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateASC') THEN Rate
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateNDESC') THEN RateN
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateNASC') THEN RateN
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeDESC') THEN ConnectionFee
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeASC') THEN ConnectionFee
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1DESC') THEN Interval1
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1ASC') THEN Interval1
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNDESC') THEN IntervalN
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNASC') THEN IntervalN
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateDESC') THEN EffectiveDate
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateASC') THEN EffectiveDate
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateDESC') THEN EndDate
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateASC') THEN EndDate
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_atDESC') THEN updated_at
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_atASC') THEN updated_at
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_byDESC') THEN updated_by
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_byASC') THEN updated_by
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateTableRateIDDESC') THEN RateTableRateID
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateTableRateIDASC') THEN RateTableRateID
				END ASC
			LIMIT
				p_RowspPage
			OFFSET
				v_OffSet_;

			SELECT
				COUNT(code) AS totalcount
			FROM tmp_RateTableRate_;

		ELSE

			SELECT
				group_concat(RateTableRateID) AS RateTableRateID,
				group_concat(Code),
				Description,
				ConnectionFee,
				Interval1,
				IntervalN,
				ANY_VALUE(PreviousRate),
				Rate,
				RateN,
				EffectiveDate,
				EndDate,
				MAX(updated_at),
				MAX(updated_by)
			FROM
				tmp_RateTableRate_
			GROUP BY
				Description, Interval1, Intervaln, ConnectionFee, Rate, EffectiveDate, EndDate
			ORDER BY
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionDESC') THEN ANY_VALUE(Description)
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionASC') THEN ANY_VALUE(Description)
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateDESC') THEN ANY_VALUE(Rate)
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateASC') THEN ANY_VALUE(Rate)
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateNDESC') THEN ANY_VALUE(RateN)
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateNASC') THEN ANY_VALUE(RateN)
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeDESC') THEN ANY_VALUE(ConnectionFee)
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeASC') THEN ANY_VALUE(ConnectionFee)
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1DESC') THEN ANY_VALUE(Interval1)
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1ASC') THEN ANY_VALUE(Interval1)
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNDESC') THEN ANY_VALUE(IntervalN)
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNASC') THEN ANY_VALUE(IntervalN)
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateDESC') THEN ANY_VALUE(EffectiveDate)
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateASC') THEN ANY_VALUE(EffectiveDate)
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateDESC') THEN ANY_VALUE(EndDate)
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateASC') THEN ANY_VALUE(EndDate)
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_atDESC') THEN ANY_VALUE(updated_at)
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_atASC') THEN ANY_VALUE(updated_at)
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_byDESC') THEN ANY_VALUE(updated_by)
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_byASC') THEN ANY_VALUE(updated_by)
				END ASC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateTableRateIDDESC') THEN ANY_VALUE(RateTableRateID)
				END DESC,
				CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateTableRateIDASC') THEN ANY_VALUE(RateTableRateID)
				END ASC
			LIMIT
				p_RowspPage
			OFFSET
				v_OffSet_;


			SELECT COUNT(*) AS `totalcount`
			FROM (
				SELECT
	            Description
	        	FROM tmp_RateTableRate_
					GROUP BY Description, Interval1, Intervaln, ConnectionFee, Rate, EffectiveDate, EndDate
			) totalcount;

		END IF;

	END IF;

	IF p_isExport = 1
	THEN
		SELECT
			Code,
			Description,
			Rate,
			RateN,
			EffectiveDate,
			EndDate,
			updated_at AS `Modified Date`,
			updated_by AS `Modified By`
		FROM tmp_RateTableRate_;
	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getDiscontinuedVendorRateGrid` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getDiscontinuedVendorRateGrid`(
	IN `p_CompanyID` INT,
	IN `p_AccountID` INT,
	IN `p_TrunkID` INT,
	IN `p_TimezonesID` INT,
	IN `p_CountryID` INT,
	IN `p_Code` VARCHAR(50),
	IN `p_Description` VARCHAR(50),
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_isExport` INT
)
BEGIN
	DECLARE v_OffSet_ int;
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

	DROP TEMPORARY TABLE IF EXISTS tmp_VendorRate_;
   CREATE TEMPORARY TABLE tmp_VendorRate_ (
        VendorRateID INT,
        Code VARCHAR(50),
        Description VARCHAR(200),
		  ConnectionFee VARCHAR(50),
        Interval1 INT,
        IntervalN INT,
        Rate DECIMAL(18, 6),
        RateN DECIMAL(18, 6),
        EffectiveDate DATE,
        EndDate DATE,
        updated_at DATETIME,
        updated_by VARCHAR(50),
        INDEX tmp_VendorRate_RateID (`Code`)
   );

   INSERT INTO tmp_VendorRate_
		SELECT
			vra.VendorRateID,
			r.Code,
			r.Description,
			'' AS ConnectionFee,
			CASE WHEN vra.Interval1 IS NOT NULL THEN vra.Interval1 ELSE r.Interval1 END AS Interval1,
			CASE WHEN vra.IntervalN IS NOT NULL THEN vra.IntervalN ELSE r.IntervalN END AS IntervalN,
			vra.Rate,
			vra.RateN,
			vra.EffectiveDate,
			vra.EndDate,
			vra.created_at AS updated_at,
			vra.created_by AS updated_by
		FROM
			tblVendorRateArchive vra
		JOIN
			tblRate r ON r.RateID=vra.RateId
		LEFT JOIN
			tblVendorRate vr ON vr.AccountId = vra.AccountId AND vr.TrunkID = vra.TrunkID AND vr.RateId = vra.RateId AND vr.TimezonesID = vra.TimezonesID
		WHERE
			r.CompanyID = p_CompanyID AND
			vra.TrunkID = p_TrunkID AND
			vra.TimezonesID = p_TimezonesID AND
			vra.AccountId = p_AccountID AND
			(p_CountryID IS NULL OR r.CountryID = p_CountryID) AND
			(p_code IS NULL OR r.Code LIKE REPLACE(p_code, '*', '%')) AND
			(p_description IS NULL OR r.Description LIKE REPLACE(p_description, '*', '%')) AND
			vr.VendorRateID is NULL;

	IF p_isExport = 0
	THEN
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_VendorRate2_ as (select * from tmp_VendorRate_);
		DELETE
			n1
		FROM
			tmp_VendorRate_ n1, tmp_VendorRate2_ n2
		WHERE
			n1.Code = n2.Code AND n1.VendorRateID < n2.VendorRateID;

 		SELECT
			VendorRateID,
			Code,
			Description,
			ConnectionFee,
			Interval1,
			IntervalN,
			Rate,
			RateN,
			EffectiveDate,
			EndDate,
			updated_at,
			updated_by
		FROM
			tmp_VendorRate_
		ORDER BY
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeDESC') THEN Code
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CodeASC') THEN Code
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionDESC') THEN Description
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DescriptionASC') THEN Description
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateDESC') THEN Rate
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateASC') THEN Rate
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateNDESC') THEN RateN
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'RateNASC') THEN RateN
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeDESC') THEN ConnectionFee
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'ConnectionFeeASC') THEN ConnectionFee
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1DESC') THEN Interval1
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'Interval1ASC') THEN Interval1
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNDESC') THEN IntervalN
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'IntervalNASC') THEN IntervalN
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateDESC') THEN EffectiveDate
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EffectiveDateASC') THEN EffectiveDate
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateDESC') THEN EndDate
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'EndDateASC') THEN EndDate
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_atDESC') THEN updated_at
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_atASC') THEN updated_at
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_byDESC') THEN updated_by
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'updated_byASC') THEN updated_by
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'VendorRateIDDESC') THEN VendorRateID
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'VendorRateIDASC') THEN VendorRateID
			END ASC
		LIMIT
			p_RowspPage
		OFFSET
			v_OffSet_;

		SELECT
			COUNT(code) AS totalcount
		FROM tmp_VendorRate_;

	END IF;

   IF p_isExport = 1
	THEN
		SELECT
			Code,
			Description,
			Rate,
			RateN,
			EffectiveDate,
			EndDate,
			updated_at AS `Modified Date`,
			updated_by AS `Modified By`

		FROM tmp_VendorRate_;
	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getDiscount` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getDiscount`(IN `p_CompanyID` INT, IN `p_DiscountPlanID` INT, IN `p_Name` VARCHAR(50), IN `p_PageNumber` INT, IN `p_RowspPage` INT, IN `p_lSortCol` VARCHAR(50), IN `p_SortOrder` VARCHAR(5), IN `p_isExport` INT)
BEGIN
	DECLARE v_OffSet_ int;
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

	IF p_isExport = 0
	THEN
		SELECT   
			dg.Name,
			ROUND(ds.Threshold/60,0) as Threshold,
			ds.Discount,
			IF(ds.Unlimited =1 ,'Unlimited','') as UnlimitedText,
			dp.UpdatedBy,
			dp.updated_at,
			dp.DiscountID,
			dp.DiscountPlanID,
			dp.DestinationGroupID,
			ds.DiscountSchemeID,
			dp.Service,
			ds.Unlimited
		FROM tblDiscount dp
		INNER JOIN tblDestinationGroup dg 
			ON dg.DestinationGroupID = dp.DestinationGroupID
		INNER JOIN tblDiscountScheme ds 
			ON ds.DiscountID = dp.DiscountID
		WHERE dp.DiscountPlanID = p_DiscountPlanID
			AND (p_Name ='' OR dg.Name like  CONCAT('%',p_Name,'%'))
		ORDER BY
			CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'NameDESC') THEN dg.Name
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'NameASC') THEN dg.Name
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CreatedByDESC') THEN dp.CreatedBy
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CreatedByASC') THEN dp.CreatedBy
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atDESC') THEN dp.created_at
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atASC') THEN dp.created_at
			END ASC
		LIMIT p_RowspPage OFFSET v_OffSet_;

		SELECT
			COUNT(dp.DiscountID) AS totalcount
		FROM tblDiscount dp
		INNER JOIN tblDestinationGroup dg ON dg.DestinationGroupID = dp.DestinationGroupID
		INNER JOIN tblDiscountScheme ds ON ds.DiscountID = dp.DiscountID
		WHERE dp.DiscountPlanID = p_DiscountPlanID
			AND (p_Name ='' OR dg.Name like  CONCAT('%',p_Name,'%'));
	END IF;

	IF p_isExport = 1
	THEN
		
		SELECT   
			dg.Name,
			dp.Service,
			ds.Threshold,
			ds.Discount,
			IF(ds.Unlimited =1 ,'Unlimited','') as Unlimited,
			dp.UpdatedBy,
			dp.updated_at
		FROM tblDiscount dp
		INNER JOIN tblDestinationGroup dg ON dg.DestinationGroupID = dp.DestinationGroupID
		INNER JOIN tblDiscountScheme ds ON ds.DiscountID = dp.DiscountID
		WHERE dp.DiscountPlanID = p_DiscountPlanID
			AND (p_Name ='' OR dg.Name like  CONCAT('%',p_Name,'%'));

	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getDiscountPlan` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getDiscountPlan`(IN `p_CompanyID` INT, IN `p_Name` VARCHAR(50), IN `p_PageNumber` INT, IN `p_RowspPage` INT, IN `p_lSortCol` VARCHAR(50), IN `p_SortOrder` VARCHAR(5), IN `p_isExport` INT)
BEGIN
	DECLARE v_OffSet_ int;
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

	IF p_isExport = 0
	THEN
		SELECT   
			dp.Name,
			dgs.Name as DestinationGroupSet,
			c.Code as Currency,
			dp.UpdatedBy,
			dp.updated_at,
			dp.DiscountPlanID,
			dp.DestinationGroupSetID,
			dp.CurrencyID,
			dp.Description,
			(SELECT adp.DiscountPlanID FROM tblAccountDiscountPlan adp WHERE adp.DiscountPlanID = dp.DiscountPlanID LIMIT 1)as Applied
		FROM tblDiscountPlan dp
		INNER JOIN tblDestinationGroupSet dgs
			ON dgs.DestinationGroupSetID = dp.DestinationGroupSetID
		INNER JOIN tblCurrency c
			ON c.CurrencyId = dp.CurrencyID
		
		WHERE dp.CompanyID = p_CompanyID
			AND (p_Name ='' OR dp.Name like  CONCAT('%',p_Name,'%'))
		ORDER BY
			CASE
					WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'NameDESC') THEN dp.Name
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'NameASC') THEN dp.Name
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CreatedByDESC') THEN dp.CreatedBy
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CreatedByASC') THEN dp.CreatedBy
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atDESC') THEN dp.created_at
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atASC') THEN dp.created_at
			END ASC
		LIMIT p_RowspPage OFFSET v_OffSet_;

		SELECT
			COUNT(dp.DiscountPlanID) AS totalcount
		FROM tblDiscountPlan dp
		WHERE dp.CompanyID = p_CompanyID
			AND (p_Name ='' OR dp.Name like  CONCAT('%',p_Name,'%'));
	END IF;

	IF p_isExport = 1
	THEN
		
		SELECT   
			dp.Name,
			dp.UpdatedBy,
			dp.updated_at,
			dp.Description
		FROM tblDiscountPlan dp
		WHERE dp.CompanyID = p_CompanyID
			AND (p_Name ='' OR dp.Name like  CONCAT('%',p_Name,'%'));

	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getDynamiclinks` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getDynamiclinks`(
	IN `p_CompanyID` INT,
	IN `p_Title` VARCHAR(255),
	IN `p_Currency` INT(11),
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_Export` INT





)
BEGIN
     DECLARE v_OffSet_ int;
     
     SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	      
	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;


	if p_Export = 0
	THEN

    SELECT   
		tblDynamiclink.Title,
		tblDynamiclink.Link,
		tblCurrency.Code as Currency,
		tblDynamiclink.created_at,
		tblDynamiclink.CurrencyID,
		tblDynamiclink.DynamicLinkID
		from tblDynamiclink LEFT JOIN tblCurrency ON tblDynamiclink.CurrencyID = tblCurrency.CurrencyId
		where tblDynamiclink.CompanyID = p_CompanyID
		AND (p_Title ='' OR tblDynamiclink.Title like Concat('%',p_Title,'%'))
		AND (p_Currency ='' OR tblDynamiclink.CurrencyID = p_Currency)
            
        ORDER BY
   
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TitleDESC') THEN tblDynamiclink.Title
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TitleASC') THEN tblDynamiclink.Title
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CurrencyDESC') THEN tblDynamiclink.CurrencyID
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'CurrencyASC') THEN tblDynamiclink.CurrencyID
			END ASC,
			
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atDESC') THEN tblDynamiclink.created_at
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atASC') THEN tblDynamiclink.created_at
			END ASC
			
		LIMIT p_RowspPage OFFSET v_OffSet_;

		SELECT
		COUNT(tblDynamiclink.DynamicLinkID) AS totalcount
		from tblDynamiclink
		where tblDynamiclink.CompanyID = p_CompanyID
		AND (p_Title ='' OR tblDynamiclink.Title like Concat('%',p_Title,'%'))
		AND (p_Currency ='' OR tblDynamiclink.CurrencyID = p_Currency);

	ELSE
	
		SELECT
			tblDynamiclink.Title,
			tblDynamiclink.Link,
			tblCurrency.Code as Currency,
			tblDynamiclink.created_at as CreatedDate
         from tblDynamiclink LEFT JOIN tblCurrency ON tblDynamiclink.CurrencyID = tblCurrency.CurrencyId
			where tblDynamiclink.CompanyID = p_CompanyID
			AND (p_Title ='' OR tblDynamiclink.Title like Concat('%',p_Title,'%'))
			AND (p_Currency ='' OR tblDynamiclink.CurrencyID = p_Currency);

	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
	
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getDynamicTypes` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_getDynamicTypes`(
	IN `p_CompanyID` INT,
	IN `p_FieldName` VARCHAR(50),
	IN `p_FieldDomType` VARCHAR(50),
	IN `p_Active` VARCHAR(1),
	IN `p_Type` VARCHAR(100),
	IN `p_ItemTypeID` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_Export` INT


)
BEGIN
     DECLARE v_OffSet_ int;
     SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	      
	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;


	if p_Export = 0
	THEN

    SELECT   
			tblDynamicFields.DynamicFieldsID,
			IFNULL(tblItemType.title,'All') AS title,
			tblDynamicFields.FieldName,
			tblDynamicFields.FieldDomType,
			tblDynamicFields.created_at,
			tblDynamicFields.Status,
			tblDynamicFields.FieldDescription,
			tblDynamicFields.FieldOrder,			
			tblDynamicFields.FieldSlug,
			tblDynamicFields.Type,
			tblItemType.ItemTypeID,
			tblDynamicFields.Minimum,
			tblDynamicFields.Maximum,	
			tblDynamicFields.DefaultValue,
			tblDynamicFields.SelectVal
            from tblDynamicFields LEFT JOIN telsomespainBilling.tblItemType ON tblDynamicFields.ItemTypeID = tblItemType.ItemTypeID
            where tblDynamicFields.`Type`= p_Type AND tblDynamicFields.CompanyID = p_CompanyID
			AND (p_FieldName ='' OR tblDynamicFields.FieldName like Concat('%',p_FieldName,'%'))
				AND ((p_FieldDomType ='' OR tblDynamicFields.FieldDomType like CONCAT(p_FieldDomType,'%')))
            AND((p_ItemTypeID ='' OR tblItemType.ItemTypeID like CONCAT(p_ItemTypeID,'%')))
            AND((p_Active = '' OR tblDynamicFields.Status = p_Active))
         ORDER BY
         	CASE
                 WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DynamicFieldsIDDESC') THEN tblDynamicFields.DynamicFieldsID
             END DESC,
             CASE
                 WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'DynamicFieldsIDASC') THEN tblDynamicFields.DynamicFieldsID
             END ASC,
             
      		CASE
                 WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'titleDESC') THEN tblItemType.title
             END DESC,
             CASE
                 WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'titleASC') THEN tblItemType.title
             END ASC,
				CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'FieldNameDESC') THEN tblDynamicFields.FieldName
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'FieldNameASC') THEN tblDynamicFields.FieldName
                END ASC,
				CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'FieldDomTypeDESC') THEN tblDynamicFields.FieldDomType
                END DESC,
				CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'FieldDomTypeASC') THEN tblDynamicFields.FieldDomType
                END ASC,
                
				CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atDESC') THEN tblDynamicFields.created_at
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'created_atASC') THEN tblDynamicFields.created_at
                END ASC,
				CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'StatusDESC') THEN tblDynamicFields.Status
                END DESC,
                CASE
                    WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'StatusASC') THEN tblDynamicFields.Status
                END ASC
            LIMIT p_RowspPage OFFSET v_OffSet_;

			SELECT
            COUNT(tblDynamicFields.DynamicFieldsID) AS totalcount
            from tblDynamicFields LEFT JOIN telsomespainBilling.tblItemType ON tblDynamicFields.ItemTypeID = tblItemType.ItemTypeID
            where tblDynamicFields.`Type`= p_Type AND tblDynamicFields.CompanyID = p_CompanyID
			AND (p_FieldName ='' OR tblDynamicFields.FieldName like Concat('%',p_FieldName,'%'))
				AND ((p_FieldDomType ='' OR tblDynamicFields.FieldDomType like CONCAT(p_FieldDomType,'%')))
            AND((p_ItemTypeID ='' OR tblItemType.ItemTypeID like CONCAT(p_ItemTypeID,'%')))
            AND((p_Active = '' OR tblDynamicFields.Status = p_Active));
            

	ELSE

			SELECT
			tblDynamicFields.DynamicFieldsID,
			IFNULL(tblItemType.title,'All') AS title,
			tblDynamicFields.FieldName,
			tblDynamicFields.FieldDomType,
			tblDynamicFields.created_at,
			tblDynamicFields.Status,
			tblDynamicFields.FieldDescription,
			tblDynamicFields.FieldOrder,			
			tblDynamicFields.FieldSlug,
			tblDynamicFields.Type,
			tblItemType.ItemTypeID,
			tblDynamicFields.Minimum,
			tblDynamicFields.Maximum,	
			tblDynamicFields.DefaultValue,
			tblDynamicFields.SelectVal
            from tblDynamicFields LEFT JOIN telsomespainBilling.tblItemType ON tblDynamicFields.ItemTypeID = tblItemType.ItemTypeID
			where tblDynamicFields.`Type`= p_Type AND tblDynamicFields.CompanyID = p_CompanyID
			AND (p_FieldName ='' OR tblDynamicFields.FieldName like Concat('%',p_FieldName,'%'))
				AND ((p_FieldDomType ='' OR tblDynamicFields.FieldDomType like CONCAT(p_FieldDomType,'%')))
            AND((p_ItemTypeID ='' OR tblItemType.ItemTypeID like CONCAT(p_ItemTypeID,'%')))
            AND((p_Active = '' OR tblDynamicFields.Status = p_Active));

	END IF;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
	
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetFileUploadTemplates` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetFileUploadTemplates`(
	IN `p_CompanyID` INT,
	IN `p_Title` VARCHAR(255),
	IN `p_Type` INT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_lSortCol` VARCHAR(50),
	IN `p_SortOrder` VARCHAR(5),
	IN `p_IsExport` INT
)
BEGIN
	DECLARE v_OffSet_ int;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

	IF p_IsExport = 0
	THEN
		SELECT
			t.`Title` AS TemplateName,
			tt.`Title` AS TemplateType,
			t.`created_at`,
			t.`FileUploadTemplateID`
		FROM
			tblFileUploadTemplate t
		LEFT JOIN
			tblFileUploadTemplateType tt ON t.FileUploadTemplateTypeID=tt.FileUploadTemplateTypeID
		WHERE
			t.CompanyID = p_CompanyID AND
			(p_Title IS NULL OR t.Title LIKE REPLACE(p_Title, '*', '%')) AND
			(p_Type IS NULL OR t.FileUploadTemplateTypeID = p_Type)
		ORDER BY
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TitleASC') THEN t.Title
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TitleDESC') THEN t.Title
			END DESC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TypeASC') THEN tt.Title
			END ASC,
			CASE
				WHEN (CONCAT(p_lSortCol,p_SortOrder) = 'TypeDESC') THEN tt.Title
			END DESC
		LIMIT p_RowspPage OFFSET v_OffSet_;

		
		SELECT
			COUNT(t.Title) AS totalcount
		FROM
			tblFileUploadTemplate t
		LEFT JOIN
			tblFileUploadTemplateType tt ON t.FileUploadTemplateTypeID=tt.FileUploadTemplateTypeID
		WHERE
			t.CompanyID = p_CompanyID AND
			(p_Title IS NULL OR t.Title LIKE REPLACE(p_Title, '*', '%')) AND
			(p_Type IS NULL OR t.FileUploadTemplateTypeID = p_Type);

	END IF;

	IF p_IsExport = 1
	THEN
		SELECT
			t.`Title` AS TemplateName,
			tt.`Title` AS TemplateType,
			t.`created_at`
		FROM
			tblFileUploadTemplate t
		LEFT JOIN
			tblFileUploadTemplateType tt ON t.FileUploadTemplateTypeID=tt.FileUploadTemplateTypeID
		WHERE
			t.CompanyID = p_CompanyID;
	END IF;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetFromEmailAddress` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetFromEmailAddress`(
	IN `p_CompanyID` int,
	IN `p_userID` int ,
	IN `p_Ticket` INT,
	IN `p_Admin` INT


)
BEGIN
	DECLARE V_Ticket_Permission int;
	DECLARE V_Ticket_Permission_level int;
	DECLARE V_User_Groups varchar(100);
	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	SELECT 0 INTO V_Ticket_Permission;
	SELECT 0 into V_Ticket_Permission_level;
	IF p_Ticket = 1
	THEN
		IF p_Admin > 0
		THEN
			SELECT 1 INTO V_Ticket_Permission;
		END IF;

		IF p_Admin < 1
		THEN
			SELECT
				count(*) into V_Ticket_Permission
			FROM
				tblUser u
			inner join
				tblUserPermission up on u.UserID = up.UserID
			inner join
				tblResourceCategories tc on up.resourceID = tc.ResourceCategoryID
			WHERE
				tc.ResourceCategoryName = 'Tickets.View.GlobalAccess'  and u.UserID = p_userID;
		END IF;

		IF V_Ticket_Permission > 0
		THEN
			SELECT 1 into V_Ticket_Permission_level;
			IF p_Admin > 0
			THEN
				SELECT DISTINCT GroupReplyAddress as EmailFrom FROM tblTicketGroups where CompanyID = p_CompanyID and GroupEmailStatus = 1 and GroupReplyAddress IS NOT NULL
					UNION ALL
				SELECT  tc.EmailFrom as EmailFrom FROM tblCompany tc where tc.EmailFrom IS NOT NULL AND tc.EmailFrom <> ''
					UNION ALL
				SELECT DISTINCT(tu.EmailAddress) as EmailFrom from tblUser tu where tu.Status=1;
			END IF;
			IF p_Admin < 1
			THEN
				SELECT DISTINCT GroupReplyAddress as EmailFrom FROM tblTicketGroups where CompanyID = p_CompanyID and GroupEmailStatus = 1 and GroupReplyAddress IS NOT NULL
					UNION ALL
				SELECT  tc.EmailFrom as EmailFrom FROM tblCompany tc where tc.EmailFrom IS NOT NULL AND tc.EmailFrom <> ''
					UNION ALL
				SELECT tu.EmailAddress as EmailFrom from tblUser tu where tu.UserID = p_userID and tu.Status=1;
			END IF;
		END IF;

		IF V_Ticket_Permission_level = 0
			THEN
				SELECT 0 into V_Ticket_Permission;
				SELECT
				
				count(*) into V_Ticket_Permission
			FROM
				tblUser u
			inner join
				tblUserPermission up on u.UserID = up.UserID
			inner join
				tblResourceCategories tc on up.resourceID = tc.ResourceCategoryID
			WHERE
				tc.ResourceCategoryName = 'Tickets.View.GroupAccess'  and u.UserID = p_userID;
		END IF;

		IF V_Ticket_Permission > 0 and V_Ticket_Permission_level = 0
		THEN
			SELECT 2 into V_Ticket_Permission_level;

			SELECT GROUP_CONCAT(GroupID SEPARATOR ',') into V_User_Groups FROM tblTicketGroupAgents TGA where TGA.UserID = p_userID;

			IF p_Admin > 0
			THEN
				SELECT DISTINCT GroupReplyAddress as EmailFrom FROM tblTicketGroups where CompanyID = p_CompanyID and GroupEmailStatus = 1 and GroupReplyAddress IS NOT NULL AND FIND_IN_SET(GroupID,V_User_Groups)
					UNION ALL
				SELECT  tc.EmailFrom as EmailFrom FROM tblCompany tc where tc.EmailFrom IS NOT NULL AND tc.EmailFrom <> ''
					UNION ALL
				SELECT DISTINCT(tu.EmailAddress) as EmailFrom from tblUser tu where tu.Status=1;
			END IF;
			IF p_Admin < 1
			THEN
				SELECT DISTINCT GroupReplyAddress as EmailFrom FROM tblTicketGroups where CompanyID = p_CompanyID and GroupEmailStatus = 1 and GroupReplyAddress IS NOT NULL AND FIND_IN_SET(GroupID,V_User_Groups)
					UNION ALL
				SELECT  tc.EmailFrom as EmailFrom FROM tblCompany tc where tc.EmailFrom IS NOT NULL AND tc.EmailFrom <> ''
					UNION ALL
				SELECT tu.EmailAddress as EmailFrom from tblUser tu where tu.UserID = p_userID and tu.Status=1;
			END IF;

		END IF;

		IF V_Ticket_Permission_level = 0
		THEN
			SELECT 0 into V_Ticket_Permission;
			SELECT 3 into V_Ticket_Permission_level;
			IF p_Admin > 0
			THEN
				SELECT DISTINCT TG.GroupReplyAddress as EmailFrom FROM tblTicketGroups TG INNER JOIN tblTickets TT ON TT.Group = TG.GroupID where TG.CompanyID = p_CompanyID and GroupEmailStatus = 1 and TG.GroupReplyAddress IS NOT NULL AND TT.Agent = p_userID
					UNION ALL
				SELECT  tc.EmailFrom as EmailFrom FROM tblCompany tc where tc.EmailFrom IS NOT NULL AND tc.EmailFrom <> ''
					UNION ALL
				SELECT DISTINCT(tu.EmailAddress) as EmailFrom from tblUser tu where tu.Status=1;
			END IF;
			IF p_Admin < 1
			THEN
				SELECT DISTINCT TG.GroupReplyAddress as EmailFrom FROM tblTicketGroups TG INNER JOIN tblTickets TT ON TT.Group = TG.GroupID where TG.CompanyID = p_CompanyID and GroupEmailStatus = 1 and TG.GroupReplyAddress IS NOT NULL AND TT.Agent = p_userID
					UNION ALL
				SELECT  tc.EmailFrom as EmailFrom FROM tblCompany tc where tc.EmailFrom IS NOT NULL AND tc.EmailFrom <> ''
					UNION ALL
				SELECT tu.EmailAddress as EmailFrom from tblUser tu where tu.UserID = p_userID and tu.Status=1;
			END IF;

		END IF;
	END IF;

	IF p_Ticket = 0
	THEN
		IF p_Admin > 0
		THEN
			SELECT  tc.EmailFrom as EmailFrom FROM tblCompany tc where tc.EmailFrom IS NOT NULL AND tc.EmailFrom <> ''
				UNION ALL
			SELECT DISTINCT(tu.EmailAddress) as EmailFrom from tblUser tu where tu.Status=1;
			
		END IF;
		IF p_Admin < 1
		THEN
			SELECT  tc.EmailFrom as EmailFrom FROM tblCompany tc where tc.EmailFrom IS NOT NULL AND tc.EmailFrom <> ''
				UNION ALL
			SELECT tu.EmailAddress as EmailFrom from tblUser tu where tu.UserID = p_userID and tu.Status=1
				UNION ALL
			SELECT tu.EmailAddress as EmailFrom from tblUser tu where tu.Status=1  and AdminUser = 0 and tu.UserID not in ( select UserID from tblUserRole );


		
		END IF;
	END IF;
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_getJobDropdown` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_getJobDropdown`(IN `p_CompanyId` int , IN `p_userId` int , IN `p_isadmin` int , IN `p_reset` int )
BEGIN
   
  SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;  
  
  IF p_reset = 1 
  THEN
    update `tblJob` set `ShowInCounter` = '0' where `CompanyID` = p_CompanyId and `ShowInCounter` = '1';
  END IF;
        select  `tblJob`.`JobID`, `tblJob`.`Title`, `tblJobStatus`.`Title` as Status, `tblJob`.`HasRead`, `tblJob`.`CreatedBy`, `tblJob`.`created_at`, `tblJobType`.`Title` as JobType 
        from `tblJob` inner join `tblJobStatus` on `tblJob`.`JobStatusID` = `tblJobStatus`.`JobStatusID` 
        inner join `tblJobType` on `tblJob`.`JobTypeID` = `tblJobType`.`JobTypeID` 
        where `tblJob`.`CompanyID` = p_CompanyId AND  `tblJob`.JobLoggedUserID = p_userId
        order by `tblJob`.`ShowInCounter` desc, `tblJob`.`updated_at` desc,`tblJob`.JobID desc 
		  limit 10;

	  select count(*) as totalNonVisitedJobs from `tblJob` 
    inner join `tblJobStatus` on `tblJob`.`JobStatusID` = `tblJobStatus`.`JobStatusID` 
    where `tblJob`.`CompanyID` = p_CompanyId and `tblJob`.`ShowInCounter` = '1' and `tblJob`.JobLoggedUserID = p_userId;
    
    

    select count(*) as totalPendingJobs from `tblJob` inner join `tblJobStatus` on `tblJob`.`JobStatusID` = `tblJobStatus`.`JobStatusID` 
    where `tblJobStatus`.`Title` = 'Pending' and `tblJob`.`CompanyID` = p_CompanyId AND 
	`tblJob`.JobLoggedUserID = p_userId;
	
	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
  
    
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetLastRateTableRate` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_GetLastRateTableRate`(IN `p_companyid` INT, IN `p_RateTableId` INT, IN `p_EffectiveDate` datetime)
BEGIN
		SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
	
        SELECT
            Code,
            Description,
            tblRateTableRate.Interval1,
            tblRateTableRate.IntervalN,
			ConnectionFee,
            Rate,
            EffectiveDate
        FROM tblRate
        INNER JOIN tblRateTableRate
            ON tblRateTableRate.RateID = tblRate.RateID
            AND tblRateTableRate.RateTableId = p_RateTableId
        INNER JOIN tblRateTable
            ON tblRateTable.RateTableId = tblRateTableRate.RateTableId
        WHERE		(tblRate.CompanyID = p_companyid)
		AND tblRateTableRate.RateTableId = p_RateTableId
		AND EffectiveDate = p_EffectiveDate;
		
		SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
		
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetLCR` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_GetLCR`(
	IN `p_companyid` INT,
	IN `p_trunkID` INT,
	IN `p_TimezonesID` VARCHAR(50),
	IN `p_codedeckID` INT,
	IN `p_CurrencyID` INT,
	IN `p_code` VARCHAR(50),
	IN `p_Description` VARCHAR(250),
	IN `p_AccountIds` TEXT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_SortOrder` VARCHAR(50),
	IN `p_Preference` INT,
	IN `p_Position` INT,
	IN `p_vendor_block` INT,
	IN `p_groupby` VARCHAR(50),
	IN `p_SelectedEffectiveDate` DATE,
	IN `p_ShowAllVendorCodes` INT,
	IN `p_merge_timezones` INT,
	IN `p_TakePrice` INT,
	IN `p_isExport` INT
)
ThisSP:BEGIN

	DECLARE v_OffSet_ int;

	DECLARE v_Code VARCHAR(50) ;
	DECLARE v_pointer_ int;
	DECLARE v_rowCount_ int;
	DECLARE v_p_code VARCHAR(50);
	DECLARE v_Codlen_ int;
	DECLARE v_position int;
	DECLARE v_p_code__ VARCHAR(50);
	DECLARE v_has_null_position int ;
	DECLARE v_next_position1 VARCHAR(200) ;
	DECLARE v_CompanyCurrencyID_ INT;

	SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

	SET @@session.collation_connection='utf8_unicode_ci';
	SET @@session.character_set_results='utf8';

	-- just for taking codes -

	SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

	DROP TEMPORARY TABLE IF EXISTS tmp_VendorRate_stage_;
	CREATE TEMPORARY TABLE tmp_VendorRate_stage_ (
		RowCode VARCHAR(50) ,
		AccountId INT ,
		BlockingId INT DEFAULT 0,
		BlockingCountryId INT DEFAULT 0,
		AccountName VARCHAR(100) ,
		Code VARCHAR(50) ,
		Rate DECIMAL(18,6) ,
		ConnectionFee DECIMAL(18,6) ,
		EffectiveDate DATETIME ,
		Description VARCHAR(255),
		Preference INT,
		MaxMatchRank int ,
		prev_prev_RowCode VARCHAR(50),
		prev_AccountID int
	)
	;

	DROP TEMPORARY TABLE IF EXISTS tmp_VendorRate_stage2_;
	CREATE TEMPORARY TABLE tmp_VendorRate_stage2_ (
		RowCode VARCHAR(50) ,
		AccountId INT ,
		BlockingId INT DEFAULT 0,
		AccountName VARCHAR(100) ,
		Code VARCHAR(50) ,
		Rate DECIMAL(18,6) ,
		ConnectionFee DECIMAL(18,6) ,
		EffectiveDate DATETIME ,
		Description VARCHAR(255),
		Preference INT,
		MaxMatchRank int ,
		prev_prev_RowCode VARCHAR(50),
		prev_AccountID int
	)
	;

	DROP TEMPORARY TABLE IF EXISTS tmp_VendorRate_;
	CREATE TEMPORARY TABLE tmp_VendorRate_ (
		AccountId INT ,
		BlockingId INT DEFAULT 0,
		BlockingCountryId INT DEFAULT 0,
		AccountName VARCHAR(100) ,
		Code VARCHAR(50) ,
		Rate DECIMAL(18,6) ,
		ConnectionFee DECIMAL(18,6) ,
		EffectiveDate DATETIME ,
		Description VARCHAR(255),
		Preference INT,
		RowCode VARCHAR(50)
	)
	;

	DROP TEMPORARY TABLE IF EXISTS tmp_final_VendorRate_;
	CREATE TEMPORARY TABLE tmp_final_VendorRate_ (
		AccountId INT ,
		BlockingId INT DEFAULT 0,
		BlockingCountryId INT DEFAULT 0,
		AccountName VARCHAR(100) ,
		Code VARCHAR(50) ,
		Rate DECIMAL(18,6) ,
		ConnectionFee DECIMAL(18,6) ,
		EffectiveDate DATETIME ,
		Description VARCHAR(255),
		Preference INT,
		RowCode VARCHAR(50),
		FinalRankNumber int
	)
	;

	-- Loop codes

	DROP TEMPORARY TABLE IF EXISTS tmp_search_code_;
	CREATE TEMPORARY TABLE tmp_search_code_ (
		Code  varchar(50),
		INDEX Index1 (Code)
	);

	-- searched codes.

	DROP TEMPORARY TABLE IF EXISTS tmp_code_;
	CREATE TEMPORARY TABLE tmp_code_ (
		RowCode  varchar(50),
		Code  varchar(50),
		RowNo int,
		INDEX Index1 (Code)
	);


	DROP TEMPORARY TABLE IF EXISTS tmp_all_code_;
	CREATE TEMPORARY TABLE tmp_all_code_ (
		RowCode  varchar(50),
		Code  varchar(50),
		RowNo int,
		INDEX Index2 (Code)
	)
	;


	DROP TEMPORARY TABLE IF EXISTS tmp_VendorCurrentRates_;
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_VendorCurrentRates_(
		AccountId int,
		BlockingId INT DEFAULT 0,
		BlockingCountryId INT DEFAULT 0,
		AccountName varchar(200),
		Code varchar(50),
		Description varchar(200),
		Rate DECIMAL(18,6) ,
		ConnectionFee DECIMAL(18,6) ,
		EffectiveDate date,
		TrunkID int,
		CountryID int,
		RateID int,
		Preference int,
		INDEX IX_Code (Code)
	)
	;

	DROP TEMPORARY TABLE IF EXISTS tmp_VendorCurrentRates1_;
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_VendorCurrentRates1_(
		AccountId int,
		BlockingId INT DEFAULT 0,
		BlockingCountryId INT DEFAULT 0,
		AccountName varchar(200),
		Code varchar(50),
		Description varchar(200),
		Rate DECIMAL(18,6) ,
		ConnectionFee DECIMAL(18,6) ,
		EffectiveDate date,
		TrunkID int,
		CountryID int,
		RateID int,
		Preference int,
		INDEX IX_Code (Code),
		INDEX tmp_VendorCurrentRates_AccountId (`AccountId`,`TrunkID`,`RateId`,`EffectiveDate`)
	)
	;

	DROP TEMPORARY TABLE IF EXISTS tmp_VendorRateByRank_;
	CREATE TEMPORARY TABLE tmp_VendorRateByRank_ (
		AccountId INT ,
		BlockingId INT DEFAULT 0,
		BlockingCountryId INT DEFAULT 0,
		AccountName VARCHAR(100) ,
		Code VARCHAR(50) ,
		Rate DECIMAL(18,6) ,
		ConnectionFee DECIMAL(18,6) ,
		EffectiveDate DATETIME ,
		Description VARCHAR(255),
		Preference INT,
		rankname INT,
		INDEX IX_Code (Code,rankname)
	)
	;

	SELECT CurrencyId INTO v_CompanyCurrencyID_ FROM  tblCompany WHERE CompanyID = p_companyid;

	-- Search code based on p_code
	IF (p_ShowAllVendorCodes = 1) THEN

		  insert into tmp_search_code_
		  SELECT  DISTINCT LEFT(f.Code, x.RowNo) as loopCode FROM (
					  SELECT @RowNo  := @RowNo + 1 as RowNo
					  FROM mysql.help_category
					  ,(SELECT @RowNo := 0 ) x
					  limit 15
		  ) x
		 -- INNER JOIN tblRate AS f          ON f.CompanyID = p_companyid  AND f.CodeDeckId = p_codedeckID
		  INNER JOIN (
						SELECT distinct Code , Description from tblRate
						WHERE CompanyID = p_companyid
							AND ( CHAR_LENGTH(RTRIM(p_code)) = 0  OR Code LIKE REPLACE(p_code,'*', '%') )
							AND ( p_Description = ''  OR Description LIKE REPLACE(p_Description,'*', '%') )
		  ) f
		  ON x.RowNo   <= LENGTH(f.Code)
		  order by loopCode   desc;


	ELSE

	insert into tmp_search_code_
		SELECT  DISTINCT LEFT(f.Code, x.RowNo) as loopCode FROM (
				SELECT @RowNo  := @RowNo + 1 as RowNo
				FROM mysql.help_category
					,(SELECT @RowNo := 0 ) x
				limit 15
			) x
			INNER JOIN tblRate AS f
				ON f.CompanyID = p_companyid  AND f.CodeDeckId = p_codedeckID
					 AND ( CHAR_LENGTH(RTRIM(p_code)) = 0  OR f.Code LIKE REPLACE(p_code,'*', '%') )
					 AND ( p_Description = ''  OR f.Description LIKE REPLACE(p_Description,'*', '%') )
					 AND x.RowNo   <= LENGTH(f.Code)
		order by loopCode   desc;

	END IF;
	-- distinct vendor rates

		/* 	#4.18
			only one dynamic query based on condition
			no need to create seperate query for seperate condition
		*/

		SET @num := 0, @AccountID := '', @TrunkID := '', @RateID := '';

		SET @stm_show_all_vendor_codes1 = CONCAT("INNER JOIN tmp_search_code_ SplitCode ON tblRate.Code = SplitCode.Code");
		SET @stm_show_all_vendor_codes2 = CONCAT('( CHAR_LENGTH(RTRIM("',p_code,'")) = 0 OR tblRate.Code LIKE REPLACE("',p_code,'","*", "%") )
													AND ("',p_Description,'"="" OR tblRate.Description LIKE REPLACE("',p_Description,'","*","%"))
													AND ');

		SET @stm = CONCAT('
			INSERT INTO tmp_VendorCurrentRates1_
			',
			IF (p_merge_timezones = 1,"
				Select DISTINCT
					AccountId,
					BlockingId,
					BlockingCountryId,
					AccountName,
					Code,
					Description,
					Rate,
					ConnectionFee,
					EffectiveDate,
					TrunkID,
					CountryID,
					RateID,
					Preference
				FROM (
			",""),'

				Select DISTINCT
					AccountId,
					BlockingId,
					BlockingCountryId ,
					AccountName,
					Code,
					Description,
					Rate,
					ConnectionFee,
					EffectiveDate,
					TrunkID,
					CountryID,
					RateID,
					Preference
					',IF (p_merge_timezones = 1,",
						@num := if(@AccountID = AccountID AND @TrunkID = TrunkID AND @RateID = RateID, @num + 1, 1) as row_number,
						@AccountID := AccountID,
						@TrunkID := TrunkID,
						@RateID := RateID
					",""),'
				FROM (
					 SELECT distinct tblVendorRate.AccountId,
						IFNULL(blockCode.VendorBlockingId, 0) AS BlockingId,
						IFNULL(blockCountry.CountryId, 0)  as BlockingCountryId,
						tblAccount.AccountName,
						tblRate.Code,
						tblRate.Description,
						CASE WHEN  tblAccount.CurrencyId = ',p_CurrencyID,'
						THEN
							tblVendorRate.Rate
						WHEN  ',v_CompanyCurrencyID_,' = ',p_CurrencyID,'
						THEN
						(
							( tblVendorRate.rate  / (Select Value from tblCurrencyConversion where tblCurrencyConversion.CurrencyId = tblAccount.CurrencyId and  CompanyID = ',p_companyid,' ) )
						)
						ELSE
						(
							-- Convert to base currrncy and x by RateGenerator Exhange
							(Select Value from tblCurrencyConversion where tblCurrencyConversion.CurrencyId = ',p_CurrencyID,' and  CompanyID = ',p_companyid,' )
							* (tblVendorRate.rate  / (Select Value from tblCurrencyConversion where tblCurrencyConversion.CurrencyId = tblAccount.CurrencyId and  CompanyID = ',p_companyid,' ))
						)
						END as Rate,
						ConnectionFee,
						DATE_FORMAT (tblVendorRate.EffectiveDate, "%Y-%m-%d") AS EffectiveDate, tblVendorRate.TrunkID, tblRate.CountryID, tblRate.RateID,IFNULL(vp.Preference, 5) AS Preference
					FROM
						tblVendorRate
					Inner join tblVendorTrunk vt on vt.CompanyID = ',p_companyid,' AND vt.AccountID = tblVendorRate.AccountID and vt.Status =  1 and vt.TrunkID =  ',p_trunkID,'
					INNER JOIN tblAccount   ON  tblAccount.CompanyID = ',p_companyid,' AND tblVendorRate.AccountId = tblAccount.AccountID and tblAccount.IsVendor = 1
					INNER JOIN tblRate ON tblRate.CompanyID = ',p_companyid,' AND    tblVendorRate.RateId = tblRate.RateID   AND vt.CodeDeckId = tblRate.CodeDeckId
					',
					IF (p_ShowAllVendorCodes = 1,"",@stm_show_all_vendor_codes1)
					,'
					LEFT JOIN tblVendorPreference vp
						ON vp.AccountId = tblVendorRate.AccountId
						AND vp.TrunkID = tblVendorRate.TrunkID
						AND vp.TimezonesID = tblVendorRate.TimezonesID
						AND vp.RateId = tblVendorRate.RateId
					LEFT OUTER JOIN tblVendorBlocking AS blockCode
						ON tblVendorRate.RateId = blockCode.RateId
						AND tblVendorRate.AccountId = blockCode.AccountId
						AND tblVendorRate.TrunkID = blockCode.TrunkID
						AND tblVendorRate.TimezonesID = blockCode.TimezonesID
					LEFT OUTER JOIN tblVendorBlocking AS blockCountry
						ON tblRate.CountryID = blockCountry.CountryId
						AND tblVendorRate.AccountId = blockCountry.AccountId
						AND tblVendorRate.TrunkID = blockCountry.TrunkID
						AND tblVendorRate.TimezonesID = blockCountry.TimezonesID
					WHERE
						',
						IF (p_ShowAllVendorCodes = 1,@stm_show_all_vendor_codes2,"")
						,'
						( EffectiveDate <= DATE("',p_SelectedEffectiveDate,'") )
						AND ( tblVendorRate.EndDate IS NULL OR  tblVendorRate.EndDate > Now() )   -- rate should not end Today
						AND ("',p_AccountIds,'"="" OR FIND_IN_SET(tblAccount.AccountID,"',p_AccountIds,'") != 0 )
						AND tblAccount.IsVendor = 1
						AND tblAccount.Status = 1
						AND tblAccount.CurrencyId is not NULL
						AND tblVendorRate.TrunkID = ',p_trunkID,'
						AND (
							(',p_merge_timezones,' = 0 AND tblVendorRate.TimezonesID = "',p_TimezonesID,'") OR
							(',p_merge_timezones,' = 1 AND FIND_IN_SET(tblVendorRate.TimezonesID, "',p_TimezonesID,'"))
						)
						AND
						(
							',p_vendor_block,' = 1 OR
							(
								',p_vendor_block,' = 0 AND   (
									blockCode.RateId IS NULL  AND blockCountry.CountryId IS NULL
								)
							)
						)
						-- AND blockCode.RateId IS NULL
						-- AND blockCountry.CountryId IS NULL
					',
					IF (p_merge_timezones = 1,CONCAT("ORDER BY AccountID, TrunkID, RateID, Rate ",IF(p_TakePrice=1,"DESC","ASC")),"")
					,'
				) tbl
			',
			IF (p_merge_timezones = 1,") AS x WHERE x.row_number <= 1","")
			,'
			order by Code asc;
		');

	--	select @stm;
	--	leave ThisSP;

	PREPARE stmt FROM @stm;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;

	-- filter by Effective Dates

	IF p_groupby = 'description' THEN

	INSERT INTO tmp_VendorCurrentRates_
		Select AccountId,max(BlockingId),max(BlockingCountryId) ,max(AccountName),max(Code),Description, MAX(Rate),max(ConnectionFee),max(EffectiveDate),max(TrunkID),max(CountryID),max(RateID),max(Preference)
		FROM (
					 SELECT * ,
						 @row_num := IF(@prev_AccountId = AccountID AND @prev_TrunkID = TrunkID AND @prev_Description = Description AND @prev_EffectiveDate >= EffectiveDate, @row_num + 1, 1) AS RowID,
						 @prev_AccountId := AccountID,
						 @prev_TrunkID := TrunkID,
						 @prev_Description := Description,
						 @prev_EffectiveDate := EffectiveDate
					 FROM tmp_VendorCurrentRates1_
						 ,(SELECT @row_num := 1,  @prev_AccountId := '',@prev_TrunkID := '', @prev_RateId := '', @prev_EffectiveDate := '') x
					 ORDER BY AccountId, TrunkID, Description, EffectiveDate DESC
				 ) tbl
		WHERE RowID = 1
		group BY AccountId, TrunkID, Description
		order by Description asc;

	ELSE

	INSERT INTO tmp_VendorCurrentRates_
		Select AccountId,BlockingId,BlockingCountryId ,AccountName,Code,Description, Rate,ConnectionFee,EffectiveDate,TrunkID,CountryID,RateID,Preference
		FROM (
					 SELECT * ,
						 @row_num := IF(@prev_AccountId = AccountID AND @prev_TrunkID = TrunkID AND @prev_RateId = RateID AND @prev_EffectiveDate >= EffectiveDate, @row_num + 1, 1) AS RowID,
						 @prev_AccountId := AccountID,
						 @prev_TrunkID := TrunkID,
						 @prev_RateId := RateID,
						 @prev_EffectiveDate := EffectiveDate
					 FROM tmp_VendorCurrentRates1_
						 ,(SELECT @row_num := 1,  @prev_AccountId := '',@prev_TrunkID := '', @prev_RateId := '', @prev_EffectiveDate := '') x
					 ORDER BY AccountId, TrunkID, RateId, EffectiveDate DESC
				 ) tbl
		WHERE RowID = 1
		order by Code asc;

	END IF;
	-- Collect Codes pressent in vendor Rates from above query.
	/*
		   9372     9372    1
		   9372     937     2
		   9372     93      3
		   9372     9       4

*/

	-- ### change
	IF p_ShowAllVendorCodes = 1 THEN

			insert into tmp_all_code_ (RowCode,Code,RowNo)
			select RowCode , loopCode,RowNo
			from (
				 select   RowCode , loopCode,
					@RowNo := ( CASE WHEN ( @prev_Code = tbl1.RowCode  ) THEN @RowNo + 1
										 ELSE 1
							END

							)      as RowNo,
					 @prev_Code := tbl1.RowCode
					from (
					SELECT distinct f.Code as RowCode, LEFT(f.Code, x.RowNo) as loopCode FROM (
							SELECT @RowNo  := @RowNo + 1 as RowNo
							FROM mysql.help_category
								,(SELECT @RowNo := 0 ) x
							limit 15
						) x
						INNER JOIN tmp_search_code_ AS f
							ON  x.RowNo   <= LENGTH(f.Code)
									AND ( CHAR_LENGTH(RTRIM(p_code)) = 0  OR Code LIKE REPLACE(p_code,'*', '%') )
						INNER JOIN tblRate as tr on f.Code=tr.Code -- AND tr.CodeDeckId=p_codedeckID
							order by RowCode desc,  LENGTH(loopCode) DESC
						) tbl1
					, ( Select @RowNo := 0 ) x
				 ) tbl order by RowCode desc,  LENGTH(loopCode) DESC ;


	ELSE

		insert into tmp_all_code_ (RowCode,Code,RowNo)
			select RowCode , loopCode,RowNo
			from (
				 select   RowCode , loopCode,
					@RowNo := ( CASE WHEN ( @prev_Code = tbl1.RowCode  ) THEN @RowNo + 1
										 ELSE 1
							END

							)      as RowNo,
					 @prev_Code := tbl1.RowCode
					from (
					SELECT distinct f.Code as RowCode, LEFT(f.Code, x.RowNo) as loopCode FROM (
							SELECT @RowNo  := @RowNo + 1 as RowNo
							FROM mysql.help_category
								,(SELECT @RowNo := 0 ) x
							limit 15
						) x
						INNER JOIN tmp_search_code_ AS f
							ON  x.RowNo   <= LENGTH(f.Code)
									AND ( CHAR_LENGTH(RTRIM(p_code)) = 0  OR Code LIKE REPLACE(p_code,'*', '%') )
						INNER JOIN tblRate as tr on f.Code=tr.Code AND tr.CodeDeckId=p_codedeckID
							order by RowCode desc,  LENGTH(loopCode) DESC
						) tbl1
					, ( Select @RowNo := 0 ) x
				 ) tbl order by RowCode desc,  LENGTH(loopCode) DESC ;

	END IF;

	IF p_Preference = 1 THEN

		-- Sort by Preference

		INSERT IGNORE INTO tmp_VendorRateByRank_
			SELECT
				AccountID,
				BlockingId ,
				BlockingCountryId,
				AccountName,
				Code,
				Rate,
				ConnectionFee,
				EffectiveDate,
				Description,
				Preference,
				preference_rank
			FROM (SELECT
							AccountID,
							BlockingId ,
							BlockingCountryId,
							AccountName,
							Code,
							Rate,
							ConnectionFee,
							EffectiveDate,
							Description,
							Preference,
							CASE WHEN p_groupby = 'description' THEN
								@preference_rank := CASE WHEN (@prev_Description     = Description AND @prev_Preference > Preference  ) THEN @preference_rank + 1
																	WHEN (@prev_Description     = Description AND @prev_Preference = Preference AND @prev_Rate < Rate) THEN @preference_rank + 1
																	WHEN (@prev_Description    = Description AND @prev_Preference = Preference AND @prev_Rate = Rate) THEN @preference_rank
																	ELSE 1
															END
							ELSE
								@preference_rank := CASE WHEN (@prev_Code     = Code AND @prev_Preference > Preference  ) THEN @preference_rank + 1
																	WHEN (@prev_Code     = Code AND @prev_Preference = Preference AND @prev_Rate < Rate) THEN @preference_rank + 1
																	WHEN (@prev_Code    = Code AND @prev_Preference = Preference AND @prev_Rate = Rate) THEN @preference_rank
																	ELSE 1
																	END
							END AS preference_rank,

							@prev_Code := Code,
							@prev_Description := Description,
							@prev_Preference := IFNULL(Preference, 5),
							@prev_Rate := Rate
						FROM tmp_VendorCurrentRates_ AS preference,
							(SELECT @preference_rank := 0 , @prev_Code := ''  , @prev_Description := ''  , @prev_Preference := 5,  @prev_Rate := 0) x
						ORDER BY
								CASE WHEN p_groupby = 'description' THEN
									preference.Description
								ELSE
									 preference.Code
								END ASC ,
							  preference.Preference DESC, preference.Rate ASC,preference.AccountId ASC
					 ) tbl
			WHERE p_isExport = 1 OR (p_isExport = 0 AND preference_rank <= p_Position)
			ORDER BY Code, preference_rank;

	ELSE

		-- Sort by Rate

		INSERT IGNORE INTO tmp_VendorRateByRank_
			SELECT
				AccountID,
				BlockingId ,
				BlockingCountryId,
				AccountName,
				Code,
				Rate,
				ConnectionFee,
				EffectiveDate,
				Description,
				Preference,
				RateRank
			FROM (SELECT
							AccountID,
							BlockingId ,
							BlockingCountryId,
							AccountName,
							Code,
							Rate,
							ConnectionFee,
							EffectiveDate,
							Description,
							Preference,
							CASE WHEN p_groupby = 'description' THEN
							@rank := CASE WHEN (@prev_Description    = Description AND @prev_Rate < Rate) THEN @rank + 1
											 WHEN (@prev_Description    = Description AND @prev_Rate = Rate) THEN @rank
											 ELSE 1
											 END
							ELSE
							@rank := CASE WHEN (@prev_Code    = Code AND @prev_Rate < Rate) THEN @rank + 1
											 WHEN (@prev_Code    = Code AND @prev_Rate = Rate) THEN @rank
											 ELSE 1
											 END
							END
								AS RateRank,
							@prev_Code := Code,
							@prev_Description := Description,
							@prev_Rate := Rate
						FROM tmp_VendorCurrentRates_ AS rank,
							(SELECT @rank := 0 , @prev_Code := '' ,  @prev_Description := '' , @prev_Rate := 0) f
						ORDER BY
							CASE WHEN p_groupby = 'description' THEN
								rank.Description
							ELSE
								 rank.Code
							END ,
							rank.Rate,rank.AccountId

						) tbl
			WHERE p_isExport = 1 OR (p_isExport = 0 AND RateRank <= p_Position)
			ORDER BY Code, RateRank;

	END IF;

	-- --------- Split Logic ----------
	/* DESC             MaxMatchRank 1  MaxMatchRank 2
923 Pakistan :       *923 V1          92 V1
923 Pakistan :       *92 V2            -

now take only where  MaxMatchRank =  1
*/


	DROP TEMPORARY TABLE IF EXISTS tmp_VendorRate_stage_1;
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_VendorRate_stage_1 as (select * from tmp_VendorRate_stage_);

	-- ### change v 4.17
	IF p_ShowAllVendorCodes = 1 THEN

		 insert ignore into tmp_VendorRate_stage_1 (
			 RowCode,
			Description ,
			AccountId ,
			AccountName ,
			Code ,
			Rate ,
			ConnectionFee,
			EffectiveDate ,
			Preference
			)
			 SELECT
			  distinct
			 RowCode,
			Description ,
			AccountId ,
			AccountName ,
			Code ,
			Rate ,
			ConnectionFee,
			EffectiveDate ,
			Preference

			from (
					select
						CASE WHEN (tr.Code is not null OR tr.Code like concat(v.Code,'%')) THEN
								tr.Code
						ELSE
								v.Code
						END 	as RowCode,
						CASE WHEN (tr.Code is not null OR tr.Code like concat(v.Code,'%')) THEN
								tr.Description
						ELSE
							concat(v.Description,'*')
						END
						as Description,
						v.AccountId ,
						v.AccountName ,
						v.Code ,
						v.Rate ,
						v.ConnectionFee,
						v.EffectiveDate ,
						v.Preference
					  FROM tmp_VendorRateByRank_ v
					  left join  tmp_all_code_ 		SplitCode   on v.Code = SplitCode.Code

					  LEFT JOIN (	select Code,Description from tblRate where CodeDeckId=p_codedeckID AND
									   ( CHAR_LENGTH(RTRIM(p_code)) = 0  OR Code LIKE REPLACE(p_code,'*', '%') )
								  AND ( p_Description = ''  OR Description LIKE REPLACE(p_Description,'*', '%') )
								) tr on tr.Code=SplitCode.Code
					  where  SplitCode.Code is not null and (p_isExport = 1 OR (p_isExport = 0 AND rankname <= p_Position))

				  ) tmp
				order by AccountID,RowCode desc ,LENGTH(RowCode), Code desc, LENGTH(Code)  desc;

	ELSE

	insert ignore into tmp_VendorRate_stage_1 (
		RowCode,
		AccountId ,
		BlockingId,
		BlockingCountryId,
		AccountName ,
		Code ,
		Rate ,
		ConnectionFee,
		EffectiveDate ,
		Description ,
		Preference
	)
		SELECT
			distinct
			RowCode,
			v.AccountId ,
			v.BlockingId,
			v.BlockingCountryId,
			v.AccountName ,
			v.Code ,
			v.Rate ,
			v.ConnectionFee,
			v.EffectiveDate ,
			tr.Description,
			-- (select Description from tblRate where tblRate.Code =RowCode AND  tblRate.CodeDeckId=p_codedeckID ) as Description ,
			v.Preference
		FROM tmp_VendorRateByRank_ v
			left join  tmp_all_code_ SplitCode   on v.Code = SplitCode.Code
			inner join tblRate tr  on  RowCode = tr.Code AND  tr.CodeDeckId=p_codedeckID
		where  SplitCode.Code is not null and (p_isExport = 1 OR (p_isExport = 0 AND rankname <= p_Position))
		order by AccountID,SplitCode.RowCode desc ,LENGTH(SplitCode.RowCode), v.Code desc, LENGTH(v.Code)  desc;

	END IF;

	insert ignore into tmp_VendorRate_stage_
		SELECT
			distinct
			RowCode,
			v.AccountId ,
			v.BlockingId,
			v.BlockingCountryId,
			v.AccountName ,
			v.Code ,
			v.Rate ,
			v.ConnectionFee,
			v.EffectiveDate ,
			v.Description ,
			v.Preference,
			@rank := ( CASE WHEN( @prev_AccountID = v.AccountId  and @prev_RowCode     = RowCode   )
				THEN  @rank + 1
								 ELSE 1
								 END
			) AS MaxMatchRank,
			@prev_RowCode := RowCode	 ,
			@prev_AccountID := v.AccountId
		FROM tmp_VendorRate_stage_1 v
			, (SELECT  @prev_RowCode := '',  @rank := 0 , @prev_Code := '' , @prev_AccountID := Null) f
		order by AccountID,RowCode desc ;



	IF p_groupby = 'description' THEN

		insert ignore into tmp_VendorRate_
			select
			distinct
			AccountId ,
			max(BlockingId) ,
			max(BlockingCountryId),
			max(AccountName) ,
			max(Code) ,
			max(Rate) ,
			max(ConnectionFee),
			max(EffectiveDate) ,
			Description ,
			max(Preference),
			max(RowCode)
		from tmp_VendorRate_stage_
		where MaxMatchRank = 1
		group by AccountId,Description
		order by AccountId,Description asc;

	ELSE

		insert ignore into tmp_VendorRate_
			select
				distinct
				AccountId ,
				BlockingId ,
				BlockingCountryId,
				AccountName ,
				Code ,
				Rate ,
				ConnectionFee,
				EffectiveDate ,
				Description ,
				Preference,
				RowCode
			from tmp_VendorRate_stage_
			where MaxMatchRank = 1
			order by RowCode desc;
	END IF;






	IF( p_Preference = 0 )
	THEN

		IF p_groupby = 'description' THEN
			/* group by description when preference off */

			insert into tmp_final_VendorRate_
				SELECT
					AccountId ,
					(CASE WHEN (select COUNT(*) from tmp_VendorCurrentRates1_ where tmp_VendorCurrentRates1_.AccountId=tbl1.AccountId AND tmp_VendorCurrentRates1_.Description=tbl1.Description AND BlockingId=0) > 0 THEN 0 ELSE 1 END) AS  BlockingId,
					-- (CASE WHEN (select COUNT(*) from tmp_VendorCurrentRates1_ where tmp_VendorCurrentRates1_.AccountId=tbl1.AccountId AND tmp_VendorCurrentRates1_.Description=tbl1.Description AND BlockingId=0) > 0 THEN 0 ELSE 1 END) AS  BlockingId,
					BlockingCountryId,
					AccountName ,
					Code ,
					Rate ,
					ConnectionFee,
					EffectiveDate ,
					Description ,
					Preference,
					RowCode,
					FinalRankNumber
				from
					(
						SELECT
							AccountId ,
							BlockingId,
							BlockingCountryId,
							AccountName ,
							Code ,
							Rate ,
							ConnectionFee,
							EffectiveDate ,
							Description ,
							Preference,
							RowCode,
							@rank := CASE WHEN (@prev_Description    = Description AND  @prev_Rate <  Rate ) THEN @rank+1
										 WHEN (@prev_Description    = Description AND  @prev_Rate = Rate ) THEN @rank
										 ELSE
											 1
										 END
							AS FinalRankNumber,
							@prev_Description  := Description,
							@prev_Rate  := Rate
						from tmp_VendorRate_
							,( SELECT @rank := 0 , @prev_Description := '' , @prev_Rate := 0 ) x
						order by Description,Rate,AccountId ASC

					) tbl1
				where
					p_isExport = 1 OR (p_isExport = 0 AND FinalRankNumber <= p_Position);
		ELSE
				/* group by code when preference off */

			insert into tmp_final_VendorRate_
				SELECT
					AccountId ,
					BlockingId ,
					BlockingCountryId,
					AccountName ,
					Code ,
					Rate ,
					ConnectionFee,
					EffectiveDate ,
					Description ,
					Preference,
					RowCode,
					FinalRankNumber
				from
					(
						SELECT
							AccountId ,
							BlockingId ,
							BlockingCountryId,
							AccountName ,
							Code ,
							Rate ,
							ConnectionFee,
							EffectiveDate ,
							Description ,
							Preference,
							RowCode,
							@rank := CASE WHEN ( @prev_RowCode     = RowCode AND @prev_Rate <  Rate ) THEN @rank+1
									 WHEN ( @prev_RowCode    = RowCode AND @prev_Rate = Rate ) THEN @rank
									 ELSE
										 1
									 END
							AS FinalRankNumber,
							@prev_RowCode  := RowCode,
							@prev_Rate  := Rate
						from tmp_VendorRate_
							,( SELECT @rank := 0 , @prev_RowCode := '' , @prev_Rate := 0 ) x
						order by RowCode,Rate,AccountId ASC

					) tbl1
				where
					p_isExport = 1 OR (p_isExport = 0 AND FinalRankNumber <= p_Position);

		END IF;

	ELSE

		IF p_groupby = 'description' THEN
			/* group by description when preference on */
			insert into tmp_final_VendorRate_
				SELECT
					AccountId ,
					(CASE WHEN (select COUNT(*) from tmp_VendorCurrentRates1_ where tmp_VendorCurrentRates1_.AccountId=tbl1.AccountId AND tmp_VendorCurrentRates1_.Description=tbl1.Description AND BlockingId=0) > 0 THEN 0 ELSE 1 END) AS  BlockingId,
					-- (CASE WHEN (select COUNT(*) from tmp_VendorCurrentRates1_ where tmp_VendorCurrentRates1_.AccountId=AccountId AND tmp_VendorCurrentRates1_.Description=Description AND BlockingId=0) > 0 THEN 0 ELSE 1 END) AS  BlockingId,
					BlockingCountryId,
					AccountName ,
					Code ,
					Rate ,
					ConnectionFee,
					EffectiveDate ,
					Description ,
					Preference,
					RowCode,
					FinalRankNumber
				from
					(
						SELECT
							AccountId ,
							BlockingId,
							BlockingCountryId,
							AccountName ,
							Code ,
							Rate ,
							ConnectionFee,
							EffectiveDate ,
							Description ,
							Preference,
							RowCode,
							@preference_rank := CASE WHEN (@prev_Description     = Description AND @prev_Preference > Preference  )   THEN @preference_rank + 1
																	WHEN (@prev_Description     = Description AND @prev_Preference = Preference AND @prev_Rate < Rate) THEN @preference_rank + 1
																	WHEN (@prev_Description    = Description AND @prev_Preference = Preference AND @prev_Rate = Rate) THEN @preference_rank
																	ELSE 1 END AS FinalRankNumber,
							@prev_Description := Description,
							@prev_Preference := Preference,
							@prev_Rate := Rate
						from tmp_VendorRate_
							,(SELECT @preference_rank := 0 , @prev_Description := ''  , @prev_Preference := 5,  @prev_Rate := 0) x
						order by Description ASC ,Preference DESC ,Rate ASC ,AccountId ASC

					) tbl1
				where
					p_isExport = 1 OR (p_isExport = 0 AND FinalRankNumber <= p_Position);
		ELSE
				/* group by code when preference on */
			insert into tmp_final_VendorRate_
				SELECT
					AccountId ,
					BlockingId ,
					BlockingCountryId,
					AccountName ,
					Code ,
					Rate ,
					ConnectionFee,
					EffectiveDate ,
					Description ,
					Preference,
					RowCode,
					FinalRankNumber
				from
					(
						SELECT
							AccountId ,
							BlockingId ,
							BlockingCountryId,
							AccountName ,
							Code ,
							Rate ,
							ConnectionFee,
							EffectiveDate ,
							Description ,
							Preference,
							RowCode,
							@preference_rank := CASE WHEN (@prev_Code     = RowCode AND @prev_Preference > Preference  )   THEN @preference_rank + 1
																	WHEN (@prev_Code     = RowCode AND @prev_Preference = Preference AND @prev_Rate < Rate) THEN @preference_rank + 1
																	WHEN (@prev_Code    = RowCode AND @prev_Preference = Preference AND @prev_Rate = Rate) THEN @preference_rank
																	ELSE 1 END AS FinalRankNumber,
							@prev_Code := RowCode,
							@prev_Preference := Preference,
							@prev_Rate := Rate
						from tmp_VendorRate_
							,(SELECT @preference_rank := 0 , @prev_Code := ''  , @prev_Preference := 5,  @prev_Rate := 0) x
						order by RowCode ASC ,Preference DESC ,Rate ASC ,AccountId ASC

					) tbl1
				where
					p_isExport = 1 OR (p_isExport = 0 AND FinalRankNumber <= p_Position);
		END IF;

	END IF;


	SET @stm_columns = "";

	-- if not export then columns must be max 10
	IF p_isExport = 0 AND p_Position > 10 THEN
		SET p_Position = 10;
	END IF;

	-- if export then all columns
	IF p_isExport = 1 THEN
		SELECT MAX(FinalRankNumber) INTO p_Position FROM tmp_final_VendorRate_;
	END IF;

	-- columns loop 5,10,50,...
	SET v_pointer_=1;
	WHILE v_pointer_ <= p_Position
	DO

		IF (p_isExport = 0)
		THEN
			SET @stm_columns = CONCAT(@stm_columns, "GROUP_CONCAT(if(ANY_VALUE(FinalRankNumber) = ",v_pointer_,", CONCAT(ANY_VALUE(t.Code), '<br>', ANY_VALUE(t.Description), '<br>', ANY_VALUE(t.Rate), '<br>', ANY_VALUE(t.AccountName), '<br>', DATE_FORMAT (ANY_VALUE(t.EffectiveDate), '%d/%m/%Y'),'', '=', ANY_VALUE(t.BlockingId), '-', ANY_VALUE(t.AccountId), '-', ANY_VALUE(t.Code), '-', ANY_VALUE(t.BlockingCountryId) ), NULL)) AS `POSITION ",v_pointer_,"`,");
		ELSE
			SET @stm_columns = CONCAT(@stm_columns, "GROUP_CONCAT(if(ANY_VALUE(FinalRankNumber) = ",v_pointer_,", CONCAT(ANY_VALUE(t.Code), '<br>', ANY_VALUE(t.Description), '<br>', ANY_VALUE(t.Rate), '<br>', ANY_VALUE(t.AccountName), '<br>', DATE_FORMAT (ANY_VALUE(t.EffectiveDate), '%d/%m/%Y')), NULL))  AS `POSITION ",v_pointer_,"`,");
		END IF;

		SET v_pointer_ = v_pointer_ + 1;

	END WHILE;

	SET @stm_columns = TRIM(TRAILING ',' FROM @stm_columns);

	/* @stm_columns output
	GROUP_CONCAT(if(ANY_VALUE(FinalRankNumber) = 1, CONCAT(ANY_VALUE(t.Code), '<br>', ANY_VALUE(t.Rate), '<br>', ANY_VALUE(t.AccountName), '<br>', DATE_FORMAT (ANY_VALUE(t.EffectiveDate), '%d/%m/%Y'),'', '=', ANY_VALUE(t.BlockingId), '-', ANY_VALUE(t.AccountId), '-', ANY_VALUE(t.Code), '-', ANY_VALUE(t.BlockingCountryId) ), NULL))AS `POSITION 1`,
	GROUP_CONCAT(if(ANY_VALUE(FinalRankNumber) = 2, CONCAT(ANY_VALUE(t.Code), '<br>', ANY_VALUE(t.Rate), '<br>', ANY_VALUE(t.AccountName), '<br>', DATE_FORMAT (ANY_VALUE(t.EffectiveDate), '%d/%m/%Y'),'', '=', ANY_VALUE(t.BlockingId), '-', ANY_VALUE(t.AccountId), '-', ANY_VALUE(t.Code), '-', ANY_VALUE(t.BlockingCountryId) ), NULL))AS `POSITION 2`,
	GROUP_CONCAT(if(ANY_VALUE(FinalRankNumber) = 3, CONCAT(ANY_VALUE(t.Code), '<br>', ANY_VALUE(t.Rate), '<br>', ANY_VALUE(t.AccountName), '<br>', DATE_FORMAT (ANY_VALUE(t.EffectiveDate), '%d/%m/%Y'),'', '=', ANY_VALUE(t.BlockingId), '-', ANY_VALUE(t.AccountId), '-', ANY_VALUE(t.Code), '-', ANY_VALUE(t.BlockingCountryId) ), NULL))AS `POSITION 3`,
	GROUP_CONCAT(if(ANY_VALUE(FinalRankNumber) = 4, CONCAT(ANY_VALUE(t.Code), '<br>', ANY_VALUE(t.Rate), '<br>', ANY_VALUE(t.AccountName), '<br>', DATE_FORMAT (ANY_VALUE(t.EffectiveDate), '%d/%m/%Y'),'', '=', ANY_VALUE(t.BlockingId), '-', ANY_VALUE(t.AccountId), '-', ANY_VALUE(t.Code), '-', ANY_VALUE(t.BlockingCountryId) ), NULL))AS `POSITION 4`,
	GROUP_CONCAT(if(ANY_VALUE(FinalRankNumber) = 5, CONCAT(ANY_VALUE(t.Code), '<br>', ANY_VALUE(t.Rate), '<br>', ANY_VALUE(t.AccountName), '<br>', DATE_FORMAT (ANY_VALUE(t.EffectiveDate), '%d/%m/%Y'),'', '=', ANY_VALUE(t.BlockingId), '-', ANY_VALUE(t.AccountId), '-', ANY_VALUE(t.Code), '-', ANY_VALUE(t.BlockingCountryId) ), NULL))AS `POSITION 5`
	*/

	IF (p_isExport = 0)
	THEN
		IF p_groupby = 'description' THEN

			SET @stm_query = CONCAT("SELECT CONCAT(max(t.Description)) as Destination,",@stm_columns," FROM tmp_final_VendorRate_  t GROUP BY  t.Description ORDER BY t.Description ASC LIMIT ",p_RowspPage," OFFSET ",v_OffSet_," ;");

		ELSE

			SET @stm_query = CONCAT("SELECT CONCAT(ANY_VALUE(t.RowCode) , ' : ' , ANY_VALUE(t.Description)) as Destination,", @stm_columns," FROM tmp_final_VendorRate_  t GROUP BY  RowCode ORDER BY RowCode ASC LIMIT ",p_RowspPage," OFFSET ",v_OffSet_," ;");

		END IF;

		SELECT count(distinct RowCode) as totalcount from tmp_final_VendorRate_
			WHERE  ( CHAR_LENGTH(RTRIM(p_code)) = 0  OR RowCode LIKE REPLACE(p_code,'*', '%') ) ;

	END IF;

	IF p_isExport = 1
	THEN

		SET @stm_query = CONCAT("SELECT CONCAT(ANY_VALUE(t.RowCode) , ' : ' , ANY_VALUE(t.Description)) as Destination,",@stm_columns," FROM tmp_final_VendorRate_  t GROUP BY  RowCode ORDER BY RowCode ASC;");

	END IF;

	PREPARE stm_query FROM @stm_query;
	EXECUTE stm_query;
	DEALLOCATE PREPARE stm_query;

	SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prc_GetLCRwithPrefix` */;
DELIMITER ;;
CREATE DEFINER=`neon-user`@`117.247.87.156` PROCEDURE `prc_GetLCRwithPrefix`(
	IN `p_companyid` INT,
	IN `p_trunkID` INT,
	IN `p_TimezonesID` VARCHAR(50),
	IN `p_codedeckID` INT,
	IN `p_CurrencyID` INT,
	IN `p_code` VARCHAR(50),
	IN `p_Description` VARCHAR(250),
	IN `p_AccountIds` TEXT,
	IN `p_PageNumber` INT,
	IN `p_RowspPage` INT,
	IN `p_SortOrder` VARCHAR(50),
	IN `p_Preference` INT,
	IN `p_Position` INT,
	IN `p_vendor_block` INT,
	IN `p_groupby` VARCHAR(50),
	IN `p_SelectedEffectiveDate` DATE,
	IN `p_ShowAllVendorCodes` INT,
	IN `p_merge_timezones` INT,
	IN `p_TakePrice` INT,
	IN `p_isExport` INT

)
ThisSP:BEGIN

		DECLARE v_OffSet_ int;
		DECLARE v_Code VARCHAR(50) ;
		DECLARE v_pointer_ int;
		DECLARE v_rowCount_ int;
		DECLARE v_p_code VARCHAR(50);
		DECLARE v_Codlen_ int;
		DECLARE v_position int;
		DECLARE v_p_code__ VARCHAR(50);
		DECLARE v_has_null_position int ;
		DECLARE v_next_position1 VARCHAR(200) ;
		DECLARE v_CompanyCurrencyID_ INT;


		SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

		SET @@session.collation_connection='utf8_unicode_ci';
		SET @@session.character_set_results='utf8';

		SET v_OffSet_ = (p_PageNumber * p_RowspPage) - p_RowspPage;

		DROP TEMPORARY TABLE IF EXISTS tmp_VendorRate_stage_;
		CREATE TEMPORARY TABLE tmp_VendorRate_stage_ (
			RowCode VARCHAR(50) ,
			AccountId INT ,
			AccountName VARCHAR(100) ,
			Code VARCHAR(50) ,
			Rate DECIMAL(18,6) ,
			ConnectionFee DECIMAL(18,6) ,
			EffectiveDate DATETIME ,
			Description VARCHAR(255),
			Preference INT,
			MaxMatchRank int ,
			prev_prev_RowCode VARCHAR(50),
			prev_AccountID int
		)
		;

		DROP TEMPORARY TABLE IF EXISTS tmp_VendorRate_stage2_;
		CREATE TEMPORARY TABLE tmp_VendorRate_stage2_ (
			RowCode VARCHAR(50) ,
			AccountId INT ,
			AccountName VARCHAR(100) ,
			Code VARCHAR(50) ,
			Rate DECIMAL(18,6) ,
			ConnectionFee DECIMAL(18,6) ,
			EffectiveDate DATETIME ,
			Description VARCHAR(255),
			Preference INT,
			MaxMatchRank int ,
			prev_prev_RowCode VARCHAR(50),
			prev_AccountID int
		)
		;

		DROP TEMPORARY TABLE IF EXISTS tmp_VendorRate_;
		CREATE TEMPORARY TABLE tmp_VendorRate_ (
			AccountId INT ,
			BlockingId INT DEFAULT 0,
			BlockingCountryId INT DEFAULT 0,
			AccountName VARCHAR(100) ,
			Code VARCHAR(50) ,
			Rate DECIMAL(18,6) ,
			RateID int,
			ConnectionFee DECIMAL(18,6) ,
			EffectiveDate DATETIME ,
			Description VARCHAR(255),
			Preference INT,
			RowCode VARCHAR(50)
		)
		;

		DROP TEMPORARY TABLE IF EXISTS tmp_final_VendorRate_;
		CREATE TEMPORARY TABLE tmp_final_VendorRate_ (
			AccountId INT ,
			BlockingId INT DEFAULT 0,
			BlockingCountryId INT DEFAULT 0,
			AccountName VARCHAR(100) ,
			Code VARCHAR(50) ,
			Rate DECIMAL(18,6) ,
			RateID int,
			ConnectionFee DECIMAL(18,6) ,
			EffectiveDate DATETIME ,
			Description VARCHAR(255),
			Preference INT,
			RowCode VARCHAR(50),
			FinalRankNumber int
		)
		;


		DROP TEMPORARY TABLE IF EXISTS tmp_search_code_;
		CREATE TEMPORARY TABLE tmp_search_code_ (
			Code  varchar(50),
			INDEX Index1 (Code)
		);


		DROP TEMPORARY TABLE IF EXISTS tmp_code_;
		CREATE TEMPORARY TABLE tmp_code_ (
			RowCode  varchar(50),
			Code  varchar(50),
			RowNo int,
			INDEX Index1 (Code)
		);


		DROP TEMPORARY TABLE IF EXISTS tmp_all_code_;
		CREATE TEMPORARY TABLE tmp_all_code_ (
			RowCode  varchar(50),
			Code  varchar(50),

			INDEX Index2 (Code)
		)
		;


		DROP TEMPORARY TABLE IF EXISTS tmp_VendorCurrentRates_;
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_VendorCurrentRates_(
			AccountId int,
			BlockingId INT DEFAULT 0,
			BlockingCountryId INT DEFAULT 0,
			AccountName varchar(200),
			Code varchar(50),
			Description varchar(200),
			Rate DECIMAL(18,6) ,
			ConnectionFee DECIMAL(18,6) ,
			EffectiveDate date,
			TrunkID int,
			CountryID int,
			RateID int,
			Preference int,
			INDEX IX_Code (Code)
		)
		;

		DROP TEMPORARY TABLE IF EXISTS tmp_VendorCurrentRates1_;
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_VendorCurrentRates1_(
			AccountId int,
			BlockingId INT DEFAULT 0,
			BlockingCountryId INT DEFAULT 0,
			AccountName varchar(200),
			Code varchar(50),
			Description varchar(200),
			Rate DECIMAL(18,6) ,
			ConnectionFee DECIMAL(18,6) ,
			EffectiveDate date,
			TrunkID int,
			CountryID int,
			RateID int,
			Preference int,
			INDEX IX_Code (Code),
			INDEX tmp_VendorCurrentRates_AccountId (`AccountId`,`TrunkID`,`RateId`,`EffectiveDate`)
		)
		;

		DROP TEMPORARY TABLE IF EXISTS tmp_VendorRateByRank_;
		CREATE TEMPORARY TABLE tmp_VendorRateByRank_ (
			AccountId INT ,
			BlockingId INT DEFAULT 0,
			BlockingCountryId INT DEFAULT 0,
			AccountName VARCHAR(100) ,
			Code VARCHAR(50) ,
			Rate DECIMAL(18,6) ,
			RateID int,
			ConnectionFee DECIMAL(18,6) ,
			EffectiveDate DATETIME ,
			Description VARCHAR(255),
			Preference INT,
			rankname INT,
			INDEX IX_Code (Code,rankname)
		)
		;

		DROP TEMPORARY TABLE IF EXISTS tmp_block0;
		CREATE TEMPORARY TABLE tmp_block0(
			AccountId INT,
			AccountName VARCHAR(200),
			des VARCHAR(200),
			RateId INT
		);

		SELECT CurrencyId INTO v_CompanyCurrencyID_ FROM  tblCompany WHERE CompanyID = p_companyid;

		/* 	#4.18
			only one dynamic query based on condition
			no need to create seperate query for seperate condition
		*/

		SET @num := 0, @AccountID := '', @TrunkID := '', @RateID := '';

		SET @stm_show_all_vendor_codes = CONCAT("INNER JOIN (SELECT Code,Description FROM tblRate WHERE CodeDeckId=",p_codedeckID,") tmpselectedcd ON tmpselectedcd.Code=tblRate.Code");

		SET @stm = CONCAT('
			INSERT INTO tmp_VendorCurrentRates1_
			',
			IF (p_merge_timezones = 1,"
				SELECT DISTINCT
					AccountId,
					BlockingId,
					BlockingCountryId,
					AccountName,
					Code,
					Description,
					Rate,
					ConnectionFee,
					EffectiveDate,
					TrunkID,
					CountryID,
					RateID,
					Preference
				FROM (
			",""),'

				Select DISTINCT
					AccountId,
					BlockingId,
					BlockingCountryId,
					AccountName,
					Code,
					Description,
					Rate,
					ConnectionFee,
					EffectiveDate,
					TrunkID,
					CountryID,
					RateID,
					Preference
					',IF (p_merge_timezones = 1,",
						@num := if(@AccountID = AccountID AND @TrunkID = TrunkID AND @RateID = RateID, @num + 1, 1) as row_number,
						@AccountID := AccountID,
						@TrunkID := TrunkID,
						@RateID := RateID
					",""),'
				FROM (
					SELECT distinct
						tblVendorRate.AccountId,
						IFNULL(blockCode.VendorBlockingId, 0) AS BlockingId,
						IFNULL(blockCountry.CountryId, 0)  as BlockingCountryId,
						tblAccount.AccountName,
						tblRate.Code,
						tblRate.Description,
						CASE WHEN  tblAccount.CurrencyId = ',p_CurrencyID,'
						THEN
							tblVendorRate.Rate
						WHEN  ',v_CompanyCurrencyID_,' = ',p_CurrencyID,'
						THEN
						(
							( tblVendorRate.rate  / (Select Value from tblCurrencyConversion where tblCurrencyConversion.CurrencyId = tblAccount.CurrencyId and  CompanyID = ',p_companyid,' ) )
						)
						ELSE
						(
							(Select Value from tblCurrencyConversion where tblCurrencyConversion.CurrencyId = ',p_CurrencyID,' and  CompanyID = ',p_companyid,' )
							* (tblVendorRate.rate  / (Select Value from tblCurrencyConversion where tblCurrencyConversion.CurrencyId = tblAccount.CurrencyId and CompanyID = ',p_companyid,' ))
						)
						END as Rate,
						ConnectionFee,
						DATE_FORMAT (tblVendorRate.EffectiveDate, "%Y-%m-%d") AS EffectiveDate,
						tblVendorRate.TrunkID, tblRate.CountryID, tblRate.RateID,IFNULL(vp.Preference, 5) AS Preference
					FROM
						tblVendorRate
					INNER JOIN tblVendorTrunk vt ON vt.CompanyID = ',p_companyid,' AND vt.AccountID = tblVendorRate.AccountID and vt.Status = 1 and vt.TrunkID = ',p_trunkID,'
					INNER JOIN tblAccount ON tblAccount.CompanyID = ',p_companyid,' AND tblVendorRate.AccountId = tblAccount.AccountID
					INNER JOIN tblRate ON tblRate.CompanyID = ',p_companyid,' AND tblVendorRate.RateId = tblRate.RateID  AND vt.CodeDeckId = tblRate.CodeDeckId
					',
					IF (p_ShowAllVendorCodes = 1,"",@stm_show_all_vendor_codes)
					,'
					LEFT JOIN
						tblVendorPreference vp
						ON vp.AccountId = tblVendorRate.AccountId
						AND vp.TrunkID = tblVendorRate.TrunkID
						AND vp.TimezonesID = tblVendorRate.TimezonesID
						AND vp.RateId = tblVendorRate.RateId
					LEFT OUTER JOIN
						tblVendorBlocking AS blockCode
						ON tblVendorRate.RateId = blockCode.RateId
						AND tblVendorRate.AccountId = blockCode.AccountId
						AND tblVendorRate.TrunkID = blockCode.TrunkID
						AND tblVendorRate.TimezonesID = blockCode.TimezonesID
					LEFT OUTER JOIN
						tblVendorBlocking AS blockCountry
						ON tblRate.CountryID = blockCountry.CountryId
						AND tblVendorRate.AccountId = blockCountry.AccountId
						AND tblVendorRate.TrunkID = blockCountry.TrunkID
						AND tblVendorRate.TimezonesID = blockCountry.TimezonesID
					WHERE
						( CHAR_LENGTH(RTRIM("',p_code,'")) = 0 OR tblRate.Code LIKE REPLACE("',p_code,'","*", "%") )
						AND ("',p_Description,'"="" OR tblRate.Description LIKE REPLACE("',p_Description,'","*","%"))
						AND ("',p_AccountIds,'"="" OR FIND_IN_SET(tblAccount.AccountID,"',p_AccountIds,'") != 0 )
						-- AND EffectiveDate <= NOW()
						AND EffectiveDate <= DATE("',p_SelectedEffectiveDate,'")
						AND (tblVendorRate.EndDate is NULL OR tblVendorRate.EndDate > now() )    -- rate should not end Today
						AND tblAccount.IsVendor = 1
						AND tblAccount.Status = 1
						AND tblAccount.CurrencyId is not NULL
						AND tblVendorRate.TrunkID = ',p_trunkID,'
						AND (
							(',p_merge_timezones,' = 0 AND tblVendorRate.TimezonesID = "',p_TimezonesID,'") OR
							(',p_merge_timezones,' = 1 AND FIND_IN_SET(tblVendorRate.TimezonesID, "',p_TimezonesID,'"))
						)
						AND
						(
							',p_vendor_block,' = 1 OR
							(
								',p_vendor_block,' = 0 AND   (
									blockCode.RateId IS NULL  AND blockCountry.CountryId IS NULL
								)
							)
						)
						-- AND blockCode.RateId IS NULL
						-- AND blockCountry.CountryId IS NULL
					',
					IF (p_merge_timezones = 1,CONCAT("ORDER BY AccountID, TrunkID, RateID, Rate ",IF(p_TakePrice=1,"DESC","ASC")),"")
					,'
				) tbl
			',
			IF (p_merge_timezones = 1,") AS x WHERE x.row_number <= 1","")
			,'
			ORDER BY Code ASC;
		');

	--	select @stm;
	--	leave ThisSP;

		PREPARE stmt FROM @stm;
		EXECUTE stmt;
		DEALLOCATE PREPARE stmt;

/* for grooup by description  			*/

			IF p_groupby = 'description' THEN

