IF EXISTS( SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_RC_CLI_CONV_PBM_CONTROLE_EXTRATO]')
          AND type IN(N'P', N'PC')
)
    BEGIN
        DROP PROCEDURE DBO.P_RC_CLI_CONV_PBM_CONTROLE_EXTRATO;
    END;
GO


--EXEC P_RC_CLI_CONV_PBM_CONTROLE_EXTRATO 1, '','2016-06-01','2016-06-17',550524,1

CREATE PROCEDURE P_RC_CLI_CONV_PBM_CONTROLE_EXTRATO @CD_EMP    INT, 
                                                    @CD_FILIAL VARCHAR(MAX) = '', 
                                                    @DT_INI    DATETIME     = NULL, 
                                                    @DT_FIM    DATETIME     = NULL, 
                                                    @CD_PROD   INT, 
                                                    @TP_SALDO  INT          = 0
AS
    BEGIN
        DECLARE @DT_ATUAL DATETIME;
        DECLARE @DT_PROC DATETIME;
        SET NOCOUNT ON;
        DECLARE @dtInicioMes DATETIME
			, @dtInicioMesFechamento DATETIME
			, @dtInicioMesAnterior DATETIME
			, @dtDiaFinalMesFechamento DATETIME
			, @ano INT, @mes VARCHAR(2)
			, @anoAnt INT, @mesAnt INT
			, @anoFecha INT
			, @mesFecha INT
			, @QtdeMesesProc INT
			, @QtdeMesProc INT;


        IF @DT_INI IS NULL
            BEGIN
                SET @DT_INI = GETDATE();
            END;
        IF @DT_FIM IS NULL
            BEGIN
                SET @DT_FIM = GETDATE();
            END;
        SET @DT_ATUAL = @DT_INI;
        SET @ANO = YEAR(@DT_ATUAL);
        SET @MES = MONTH(@DT_ATUAL);
        IF LEN(@mes) = 1
            SET @mes = '0' + @mes;
        SELECT @dtInicioMes = CONVERT(CHAR(8), CONVERT(CHAR(4), @ano) + @mes + '01');

        CREATE TABLE #TMPFILIAL(cd_emp    INT, cd_filial INT);

        IF @CD_FILIAL = ''
            BEGIN
                INSERT INTO #TMPFILIAL
                       SELECT CD_EMP, 
                              CD_FILIAL
                       FROM PRC_FILIAL;
            END;
            ELSE
            BEGIN
                INSERT INTO #TMPFILIAL
                       SELECT CD_EMP, 
                              CD_FILIAL
                       FROM PRC_FILIAL
                       WHERE CD_EMP = @CD_EMP
                             AND CD_FILIAL IN
                       (
                           SELECT ID
                           FROM UFD_PRM_IN_STRING(@CD_FILIAL)
                       );
            END;
        CREATE TABLE #RsProcEstFechamento
        (CD_EMP      INT, 
         CD_FILIAL   INT, 
         CD_PROD     INT, 
         DT_FECHA    DATETIME, 
         HISTORICO   VARCHAR(1800), 
         QT_IT_FECHA MONEY
        );
        CREATE TABLE #RsVendasPBMProc
        (ORDEM          INT IDENTITY(1, 1), 
         CD_EMP         INT, 
         CD_FILIAL      INT, 
         DT_MOV         DATETIME, 
         HISTORICO      VARCHAR(1800), 
         CD_PROD        INT, 
         QT_IT_VD       MONEY, 
         QT_IT_ENT      MONEY, 
         QT_IT_FECHA    MONEY, 
         QT_IT_SALDO    MONEY, 
         CD_DOCUMENTO   INT, 
         TIPO_TRANSACAO INT, 
         DT_REGISTRO    DATETIME
        );
        CREATE TABLE #RsProcEntradaPBM
        (CD_EMP        INT, 
         CD_FILIAL     INT, 
         CD_NF         INT, 
         PERC_ATENDIDO INT
        );
        SELECT @dtInicioMesFechamento = @dtInicioMes, 
               @dtDiaFinalMesFechamento = @DT_FIM, 
               @dtInicioMesAnterior = DATEADD(month, -1, @dtInicioMesFechamento), 
               @anoAnt = DATEPART(year, @dtInicioMesAnterior), 
               @mesAnt = DATEPART(month, @dtInicioMesAnterior), 
               @anoFecha = DATEPART(year, @dtInicioMesFechamento), 
               @mesFecha = DATEPART(month, @dtInicioMesFechamento);

/****************************************************************************************************************************/

        PRINT 'Buscando notas de entradas 100% PBM ' + CONVERT(VARCHAR(10), @anoAnt) + ' ' + CONVERT(VARCHAR, @MesAnt, 112) + ' ' + CONVERT(VARCHAR, GETDATE(), 108);
		
        INSERT INTO #RsProcEntradaPBM
        SELECT EST_NF_ENT.CD_EMP, 
                EST_NF_ENT.CD_FILIAL, 
                EST_NF_ENT.CD_NF, 
                100--REPOSICAO_PBM.PERC_ATEND
        FROM EST_NF_ENT
            JOIN #TMPFILIAL F ON F.CD_EMP = EST_NF_ENT.CD_EMP
                                    AND F.CD_FILIAL = EST_NF_ENT.CD_FILIAL
            --INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT D ON D.CD_EMP = EST_NF_ENT.CD_EMP
            --                                                        AND D.CD_FILIAL = EST_NF_ENT.CD_FILIAL
            --                                                        AND D.CD_NF = EST_NF_ENT.CD_NF
            --INNER JOIN V_EST_NF_ENT_DANFE_PROVISORIO_REPOSICAO_PBM REPOSICAO_PBM ON REPOSICAO_PBM.CD_EMP = D.CD_EMP
            --                                                                        AND REPOSICAO_PBM.CD_CTR = D.CD_CTR
        WHERE 
			EST_NF_ENT.CD_EMP = @CD_EMP
            AND EST_NF_ENT.DT_ENT BETWEEN @DTINICIOMESFECHAMENTO AND @DTDIAFINALMESFECHAMENTO
			AND EST_NF_ENT.DT_ENT BETWEEN @DTINICIOMESFECHAMENTO AND @DTDIAFINALMESFECHAMENTO
            AND   EST_NF_ENT.FLAG_REPOSICAO_PBM=1--(REPOSICAO_PBM.PERC_ATEND = 100 );

		--Vinculadas pelo usuario
		INSERT INTO #RsProcEntradaPBM
        SELECT 
				e.CD_EMP, 
                e.CD_FILIAL, 
                e.CD_NF, 
                100 PERC_ATEND 
			FROM 
				EST_NF_ENT_PBM  e
				LEFT JOIN #RsProcEntradaPBM D ON 
						E.CD_EMP	= D.CD_EMP
                    AND E.CD_FILIAL = D.CD_FILIAL
                    AND E.CD_NF		= D.CD_NF
		WHERE D.CD_EMP IS NULL;


        PRINT 'Buscando dados ano\mes anterior ' + CONVERT(VARCHAR(10), @anoAnt) + ' ' + CONVERT(VARCHAR, @MesAnt, 112) + ' ' + CONVERT(VARCHAR, GETDATE(), 108);

        IF EXISTS( SELECT COUNT(CD_FILIAL) FROM #TMPFILIAL
						HAVING COUNT(CD_FILIAL) = 1 )
            BEGIN
                INSERT INTO #RsProcEstFechamento (CD_EMP,  CD_FILIAL,  CD_PROD,  DT_FECHA,  HISTORICO,  QT_IT_FECHA)

                SELECT RC_CLI_CONV_PBM_CONTROLE_EST_PROD_FECHA_MENSAL.CD_EMP, 
                        RC_CLI_CONV_PBM_CONTROLE_EST_PROD_FECHA_MENSAL.CD_FILIAL, 
                        RC_CLI_CONV_PBM_CONTROLE_EST_PROD_FECHA_MENSAL.CD_PROD, 
                        DATEADD(day, -1, @dtInicioMesFechamento), 
                        'SALDO INICIAL DO MES ANTERIOR', 
                        QT_SALDO AS QT_IT_FECHA
                FROM RC_CLI_CONV_PBM_CONTROLE_EST_PROD_FECHA_MENSAL
                    INNER JOIN #TMPFILIAL P ON RC_CLI_CONV_PBM_CONTROLE_EST_PROD_FECHA_MENSAL.CD_EMP = P.CD_EMP
                                                AND RC_CLI_CONV_PBM_CONTROLE_EST_PROD_FECHA_MENSAL.CD_FILIAL = P.CD_FILIAL
                WHERE RC_CLI_CONV_PBM_CONTROLE_EST_PROD_FECHA_MENSAL.ANO = @anoAnt
                        AND RC_CLI_CONV_PBM_CONTROLE_EST_PROD_FECHA_MENSAL.MES = @mesAnt
                        AND RC_CLI_CONV_PBM_CONTROLE_EST_PROD_FECHA_MENSAL.CD_PROD = @CD_PROD;
                
				IF NOT EXISTS(SELECT TOP 1 CD_PROD FROM #RsProcEstFechamento )
                    BEGIN
						INSERT INTO #RsProcEstFechamento (CD_EMP,  CD_FILIAL, CD_PROD, 
															DT_FECHA, HISTORICO, QT_IT_FECHA)
						SELECT P.CD_EMP, 
								P.CD_FILIAL, 
								@CD_PROD, 
								DATEADD(day, -1, @dtInicioMesFechamento), 
								'SALDO INICIAL DO MES ANTERIOR', 
								0 AS QT_IT_FECHA
						FROM #TMPFILIAL P;
                    END;
            END;
            ELSE
            BEGIN

			 
                INSERT INTO #RsProcEstFechamento (CD_EMP, CD_FILIAL, CD_PROD, DT_FECHA, HISTORICO, QT_IT_FECHA)
                SELECT 
					RC_CLI_CONV_PBM_CONTROLE_EST_PROD_FECHA_MENSAL.CD_EMP, 
                        0 AS CD_FILIAL, 
                        CD_PROD, 
                        DATEADD(day, -1, @dtInicioMesFechamento), 
                        'SALDO INICIAL DO MES ANTERIOR - ' +Convert(varchar,@mesAnt) + ' - ' + convert(varchar,@anoAnt) , 
                        SUM(RC_CLI_CONV_PBM_CONTROLE_EST_PROD_FECHA_MENSAL.QT_SALDO) AS QT_IT_FECHA
                FROM 
					RC_CLI_CONV_PBM_CONTROLE_EST_PROD_FECHA_MENSAL
                WHERE 
					RC_CLI_CONV_PBM_CONTROLE_EST_PROD_FECHA_MENSAL.ANO = @anoAnt
					AND RC_CLI_CONV_PBM_CONTROLE_EST_PROD_FECHA_MENSAL.MES = @mesAnt
					AND RC_CLI_CONV_PBM_CONTROLE_EST_PROD_FECHA_MENSAL.CD_EMP = @CD_EMP
					AND RC_CLI_CONV_PBM_CONTROLE_EST_PROD_FECHA_MENSAL.CD_PROD = @CD_PROD
                GROUP BY 
					RC_CLI_CONV_PBM_CONTROLE_EST_PROD_FECHA_MENSAL.CD_EMP, 
                    RC_CLI_CONV_PBM_CONTROLE_EST_PROD_FECHA_MENSAL.CD_PROD;


                IF NOT EXISTS
                (
                    SELECT TOP 1 CD_PROD
                    FROM #RsProcEstFechamento
                )
                    BEGIN
                        INSERT INTO #RsProcEstFechamento
                        (CD_EMP, 
                         CD_FILIAL, 
                         CD_PROD, 
                         DT_FECHA, 
                         HISTORICO, 
                         QT_IT_FECHA
                        )
                               SELECT @CD_EMP, 
                                      0 AS CD_FILIAL, 
                                      @CD_PROD, 
                                      DATEADD(day, -1, @dtInicioMesFechamento), 
                                      'SALDO INICIAL DO MES ANTERIOR', 
                                      0 AS QT_IT_FECHA;
                    END;
            END;
			        
        INSERT INTO #RsVendasPBMProc(CD_EMP,  CD_FILIAL,  CD_PROD,  DT_MOV,  HISTORICO,  QT_IT_VD,  
										QT_IT_ENT, QT_IT_FECHA, QT_IT_SALDO, CD_DOCUMENTO, TIPO_TRANSACAO, DT_REGISTRO)
        SELECT F.CD_EMP, 
                F.CD_FILIAL, 
                F.CD_PROD, 
                F.DT_FECHA, 
                F.HISTORICO, 
                0 AS QT_IT_VD, 
                0 AS QT_IT_ENT, 
                SUM(QT_IT_FECHA) AS QT_IT_FECHA, 
                0 AS QT_IT_SALDO, 
                0 AS CD_DOCUMENTO, 
                0 AS TIPO_TRANSACAO, 
                GETDATE()
        FROM #RsProcEstFechamento F
        GROUP BY F.CD_EMP, 
                F.CD_FILIAL, 
                F.CD_PROD, 
                F.DT_FECHA, 
                F.HISTORICO;

        PRINT 'Periodo analise ' + CONVERT(VARCHAR, @dtInicioMesFechamento, 112) + ' a ' + CONVERT(VARCHAR, @dtDiaFinalMesFechamento, 112);
        PRINT 'Gerando movimento de vendas ' + CONVERT(VARCHAR, GETDATE(), 108);

        INSERT INTO #RsVendasPBMProc
        (CD_EMP, 
         CD_FILIAL, 
         CD_PROD, 
         DT_MOV, 
         HISTORICO, 
         QT_IT_VD, 
         QT_IT_ENT, 
         QT_IT_FECHA, 
         QT_IT_SALDO, 
         CD_DOCUMENTO, 
         TIPO_TRANSACAO, 
         DT_REGISTRO
        )
               SELECT PDV_VD_IT.CD_EMP, 
                      PDV_VD_IT.CD_FILIAL, 
                      PDV_VD_IT.CD_PROD, 
                      PDV_VD_IT.DT_VD, 
                      'VENDAS CUPOM FISCAL NR.: ' + CONVERT(VARCHAR(10), PDV_VD.NR_ECF) + '   PDV   ' + CONVERT(VARCHAR(4), PDV_VD.CD_CX) + '    AUT.: ' + ISNULL(PDV_VD_IT_VD_PBM.NR_AUTORIZACAO, ''), 
                      PDV_VD_IT.QT_IT AS QT_IT_VD, 
                      0 AS QT_IT_ENT, 
                      0 AS QT_IT_FECHA, 
                      0 AS QT_IT_SALDO, 
                      PDV_VD_IT.CD_VD, 
                      1 AS TIPO_TRANSACAO, 
                      PDV_VD.DT_CONSD
               FROM PDV_VD_IT
                    INNER JOIN PDV_VD ON PDV_VD_IT.CD_EMP = PDV_VD.CD_EMP
                                         AND PDV_VD_IT.CD_FILIAL = PDV_VD.CD_FILIAL
                                         AND PDV_VD_IT.CD_VD = PDV_VD.CD_VD
                    INNER JOIN PDV_VD_IT_VD_PBM ON PDV_VD_IT.CD_EMP = PDV_VD_IT_VD_PBM.CD_EMP
                                                   AND PDV_VD_IT.CD_FILIAL = PDV_VD_IT_VD_PBM.CD_FILIAL
                                                   AND PDV_VD_IT.CD_VD = PDV_VD_IT_VD_PBM.CD_VD
                                                   AND PDV_VD_IT.CD_IT = PDV_VD_IT_VD_PBM.CD_IT
                    INNER JOIN RC_CLI_CONV_VINC_RC_CLI ON PDV_VD_IT_VD_PBM.CD_EMP = RC_CLI_CONV_VINC_RC_CLI.CD_EMP
                                                          AND PDV_VD_IT_VD_PBM.CD_CLI_PBM = RC_CLI_CONV_VINC_RC_CLI.CD_CLI
                    INNER JOIN RC_CLI_CONV_PBM ON RC_CLI_CONV_VINC_RC_CLI.CD_EMP = RC_CLI_CONV_PBM.CD_EMP
                                                  AND RC_CLI_CONV_VINC_RC_CLI.CD_CONV = RC_CLI_CONV_PBM.CD_CONV
                                                  AND PDV_VD_IT.DT_VD >= RC_CLI_CONV_PBM.DT_ATIVAR_CONTROLE
                    LEFT OUTER JOIN PDV_VD_IT_VD_PBM_GLOSADA ON PDV_VD_IT.CD_EMP = PDV_VD_IT_VD_PBM_GLOSADA.CD_EMP
                                                                AND PDV_VD_IT.CD_FILIAL = PDV_VD_IT_VD_PBM_GLOSADA.CD_FILIAL
                                                                AND PDV_VD_IT.CD_VD = PDV_VD_IT_VD_PBM_GLOSADA.CD_VD
                                                                AND PDV_VD_IT.CD_IT = PDV_VD_IT_VD_PBM_GLOSADA.CD_IT
                    LEFT OUTER JOIN PDV_VD_IT_VD_PBM_FINANCEIRO ON PDV_VD_IT.CD_EMP = PDV_VD_IT_VD_PBM_FINANCEIRO.CD_EMP
                                                                   AND PDV_VD_IT.CD_FILIAL = PDV_VD_IT_VD_PBM_FINANCEIRO.CD_FILIAL
                                                                   AND PDV_VD_IT.CD_VD = PDV_VD_IT_VD_PBM_FINANCEIRO.CD_VD
                                                                   AND PDV_VD_IT.CD_IT = PDV_VD_IT_VD_PBM_FINANCEIRO.CD_IT
                    INNER JOIN #TMPFILIAL P ON PDV_VD_IT.CD_EMP = P.CD_EMP
                                               AND PDV_VD_IT.CD_FILIAL = P.CD_FILIAL
               WHERE PDV_VD_IT.CD_EMP = @CD_EMP
                     AND PDV_VD_IT.ST_IT = 1
                     AND PDV_VD.ST_VD = 0
                     AND PDV_VD_IT.DT_VD BETWEEN @dtInicioMesFechamento AND @dtDiaFinalMesFechamento
                     AND RC_CLI_CONV_PBM.FLAG_POSSUI_REPOSICAO_PRODUTOS = 1
                     AND PDV_VD_IT_VD_PBM_GLOSADA.CD_IT IS NULL
                     AND PDV_VD_IT_VD_PBM_FINANCEIRO.CD_IT IS NULL
                     AND PDV_VD_IT.CD_PROD = @CD_PROD
               UNION ALL
               SELECT RC_CLI_CONV_PBM_CONTROLE_AJUSTES.CD_EMP, 
                      RC_CLI_CONV_PBM_CONTROLE_AJUSTES.CD_FILIAL, 
                      RC_CLI_CONV_PBM_CONTROLE_AJUSTES.CD_PROD, 
                      RC_CLI_CONV_PBM_CONTROLE_AJUSTES.DT_MOVIMENTO, 
                      'AJUSTE ACRESCIMO USUARIO ' + GLB_USU.NM_USU, 
                      RC_CLI_CONV_PBM_CONTROLE_AJUSTES.QT_MOVIMENTO AS QT_IT_VD, 
                      0 AS QT_IT_ENT, 
                      0 AS QT_IT_FECHA, 
                      0 AS QT_IT_SALDO, 
                      RC_CLI_CONV_PBM_CONTROLE_AJUSTES.CD_CTR, 
                      3 AS TIPO_TRANSACAO, 
                      RC_CLI_CONV_PBM_CONTROLE_AJUSTES.DT_CAD
               FROM RC_CLI_CONV_PBM_CONTROLE_AJUSTES
                    INNER JOIN GLB_USU ON RC_CLI_CONV_PBM_CONTROLE_AJUSTES.CD_USU = GLB_USU.CD_USU
                    INNER JOIN #TMPFILIAL PR ON RC_CLI_CONV_PBM_CONTROLE_AJUSTES.CD_EMP = PR.CD_EMP
                                                AND RC_CLI_CONV_PBM_CONTROLE_AJUSTES.CD_FILIAL = PR.CD_FILIAL
               WHERE RC_CLI_CONV_PBM_CONTROLE_AJUSTES.CD_EMP = @CD_EMP
                     AND RC_CLI_CONV_PBM_CONTROLE_AJUSTES.CD_PROD = @CD_PROD
                     AND RC_CLI_CONV_PBM_CONTROLE_AJUSTES.DT_MOVIMENTO BETWEEN @dtInicioMesFechamento AND @dtDiaFinalMesFechamento
                     AND RC_CLI_CONV_PBM_CONTROLE_AJUSTES.TP_TRANSACAO = 1;
        PRINT 'Gerando movimento de entrada ' + CONVERT(VARCHAR, GETDATE(), 108);
        INSERT INTO #RsVendasPBMProc
        (CD_EMP, 
         CD_FILIAL, 
         CD_PROD, 
         DT_MOV, 
         HISTORICO, 
         QT_IT_VD, 
         QT_IT_ENT, 
         QT_IT_FECHA, 
         QT_IT_SALDO, 
         CD_DOCUMENTO, 
         TIPO_TRANSACAO, 
         DT_REGISTRO
        )
               SELECT EST_NF_ENT_IT.CD_EMP, 
                      EST_NF_ENT_IT.CD_FILIAL, 
                      EST_NF_ENT_IT.CD_PROD, 
                      EST_NF_ENT_IT.DT_ENT, 
                      DS_MOV_OP + ' REF. NOTA FISCAL NR.: ' + CONVERT(VARCHAR(10), NR_NF) + '   CD. ORIGEM.: ' + CONVERT(VARCHAR(10), CD_ORIG) + ' CIDADE: ' + DS_CID + ' - ' + UF, 
                      0 AS QT_IT_VD, 
                      EST_NF_ENT_IT.QT_IT AS QT_IT_ENT, 
                      0 AS QT_IT_FECHA, 
                      0 AS QT_IT_SALDO, 
                      EST_NF_ENT_IT.CD_NF, 
                      2 AS TIPO_TRANSACAO, 
                      CONVERT(CHAR(10), COALESCE(V_EST_NF_ENT_CAB.DT_HR_CAD, V_EST_NF_ENT_CAB.DT_ENT), 120) + ' ' + CONVERT(CHAR(5), ISNULL(V_EST_NF_ENT_CAB.DT_HR_CAD, ''), 114)
               FROM V_EST_NF_ENT_CAB
                    INNER JOIN EST_NF_ENT_IT ON V_EST_NF_ENT_CAB.CD_EMP = EST_NF_ENT_IT.CD_EMP
                                                AND V_EST_NF_ENT_CAB.CD_FILIAL = EST_NF_ENT_IT.CD_FILIAL
                                                AND V_EST_NF_ENT_CAB.CD_NF = EST_NF_ENT_IT.CD_NF
                    INNER JOIN
               (
                   SELECT c.CD_EMP, 
                          c.CD_PROD, 
                          1 AS QT_IT, 
                          PBM.DT_ATIVAR_CONTROLE
                   FROM EST_PROD_RC_CLI_CONV c
                        INNER JOIN RC_CLI_CONV_PBM pbm ON C.CD_EMP = pbm.CD_EMP
                                                          AND C.CD_CONV = pbm.CD_CONV
                   WHERE pbm.FLAG_POSSUI_REPOSICAO_PRODUTOS = 1
                   GROUP BY c.CD_EMP, 
                            c.CD_PROD, 
                            PBM.DT_ATIVAR_CONTROLE
               ) P ON EST_NF_ENT_IT.CD_PROD = P.CD_PROD
                      AND EST_NF_ENT_IT.CD_EMP = P.CD_EMP
                      AND EST_NF_ENT_IT.DT_ENT >= P.DT_ATIVAR_CONTROLE
                    LEFT OUTER JOIN EST_NF_ENT_IT_PBM_GLOSADA ON EST_NF_ENT_IT.CD_EMP = EST_NF_ENT_IT_PBM_GLOSADA.CD_EMP
                                                                 AND EST_NF_ENT_IT.CD_FILIAL = EST_NF_ENT_IT_PBM_GLOSADA.CD_FILIAL
                                                                 AND EST_NF_ENT_IT.CD_NF = EST_NF_ENT_IT_PBM_GLOSADA.CD_NF
                                                                 AND EST_NF_ENT_IT.CD_PROD = EST_NF_ENT_IT_PBM_GLOSADA.CD_PROD
                    INNER JOIN #TMPFILIAL PR ON EST_NF_ENT_IT.CD_EMP = PR.CD_EMP
                                                AND EST_NF_ENT_IT.CD_FILIAL = PR.CD_FILIAL
                    INNER JOIN #RsProcEntradaPBM RsProcEntradaPBM ON RsProcEntradaPBM.CD_EMP = V_EST_NF_ENT_CAB.CD_EMP
                                                                     AND RsProcEntradaPBM.CD_FILIAL = V_EST_NF_ENT_CAB.CD_FILIAL
                                                                     AND RsProcEntradaPBM.CD_NF = V_EST_NF_ENT_CAB.CD_NF
               WHERE EST_NF_ENT_IT.CD_EMP = @CD_EMP
                     AND EST_NF_ENT_IT.CD_PROD = @CD_PROD
                     AND EST_NF_ENT_IT.DT_ENT BETWEEN @dtInicioMesFechamento AND @dtDiaFinalMesFechamento
                     AND EST_NF_ENT_IT_PBM_GLOSADA.CD_NF IS NULL
               --AND V_EST_NF_ENT_CAB.FLAG_REPOSICAO_PBM=1
               UNION ALL
               SELECT RC_CLI_CONV_PBM_CONTROLE_AJUSTES.CD_EMP, 
                      RC_CLI_CONV_PBM_CONTROLE_AJUSTES.CD_FILIAL, 
                      RC_CLI_CONV_PBM_CONTROLE_AJUSTES.CD_PROD, 
                      RC_CLI_CONV_PBM_CONTROLE_AJUSTES.DT_MOVIMENTO,
                      CASE
                          WHEN RC_CLI_CONV_PBM_CONTROLE_AJUSTES.ORIGEM_TRANSACAO = 0
                          THEN 'AJUSTE RETIRADA USUARIO ' + GLB_USU.NM_USU
                          ELSE RC_CLI_CONV_PBM_CONTROLE_AJUSTES.HISTORICO
                      END, 
                      0 AS QT_IT_VD, 
                      RC_CLI_CONV_PBM_CONTROLE_AJUSTES.QT_MOVIMENTO AS QT_IT_ENT, 
                      0 AS QT_IT_FECHA, 
                      0 AS QT_IT_SALDO, 
                      RC_CLI_CONV_PBM_CONTROLE_AJUSTES.CD_CTR, 
                      4 AS TIPO_TRANSACAO, 
                      RC_CLI_CONV_PBM_CONTROLE_AJUSTES.DT_CAD
               FROM RC_CLI_CONV_PBM_CONTROLE_AJUSTES
                    INNER JOIN GLB_USU ON RC_CLI_CONV_PBM_CONTROLE_AJUSTES.CD_USU = GLB_USU.CD_USU
                    INNER JOIN #TMPFILIAL PR ON RC_CLI_CONV_PBM_CONTROLE_AJUSTES.CD_EMP = PR.CD_EMP
                                                AND RC_CLI_CONV_PBM_CONTROLE_AJUSTES.CD_FILIAL = PR.CD_FILIAL
               WHERE RC_CLI_CONV_PBM_CONTROLE_AJUSTES.CD_EMP = @CD_EMP
                     AND RC_CLI_CONV_PBM_CONTROLE_AJUSTES.CD_PROD = @CD_PROD
                     AND RC_CLI_CONV_PBM_CONTROLE_AJUSTES.DT_MOVIMENTO BETWEEN @dtInicioMesFechamento AND @dtDiaFinalMesFechamento
                     AND RC_CLI_CONV_PBM_CONTROLE_AJUSTES.TP_TRANSACAO = 0;
        DECLARE @DT_MOV DATETIME, @ORDEM INT, @QT_IT_VD MONEY, @QT_IT_ENT MONEY, @QT_IT_FECHA MONEY, @QT_SLD MONEY;
        SET @QT_SLD = 0;
        DECLARE CalcMovPBMExtrato CURSOR FAST_FORWARD
        FOR SELECT DT_MOV, 
                   ORDEM, 
                   QT_IT_VD, 
                   QT_IT_ENT, 
                   QT_IT_FECHA
            FROM #RsVendasPBMProc
            ORDER BY DT_MOV;
        OPEN CalcMovPBMExtrato;
        FETCH NEXT FROM CalcMovPBMExtrato INTO @DT_MOV, @ORDEM, @QT_IT_VD, @QT_IT_ENT, @QT_IT_FECHA;
        WHILE @@FETCH_STATUS = 0
            BEGIN
                UPDATE #RsVendasPBMProc
                  SET 
                      @QT_SLD = @QT_SLD + @QT_IT_FECHA + @QT_IT_VD - @QT_IT_ENT, 
                      QT_IT_SALDO = @QT_SLD
                WHERE ORDEM = @ORDEM;
                --Proximo registro
                FETCH NEXT FROM CalcMovPBMExtrato INTO @DT_MOV, @ORDEM, @QT_IT_VD, @QT_IT_ENT, @QT_IT_FECHA;
            END;
        --Fechando cursos
        CLOSE CalcMovPBMExtrato;
        --Desalocando cursos da memoria
        DEALLOCATE CalcMovPBMExtrato;

        SELECT *
        FROM #RSVENDASPBMPROC
        ORDER BY DT_MOV;
        RETURN;

        DROP TABLE #RsVendasPBMProc;
        DROP TABLE #TMPFILIAL;
        DROP TABLE #RsProcEstFechamento;
    END;