IF EXISTS (SELECT *
             FROM SYSOBJECTS O, SYSUSERS U
            WHERE O.NAME = 'ATUALIZA_CTBL_IMPOSTONF'
	      AND TYPE = 'P'
	      AND U.UID = O.UID
	      AND U.NAME = USER)
DROP PROCEDURE ATUALIZA_CTBL_IMPOSTONF
GO

CREATE PROCEDURE ATUALIZA_CTBL_IMPOSTONF
   @P_CDIMPOSTO      VARCHAR(02),
   @P_NRSEQUMAPAPU   VARCHAR(10)
AS
   DECLARE @CDFILIAL     VARCHAR(4);
   DECLARE @NRLANCTONF   VARCHAR(10);
   DECLARE @CDIMPOSTO    VARCHAR(2);
   DECLARE @CDTIPOOPER   VARCHAR(2);
   DECLARE @IDENTRSAIDOP VARCHAR(1);
   DECLARE @CDFILIMOVI   VARCHAR(4);
   DECLARE @V_CDPRODUTO  VARCHAR(10);
   DECLARE @V_CDCONTCTBL VARCHAR(20);
BEGIN
   DECLARE C CURSOR FOR
      SELECT DISTINCT I.CDFILIAL, I.NRLANCTONF, I.CDIMPOSTO, N.CDTIPOOPER, N.IDENTRSAIDOP,
             (CASE N.IDENTRSAIDOP WHEN 'E' THEN N.CDFILIRECE ELSE N.CDFILIEMIT END) AS CDFILIMOVI
        FROM IMPOSTONF I, NOTAFISCAL N
       WHERE I.CDFILIAL     = N.CDFILIAL
         AND I.NRLANCTONF   = N.NRLANCTONF
         AND I.CDIMPOSTO    = @P_CDIMPOSTO
         AND I.NRSEQUMAPAPU = @P_NRSEQUMAPAPU
         AND I.CDCCTBLIMPNF IS NULL
         AND N.IDSTATUS IN ('A','E');
   OPEN C;
   FETCH NEXT FROM C INTO @CDFILIAL, @NRLANCTONF, @CDIMPOSTO, @CDTIPOOPER, @IDENTRSAIDOP, @CDFILIMOVI;
   WHILE (@@FETCH_STATUS = 0) BEGIN

      SELECT @V_CDCONTCTBL = MAX(CDCONTPROD)
        FROM TIPOOPERAC
       WHERE IDENTRSAIDOP = @IDENTRSAIDOP
         AND CDTIPOOPER = @CDTIPOOPER;

      IF @V_CDCONTCTBL IS NULL BEGIN

         SELECT @V_CDPRODUTO = MAX(CDPRODUTO)
           FROM ITEMPRODUTO
          WHERE CDFILIAL = @CDFILIAL
            AND NRLANCTONF = @NRLANCTONF
            AND NRSEQITPROD = (SELECT MIN(NRSEQITPROD)
                                 FROM ITEMPROIMPOS
                                WHERE CDFILIAL = @CDFILIAL
                                  AND NRLANCTONF = @NRLANCTONF
                                  AND CDIMPOSTO = @P_CDIMPOSTO
                                  AND CDFISCALIT = '1');

         SELECT @V_CDCONTCTBL = MAX(CASE @IDENTRSAIDOP WHEN 'E' THEN CDCTBLENTRPF ELSE CDCTBLSAIDPF END)
           FROM PRODFILI
          WHERE CDFILIAL = @CDFILIMOVI
            AND CDPRODUTO = @V_CDPRODUTO;

         IF @V_CDCONTCTBL IS NULL BEGIN
            SET @V_CDCONTCTBL = TEKNISA.CTBL_PRODUTO(@V_CDPRODUTO, @IDENTRSAIDOP);
         END;
      END;

      IF @V_CDCONTCTBL IS NOT NULL BEGIN
         UPDATE IMPOSTONF
            SET CDCCTBLIMPNF = @V_CDCONTCTBL
          WHERE CDFILIAL = @CDFILIAL
            AND NRLANCTONF = @NRLANCTONF
            AND CDIMPOSTO = @CDIMPOSTO;
      END;

      FETCH NEXT FROM C INTO @CDFILIAL, @NRLANCTONF, @CDIMPOSTO, @CDTIPOOPER, @IDENTRSAIDOP, @CDFILIMOVI;
   END;
   CLOSE C;
   DEALLOCATE C;
   COMMIT;
END;
GO

-- VERSAO --
EXEC ATUVEROBJ 'ATUALIZA_CTBL_IMPOSTONF','5.25.000';
GO
