CREATE OR REPLACE TRIGGER ATUALIZA_INSERT_LANCTOESTOQ BEFORE INSERT ON LANCTOESTOQ
FOR EACH ROW
DECLARE
   V_IDENTRSAIDOP TIPOOPERAC.IDENTRSAIDOP%TYPE;
   V_CDTIPOOPER   TIPOOPERAC.CDTIPOOPER%TYPE;
   V_IDNFRETIND   TIPOOPERAC.IDNFRETIND%TYPE;
BEGIN
   IF :NEW.IDENTRSAIDOP <> 'E' AND
      :NEW.CDTIPOOPER <> '10'  THEN
      BEGIN
         SELECT N.IDENTRSAIDOP, N.CDTIPOOPER, NVL(T.IDNFRETIND, 'N') AS IDNFRETIND
           INTO V_IDENTRSAIDOP, V_CDTIPOOPER, V_IDNFRETIND
           FROM NOTAFISCAL N, TIPOOPERAC T
          WHERE N.IDENTRSAIDOP = T.IDENTRSAIDOP
            AND N.CDTIPOOPER   = T.CDTIPOOPER
            AND N.CDFILIAL     = :NEW.CDFILIAL
            AND N.NRLANCTONF   = :NEW.NRLANCTONF;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_IDENTRSAIDOP := NULL;
            V_CDTIPOOPER   := NULL;
            V_IDNFRETIND   := 'N';
      END;

      IF (V_IDENTRSAIDOP IS NOT NULL) AND (V_CDTIPOOPER IS NOT NULL) THEN
         IF (V_IDNFRETIND = 'S') AND (:NEW.IDTPLANCTO = '4') THEN
            :NEW.IDENTRSAIDOP := NULL;
            :NEW.CDTIPOOPER   := NULL;
         ELSE
            :NEW.IDENTRSAIDOP := V_IDENTRSAIDOP;
            :NEW.CDTIPOOPER   := V_CDTIPOOPER;
         END IF;
      ELSE
         :NEW.IDENTRSAIDOP := V_IDENTRSAIDOP;
         :NEW.CDTIPOOPER   := V_CDTIPOOPER;
      END IF;
   END IF;
END;
/