CREATE OR REPLACE TRIGGER USR_BLOQUEIA_DUPLICACAO BEFORE INSERT ON NOTAFISCAL FOR EACH ROW
DECLARE
   V_NUMANT NUMBER;
   V_IDINFCPFCNPJNF VARCHAR2(1);
   V_LANCTONF  VARCHAR2(10);
BEGIN
   IF :NEW.NRACESSONFE IS NOT NULL THEN
      IF (:NEW.IDENTRSAIDOP = 'E') AND NOT(:NEW.IDSTATUSNFE = 'C') AND NOT(:NEW.IDSTATUS = 'C') AND NOT(:NEW.IDSTATUSNFE = 'D') THEN
         SELECT MAX(NRLANCTONF)
           INTO V_LANCTONF
           FROM NOTAFISCAL
          WHERE NRACESSONFE  = :NEW.NRACESSONFE
            AND IDENTRSAIDOP = 'E';

         IF V_LANCTONF IS NOT NULL THEN
            RAISE_APPLICATION_ERROR(-20501, 'DOCUMENTO JA LANCADO NO SISTEMA.', TRUE);
         END IF;
      END IF;
   ELSE
      IF ((:NEW.IDENTRSAIDOP = 'E') AND NOT(:NEW.IDSTATUSNFE = 'C') AND NOT(:NEW.IDSTATUS = 'C') AND (NOT :NEW.NRNOTAFISC IS NULL)) AND NOT(:NEW.IDSTATUSNFE = 'D') THEN

         SELECT TO_NUMBER(MAX(NVL(NRLANCTONF,'0')))
           INTO V_NUMANT
           FROM NOTAFISCAL
          WHERE CDFILIRECE   = :NEW.CDFILIRECE
            AND NRNOTAFISC   = :NEW.NRNOTAFISC
            AND CDSERIEENTR  = :NEW.CDSERIEENTR
            AND IDENTRSAIDOP = :NEW.IDENTRSAIDOP
            AND NRINSJURNF   = :NEW.NRINSJURNF
            AND CDMODDOCFISC = :NEW.CDMODDOCFISC
            AND VRNOTAFISC   = :NEW.VRNOTAFISC;

         IF (TO_NUMBER(:NEW.NRLANCTONF) - V_NUMANT) < 4 THEN

            SELECT IDINFCPFCNPJNF
              INTO V_IDINFCPFCNPJNF
              FROM TIPOOPERAC
             WHERE CDTIPOOPER     = :NEW.CDTIPOOPER
               AND IDENTRSAIDOP   = :NEW.IDENTRSAIDOP;

            IF V_IDINFCPFCNPJNF <> 'S' THEN
               RAISE_APPLICATION_ERROR(-20501, 'DOCUMENTO JA LANCADO NO SISTEMA.', TRUE);
            END IF;
         END IF;
      END IF;
   END IF;
END;
/