IF  EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[P_GERA_EST_PED_ELTR_EST_PROD_TRANSF_POOL]') 
					AND TYPE IN (N'P', N'PC'))
	BEGIN
		DROP PROCEDURE [DBO].[P_GERA_EST_PED_ELTR_EST_PROD_TRANSF_POOL]
	END
GO

--P_GERA_EST_PED_ELTR_EST_PROD_TRANSF_POOL 1
CREATE PROCEDURE [DBO].[P_GERA_EST_PED_ELTR_EST_PROD_TRANSF_POOL](@CD_EMP INT =1, @CD_FILIAL INT=0)
WITH ENCRYPTION 
AS

SET NOCOUNT ON;

DECLARE	@mensagemErro	VARCHAR(255),
		@severidadeErro INT,
		@estadoErro		INT;
		 
DECLARE @UTILIZA_ARREDONDAMENTO INT=0;
DECLARE @FLAG_UTILIZA_ENVIO_UNIDADE_CAIXA_FECHADA INT=0;

 

--ESSE FLAG FOI CRIADO PARA CONSIDERAR A SEGUINTE SITUACAO:
-- SE A NECESSIDADE DO PRODUTO/FILIAL ATINGIR 50% + 1 DE UMA CAIXA FECHADA, ENVIA A CAIXA TODA. SE NÃO ATINGIR, ENVIA UNIDADE
SET @FLAG_UTILIZA_ENVIO_UNIDADE_CAIXA_FECHADA = ISNULL((SELECT VALOR FROM PRC_EMP_CONFIG 
															WHERE CD_EMP = @CD_EMP AND CD_CHAVE = 'FLAG_UTILIZA_ENVIO_UNIDADE_CAIXA_FECHADA'), 0);

	
	Print '-------------- Gerando pedido eletronico  ------------------' + convert(varchar, getdate(),108 )

---------------------------------------------------------------------------------------------------------- 
-- ALIMENTA A TABELA INICIAL COM OS RESSUPRIMENTOS
----------------------------------------------------------------------------------------------------------
	CREATE TABLE #TMP_PED ( CD_EMP			INT,	
								CD_GRP		INT,
								CD_PED_SOL	INT,
								DT_PED		DATETIME,
								DS_GRP		VARCHAR(150),
								CD_FIL_ORIG	INT,
								CD_FILIAL	INT,	
								CD_CTR		INT,
								CD_PROD		INT,
								QT_SOL		MONEY,
								VLR_PROD		MONEY,
								QT_UNI_RESSUP	MONEY,
								CD_ROTEIRO_DEFAULT	INT)
	
	DECLARE @CD_PED_SOL INT; 
	DECLARE @CD_CTR INT;
	DECLARE @TP_GRP_PED INT = 0;
	DECLARE @DIAS_ACRESCENTAR INT = 0;

--------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------
begin try	
	Begin tran
--------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------

		SET @CD_PED_SOL = ISNULL((SELECT MAX(CD_PED_SOL) 
										FROM EST_PED_ELTR WITH (TABLOCKX)  WHERE CD_EMP = 1), 0) + 1; -- Gera um bloqueio na tabela para nao ser quebrada a sequencia de pedidos.

		DECLARE @CD_ROT INT;

		SET @CD_ROT= ISNULL((SELECT VALOR FROM PRC_EMP_CONFIG WHERE CD_EMP = @CD_EMP AND CD_CHAVE = 'ROTEIRO_PADRAO_COMPRA_POR_RESSUPRIMENTO'), 0)
		SET @DIAS_ACRESCENTAR = ISNULL((SELECT DIAS_RES_ACRESCENTAR FROM PRC_EMP WHERE CD_EMP = @CD_EMP), 0)
		 
		 
		CREATE TABLE #RESSUP
		(
					 CD_EMP             INT
				   , CD_FILIAL          INT
				   , CD_FIL_ORIG        INT
				   , CD_CTR             INT
				   , DT_TRANSF          DATETIME
				   , CD_PROD            INT
				   , QT_SOL             MONEY
				   , VLR_PROD           MONEY
				   , QT_UNI_RESSUP      MONEY
				   , CD_ROTEIRO_DEFAULT INT
				   , CD_GRP_PRT         INT
				   , DS_GRP_RES_PRT     VARCHAR(100)
		);
		CREATE TABLE #RESSUP_QUEBRADO
		(
					 CD_EMP             INT
				   , CD_FILIAL          INT
				   , CD_FIL_ORIG        INT
				   , CD_CTR             INT
				   , DT_TRANSF          DATETIME
				   , CD_PROD            INT
				   , QT_SOL             MONEY
				   , VLR_PROD           MONEY
				   , QT_UNI_RESSUP      MONEY
				   , CD_ROTEIRO_DEFAULT INT
				   , CD_GRP_PRT         INT
				   , DS_GRP_RES_PRT     VARCHAR(100)
		);


	   INSERT INTO #RESSUP
       SELECT
              T.CD_EMP CD_EMP
            , T.CD_FIL_DEST CD_FILIAL
            , T.CD_FILIAL CD_FIL_ORIG
            , DENSE_RANK() OVER(ORDER BY T.CD_EMP, T.CD_FIL_DEST,T.CD_FILIAL, E.CD_GRP_PRT) CD_CTR
            , MAX(T.DT_TRANSF) DT_TRANSF
            , I.CD_PROD
            , SUM(I.QT_SOL) QT_SOL
            , MAX(I.VLR_CUSTO) VLR_PROD
            , MAX(COALESCE(I.QT_UNI_RESSUPRIMENTO, 1)) QT_UNI_RESSUP
            , E.CD_ROTEIRO_DEFAULT
            , E.CD_GRP_PRT
            , COALESCE(E.DS_ROTEIRO, 'GERAL') DS_GRP_RES_PRT
       FROM
            EST_PROD_TRANSF T
            INNER JOIN EST_PROD_TRANSF_IT I ON T.CD_EMP = I.CD_EMP
                                               AND T.CD_FILIAL = I.CD_FILIAL
                                               AND T.CD_CTR = I.CD_CTR
            JOIN EST_PROD_CPL C ON T.CD_EMP = C.CD_EMP
                                   AND T.CD_FILIAL = C.CD_FILIAL
                                   AND I.CD_PROD = C.CD_PROD
            INNER JOIN PRC_FILIAL_DEPOSITO D ON T.CD_EMP = D.CD_EMP
                                                AND T.CD_FILIAL = D.CD_FILIAL
            LEFT JOIN ( SELECT
							CD_ROTEIRO_DEFAULT
							, C.CD_GRP_PRT
							, E.CD_EMP
							, E.CD_PRT
							, R.DS_ROTEIRO
							, C.CD_CTR_DEPO
								FROM
									 EST_PROD_PRT_GRP_RESSUPRIMENTO C
									 JOIN EST_PROD_PRT_GRP_RESSUPRIMENTO_CPL E ON C.CD_GRP_PRT = E.CD_GRP_PRT
									 LEFT JOIN EST_PED_CP_ROTEIRO_CP R ON C.CD_ROTEIRO_DEFAULT = R.CD_ROTEIRO
							) E ON C.CD_EMP = E.CD_EMP
								   AND C.PRAT = E.CD_PRT
								   AND ISNULL(E.CD_CTR_DEPO, D.CD_CTR_DEPO) = D.CD_CTR_DEPO
       WHERE T.CD_EMP = 1
             AND T.STS_TRANSF = 0
             AND T.CD_FILIAL = (CASE
                                    WHEN @CD_FILIAL > 0 THEN @CD_FILIAL
                                    ELSE T.CD_FILIAL
                                END)
       GROUP BY
                T.CD_EMP
              , T.CD_FIL_DEST
              , T.CD_FILIAL
              , I.CD_PROD
              , E.CD_ROTEIRO_DEFAULT
              , E.CD_GRP_PRT
              , COALESCE(E.DS_ROTEIRO, 'GERAL');

/*****************************************************************************************************************/
/*****************************************************************************************************************/
/*****************************************************************************************************************/
	
		DECLARE 
				@Emp    INT
			, @Filial INT
			, @Orig   INT
			, @ctr    INT
			, @NewID  INT
			, @Qtde_Quebra int = 250 ;

		set @Qtde_Quebra = ISNULL((SELECT VALOR FROM PRC_EMP_CONFIG WHERE CD_EMP = @CD_EMP AND CD_CHAVE = 'QTDE_ITENS_DIVIDE_RESSUPRIMENTO'),0);

		SET @NewID =(SELECT MAX(cd_ctr) FROM #RESSUP );

		DECLARE c_Quebra CURSOR FAST_FORWARD
		FOR SELECT
			cd_emp
			, cd_filial
			, cd_fil_orig
			, cd_ctr 
		FROM
			#RESSUP
		GROUP BY
				cd_emp
			, cd_filial
			, cd_fil_orig
			, cd_ctr
		HAVING COUNT(*) > @Qtde_Quebra;
		OPEN c_Quebra;
		FETCH NEXT FROM c_Quebra INTO @Emp   ,@Filial, @Orig,  @ctr   

		WHILE @@FETCH_STATUS = 0
		BEGIN
		WHILE EXISTS(SELECT  COUNT(*)
						FROM #RESSUP
						WHERE cd_emp = @Emp AND cd_filial = @Filial AND cd_fil_orig = @Orig AND cd_ctr = @ctr
						GROUP BY cd_emp , cd_filial , cd_fil_orig, cd_ctr 
					HAVING COUNT(*) > @Qtde_Quebra )
			BEGIN
				SET @NewID = @NewID + 1;
            
				INSERT INTO #RESSUP_QUEBRADO
				SELECT TOP (@Qtde_Quebra)
						CD_EMP
					, CD_FILIAL
					, CD_FIL_ORIG
					, @NewID CD_CTR
					, DT_TRANSF
					, CD_PROD
					, QT_SOL
					, VLR_PROD
					, QT_UNI_RESSUP
					, CD_ROTEIRO_DEFAULT
					, CD_GRP_PRT
					, DS_GRP_RES_PRT
				FROM
					#RESSUP
				WHERE cd_emp = @Emp
						AND cd_filial = @Filial
						AND cd_fil_orig = @Orig
						AND cd_ctr = @ctr
				ORDER BY
						cd_prod;

				DELETE FROM A
				FROM 
					#RESSUP A
					INNER JOIN #RESSUP_QUEBRADO B ON 
					A.CD_EMP		= B.CD_EMP AND
					A.CD_FILIAL		= B.CD_FILIAL AND
					A.CD_FIL_ORIG	= B.CD_FIL_ORIG AND
					A.CD_PROD		= B.CD_PROD   
				WHERE
							a.cd_emp = @Emp
						AND a.cd_filial = @Filial
						AND a.cd_fil_orig = @Orig
						AND a.cd_ctr = @ctr;

			END;
			FETCH NEXT FROM c_Quebra INTO @Emp   ,@Filial, @Orig,  @ctr   
		END;

		CLOSE c_Quebra; 
		DEALLOCATE c_Quebra;

		insert into #RESSUP
		SELECT 		CD_EMP
					, CD_FILIAL
					, CD_FIL_ORIG
					, CD_CTR
					, DT_TRANSF
					, CD_PROD
					, QT_SOL
					, VLR_PROD
					, QT_UNI_RESSUP
					, CD_ROTEIRO_DEFAULT
					, CD_GRP_PRT
					, DS_GRP_RES_PRT FROM #RESSUP_QUEBRADO

 /*****************************************************************************************************************/
 PRINT 'Realizou as quebras do pedido ' +convert(varchar,getdate(),108) 
 /*****************************************************************************************************************/
  		
	
		INSERT INTO #TMP_PED
		SELECT DISTINCT
				RESSUP.CD_EMP
			--COALESCE(RESSUP.CD_GRP_PRT,@CD_ROT) + CD_FIL_ORIG  CD_GRP,
			, DENSE_RANK() OVER(ORDER BY RESSUP.CD_EMP
										, RESSUP.CD_FIL_ORIG
										, COALESCE(RESSUP.CD_ROTEIRO_DEFAULT, @CD_ROT)) CD_GRP
			, @CD_PED_SOL + DENSE_RANK() OVER(ORDER BY RESSUP.CD_EMP
														, RESSUP.CD_FIL_ORIG
														, RESSUP.CD_CTR
														, COALESCE(RESSUP.CD_ROTEIRO_DEFAULT, @CD_ROT)) CD_PED_SOL
			, DATEADD(DAY, @DIAS_ACRESCENTAR * -1, RESSUP.DT_TRANSF) AS DT_TRANSF
			, LEFT ('RESSUP. VIA DIST.: '+CONVERT(VARCHAR(10), RESSUP.CD_FIL_ORIG)+' GRP RES.:'+DS_GRP_RES_PRT,150) DS_GRP
			, RESSUP.CD_FIL_ORIG
			, RESSUP.CD_FILIAL
			, RESSUP.CD_CTR
			, RESSUP.CD_PROD
			, RESSUP.QT_SOL
			, RESSUP.VLR_PROD
			, COALESCE(RESSUP.QT_UNI_RESSUP, 1)
			, COALESCE(RESSUP.CD_ROTEIRO_DEFAULT, @CD_ROT) CD_ROTEIRO
		FROM
			#RESSUP RESSUP;  
  
		------------------------------------------------------------------------------------------------------------------------
		-- CASO ESTEJA PARAMETRIZADO PARA EFETUAR O ARREDONDAMENTO DO RESSUPRIMENTO DO DEPOSITO AUXILIAR, FAZ O ARREDONDAMENTO
		------------------------------------------------------------------------------------------------------------------------
		SET @UTILIZA_ARREDONDAMENTO = COALESCE((SELECT VALOR FROM PRC_EMP_CONFIG WHERE CD_EMP = 1 AND CD_CHAVE = 'FLAG_UTILIZA_ARREDONDAMENTO_RESSUP'), 0)

		IF @UTILIZA_ARREDONDAMENTO = 1
		BEGIN

			DECLARE @CD_FILIAL_AUX INT;
			DECLARE @CD_PED_SOL_AUX INT;
			DECLARE @CD_PROD_AUX INT;
			DECLARE @CD_USU_AUX INT;
			DECLARE @ORDEM_AUX INT;
			DECLARE @QT_SOL_AUX INT;
			DECLARE @QT_SOL_ARREDOND MONEY;
			DECLARE @QTDE_ARREDOND MONEY;
			DECLARE @PERC_ARREDOND MONEY;
			DECLARE @QT_EST_AUX MONEY;
			DECLARE @QT_EST_UTILIZADO MONEY; 

			DECLARE @QT_EST_AUX_AUX MONEY;
			DECLARE @CD_PROD_AUX_AUX INT; 

			DECLARE
				CURSOR_PED
			CURSOR FOR
				SELECT
					A.CD_FILIAL,
					T.CD_PED_SOL,
					A.CD_PROD,
					T.QT_SOL,
					isnull(A.QTDE_ARREDOND,0) QTDE_ARREDOND,
					isnull(A.PERC_ARREDOND,0) PERC_ARREDOND,
					CPL.QT_EST - (SELECT SUM(QT_SOL) FROM #TMP_PED WHERE CD_EMP = T.CD_EMP AND CD_PROD = T.CD_PROD GROUP BY CD_PROD),
					A.CD_USU,
					A.ORDEM
				FROM
					#TMP_PED T
					INNER JOIN EST_ARV_GRP_RESSUPRIMENTO_ARREDONDAMENTO A ON
						T.CD_EMP = A.CD_EMP
						AND T.CD_FILIAL = A.CD_FILIAL
						AND T.CD_PROD = A.CD_PROD
					INNER JOIN EST_PROD_CPL CPL ON
						T.CD_EMP = CPL.CD_EMP
						AND CPL.CD_FILIAL = @CD_FILIAL
						AND T.CD_PROD = CPL.CD_PROD
				WHERE
					A.QTDE_ARREDOND > 1
					AND T.QT_UNI_RESSUP = 1
				ORDER BY
					A.CD_PROD,
					A.ORDEM,
					A.QTDE_ARREDOND DESC


			OPEN CURSOR_PED

			FETCH NEXT FROM CURSOR_PED INTO @CD_FILIAL_AUX, @CD_PED_SOL_AUX, @CD_PROD_AUX, @QT_SOL_AUX, @QTDE_ARREDOND, @PERC_ARREDOND, @QT_EST_AUX, @CD_USU_AUX, @ORDEM_AUX

			SET @CD_PROD_AUX_AUX = 0
			SET @QT_EST_AUX_AUX = 0

			WHILE @@FETCH_STATUS = 0
			BEGIN

				IF @CD_PROD_AUX_AUX <> @CD_PROD_AUX
				BEGIN
					SET @CD_PROD_AUX_AUX = @CD_PROD_AUX
					SET @QT_EST_AUX_AUX = @QT_EST_AUX
				END		
		
				IF @QT_EST_AUX_AUX > 0 AND @QT_EST_AUX_AUX + @QT_SOL_AUX >= @QTDE_ARREDOND
				BEGIN
			
					SET @QT_SOL_ARREDOND = 0

					IF @PERC_ARREDOND > 0
					BEGIN
						IF @QT_SOL_AUX * 100 / @QTDE_ARREDOND >= @PERC_ARREDOND
						BEGIN
							SET @QT_SOL_ARREDOND = (ROUND(@QT_SOL_AUX / @QTDE_ARREDOND, 0, 1) + CASE WHEN @QT_SOL_AUX % @QTDE_ARREDOND = 0 THEN 0 ELSE 1 END) * @QTDE_ARREDOND
						END ELSE
						BEGIN
							SET @QT_SOL_ARREDOND = 0
						END
					END ELSE
					BEGIN
						SET @QT_SOL_ARREDOND = (ROUND(@QT_SOL_AUX / @QTDE_ARREDOND, 0, 1) + CASE WHEN @QT_SOL_AUX % @QTDE_ARREDOND = 0 THEN 0 ELSE 1 END) * @QTDE_ARREDOND
					END

					IF @QT_SOL_ARREDOND > 0
					BEGIN
						UPDATE
							#TMP_PED
						SET
							QT_SOL = @QT_SOL_ARREDOND
						WHERE
							CD_EMP = @CD_EMP
							AND CD_PED_SOL = @CD_PED_SOL_AUX
							AND CD_FILIAL = @CD_FILIAL_AUX
							AND CD_PROD = @CD_PROD_AUX


						SET @QT_EST_AUX_AUX = @QT_EST_AUX_AUX - @QT_SOL_ARREDOND + @QT_SOL_AUX

						INSERT INTO
							EST_ARV_GRP_RESSUPRIMENTO_ARREDONDAMENTO_EST_PED_ELTR (CD_EMP, CD_FILIAL, CD_PED_SOL, CD_PROD, QT_SOL, QTDE_ARREDOND, QT_SOL_ARREDOND, 
								QT_EST, QT_EST_ATU, ORDEM, CD_USU, DT_REGISTRO, PERC_ARREDOND)
						VALUES
							(@CD_EMP, @CD_FILIAL_AUX, @CD_PED_SOL_AUX, @CD_PROD_AUX, @QT_SOL_AUX, @QTDE_ARREDOND, @QT_SOL_ARREDOND, 
								@QT_EST_AUX, @QT_EST_AUX_AUX, @ORDEM_AUX, @CD_USU_AUX, GETDATE(), @PERC_ARREDOND)
					END

				END

				FETCH NEXT FROM CURSOR_PED INTO @CD_FILIAL_AUX, @CD_PED_SOL_AUX, @CD_PROD_AUX, @QT_SOL_AUX, @QTDE_ARREDOND, @PERC_ARREDOND, @QT_EST_AUX, @CD_USU_AUX, @ORDEM_AUX
			END

			CLOSE CURSOR_PED
			DEALLOCATE CURSOR_PED 
		END
	 
	---------------------------------------------------------------------------------------------------------- 
	-- GRAVA OS PEDIDOS SEPARADOS POR GRUPO
	----------------------------------------------------------------------------------------------------------
		-- GRAVA O CABECALHO DO PEDIDO ELETRONICO
		INSERT INTO EST_PED_ELTR	(CD_EMP,CD_PED_SOL,CD_FILIAL,DT_PED,DT_ENTR,CD_FIL_FAT,CD_FIL_ENTR,
									 STS_PED,DT_CAD,CD_USU,DT_ULT_ATU,TP_REQ,FLAG_FECHAR,HORA_ENTREGA,HORA_DEMANDA,
									 FLAG_ESTOQUE_ZERADO,PERC_AUMENTO,FLAG_PERC_AUMENTO,
									 FLAG_GERAR_CROSS,
									 CD_CTR_DEMANDA,ATIVAR_PW_AUTOMATICO)
		SELECT DISTINCT
			T.CD_EMP CD_EMP,
			T.CD_PED_SOL CD_PED_SOL,
			T.CD_FILIAL	 CD_FILIAL,
			T.DT_PED DT_PED,
			T.DT_PED+2	DT_ENTR,
			T.CD_FILIAL CD_FIL_FAT,
			T.CD_FILIAL CD_FIL_ENTR,
			0 STS_PED,
			GETDATE() DT_CAD,
			1 CD_USU,
			NULL DT_ULT_ATU,
			0 TP_REQ,
			0 FLAG_FECHAR,
			GETDATE()+2 HORA_ENTREGA,
			GETDATE() HORA_DEMANDA,
			0 FLAG_ESTOQUE_ZERADO,
			0 PERC_AUMENTO,
			0 FLAG_PERC_AUMENTO,
			0 FLAG_GERAR_CROSS,
			NULL CD_CTR_DEMANDA,
			1
		FROM 
			#TMP_PED T;

	---------------------------------------------------------------------------------------------------------- 
	-- GRAVA OS ITENS DO PEDIDO ELETRONICO
	----------------------------------------------------------------------------------------------------------
		INSERT INTO
			EST_PED_ELTR_IT (CD_EMP, CD_PED_SOL, CD_PROD, QT_IT_UN,QT_IT, VLR_PROD, PERC_DESC, CD_COND_COMPRA, UNIDADE)
		SELECT   
			T.CD_EMP,
			T.CD_PED_SOL,
			T.CD_PROD,		
			CASE WHEN @FLAG_UTILIZA_ENVIO_UNIDADE_CAIXA_FECHADA = 0 THEN
				(ROUND((T.QT_SOL / T.QT_UNI_RESSUP),0) * T.QT_UNI_RESSUP)
			ELSE
				CASE WHEN ROUND((T.QT_SOL / T.QT_UNI_RESSUP),0) = 0 THEN
					T.QT_SOL
				ELSE
					(ROUND((T.QT_SOL / T.QT_UNI_RESSUP),0) * T.QT_UNI_RESSUP)
				END
			END AS QT_IT_UN,

			CASE WHEN @FLAG_UTILIZA_ENVIO_UNIDADE_CAIXA_FECHADA = 0 THEN
				(ROUND((T.QT_SOL / T.QT_UNI_RESSUP),0) * T.QT_UNI_RESSUP)
			ELSE
				CASE WHEN ROUND((T.QT_SOL / T.QT_UNI_RESSUP),0) = 0 THEN
					T.QT_SOL
				ELSE
					(ROUND((T.QT_SOL / T.QT_UNI_RESSUP),0) * T.QT_UNI_RESSUP)
				END
			END AS QT_SOL,

			T.VLR_PROD,
			0 PERC_DESC,
			0 CD_COND_COMPRA,
			1 UNIDADE
		FROM
			#TMP_PED T
		WHERE
			CASE WHEN @FLAG_UTILIZA_ENVIO_UNIDADE_CAIXA_FECHADA = 0 THEN
				ROUND(T.QT_SOL / T.QT_UNI_RESSUP, 0)
			ELSE
				1
			END > 0;
	---------------------------------------------------------------------------------------------------------- 
	-- GRAVA O VINCULO ENTRE AS TABELAS
	----------------------------------------------------------------------------------------------------------
	 
		/*INSERT INTO  EST_PROD_TRANSF_EST_PED_ELTR (CD_EMP, CD_FILIAL, CD_CTR, CD_PED_SOL)
		SELECT DISTINCT
			T.CD_EMP,
			T.CD_FIL_ORIG,
			T.CD_CTR,
			T.CD_PED_SOL
		FROM 
			#TMP_PED T ; 
			*/
	---------------------------------------------------------------------------------------------------------- 
	-- GRAVA O GRUPO DE PEDIDO ELETRONICO
	----------------------------------------------------------------------------------------------------------
	
		SET @CD_CTR = ISNULL((SELECT MAX(CD_GRP_PED) FROM EST_PED_ELTR_GRP_PED WHERE CD_EMP = @CD_EMP),1);
		SET @TP_GRP_PED = ISNULL((SELECT VALOR FROM PRC_EMP_CONFIG WHERE CD_EMP = @CD_EMP AND CD_CHAVE = 'TIPO_GRUPO_PEDIDOS_RESSP_DIST'), 0);

		IF @TP_GRP_PED = 0
		BEGIN
			UPDATE 
				#TMP_PED 
			SET 
				CD_GRP = CD_GRP + @CD_CTR;

			INSERT INTO  EST_PED_ELTR_GRP_PED (CD_EMP,CD_GRP_PED,DT_GRP_PED,STS_GRP_PED,
												CD_USU,DT_CAD,DS_GRP_PED, CD_ROTEIRO_DEFAULT)
			SELECT DISTINCT
				CD_EMP,
				CD_GRP CD_GRP_PED,
				CONVERT( DATE,GETDATE()) DT_GRP_PED,
				0 STS_GRP_PED,
				1 CD_USU,
				GETDATE() DT_CAD, 
				LEFT (DS_GRP + ' '  + CONVERT(VARCHAR, GETDATE(),103) + ' ' + CONVERT(VARCHAR, GETDATE(),108) + ' PED. ELTR REF. RESSUP', 100),
				CD_ROTEIRO_DEFAULT
			FROM
				 #TMP_PED A

			INSERT INTO 
				EST_PED_ELTR_GRP_PED_EST_PED_ELTR (CD_EMP,CD_GRP_PED,CD_PED_SOL)
			SELECT DISTINCT
				T.CD_EMP,
				T.CD_GRP CD_GRP_PED,
				T.CD_PED_SOL
			FROM
				#TMP_PED T 
			ORDER BY 
				CD_PED_SOL;

		END ELSE
		BEGIN
			SET @CD_CTR = @CD_CTR + 1
			INSERT INTO
				EST_PED_ELTR_GRP_PED (CD_EMP,CD_GRP_PED,DT_GRP_PED,STS_GRP_PED,
									  CD_USU,DT_CAD,DS_GRP_PED, CD_ROTEIRO_DEFAULT)
			SELECT
				@CD_EMP
				, ISNULL((SELECT MAX(CD_GRP_PED) 
								FROM EST_PED_ELTR_GRP_PED WITH (TABLOCKX)
								WHERE CD_EMP = @CD_EMP),1) + 1
				, CONVERT(DATE, GETDATE())
				, 0
				, 1 CD_USU
				, GETDATE() DT_CAD
				, LEFT ('RESSUPRIMENTO VIA DISTRIBUIDOR - ' + CONVERT(VARCHAR, GETDATE(),103) + ' - ' + CONVERT(VARCHAR, GETDATE(),108) + ' PED. ELTR REF. RESSUP',100) DS_GRP_PED
				, @CD_ROT CD_ROTEIRO_DEFAULT;
			
			INSERT INTO 
				EST_PED_ELTR_GRP_PED_EST_PED_ELTR (CD_EMP, CD_GRP_PED, CD_PED_SOL)
			SELECT DISTINCT
				T.CD_EMP,
				@CD_CTR,
				T.CD_PED_SOL
			FROM
				#TMP_PED T 
			ORDER BY
				CD_PED_SOL;
		END

	---------------------------------------------------------------------------------------------------------------------
	-- CANCELAR OS RESSUPRIMENTOS
	---------------------------------------------------------------------------------------------------------------------
		UPDATE 
			T 
		SET 
			STS_TRANSF=4
		FROM 
			EST_PROD_TRANSF T
			--INNER JOIN #TMP_PED E ON 
			--	T.CD_EMP		= E.CD_EMP AND
			--	T.CD_FILIAL		= E.CD_FIL_ORIG AND
			--	T.CD_CTR		= E.CD_CTR
		WHERE
			T.CD_EMP=@CD_EMP
			AND T.STS_TRANSF= 0; 
	--------------------------------------------------------------------------------------------------------------
	--------------------------------------------------------------------------------------------------------------
	commit tran
end try
begin catch

	IF @@NESTLEVEL > 0  ROLLBACK TRANSACTION;

	SELECT	@mensagemErro = ERROR_MESSAGE(), 
			@severidadeErro = ERROR_SEVERITY(), 
			@estadoErro = ERROR_STATE();
	
    INSERT INTO ADM_ERRO (numero, severidade, estado, rotina, linha, mensagem, dtErro)
	SELECT
		ERROR_NUMBER() AS numero,
		@severidadeErro AS severidade,
		@estadoErro AS estado,
		ERROR_PROCEDURE() AS rotina,
		ERROR_LINE() AS linha,
		@mensagemErro AS mensagem,
		GETDATE() AS dtErro;

	RAISERROR (@mensagemErro, @severidadeErro, @estadoErro);
	RETURN -2;	
end catch
--------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------

---------------------------------------------------------------------------------------------------------- 
-- FIM
----------------------------------------------------------------------------------------------------------

GO


