CREATE OR REPLACE TRIGGER ALTERA_EFECLIFAT
BEFORE INSERT OR UPDATE OR DELETE
ON EFETCLIE FOR EACH ROW
DECLARE
   V_EXISTE       NUMBER;
   V_IDCOPALTEFEPLA VARCHAR2(01);
BEGIN

   SELECT NVL(MAX(IDCOPALTEFEPLA), 'N')
     INTO V_IDCOPALTEFEPLA
     FROM PARAMFILIAL
    WHERE CDFILIAL = :NEW.CDFILIAL;

   IF (V_IDCOPALTEFEPLA = 'S') THEN
      IF INSERTING THEN
         SELECT COUNT(*)
           INTO V_EXISTE
           FROM EFECLIFAT
          WHERE CDFILIAL = :NEW.CDFILIAL
            AND CDSERVFILI = :NEW.CDSERVFILI
            AND CDCLIENTE = :NEW.CDCLIENTE
            AND DTFATURAM = :NEW.DTEFETCLIE;

         IF (V_EXISTE = 0) THEN
            INSERT INTO EFECLIFAT
               (CDFILIAL, CDSERVFILI, CDCLIENTE, DTFATURAM, QTCOMEFATU, CDFILIFATU, NRAPURACFAT)
            VALUES
               (:NEW.CDFILIAL, :NEW.CDSERVFILI, :NEW.CDCLIENTE, :NEW.DTEFETCLIE, :NEW.QTCOMEFETCLI, :NEW.CDFILIFATU, :NEW.NRAPURACFAT);
         ELSE
            UPDATE EFECLIFAT
               SET QTCOMEFATU = :NEW.QTCOMEFETCLI
             WHERE CDFILIAL = :NEW.CDFILIAL
               AND CDSERVFILI = :NEW.CDSERVFILI
               AND CDCLIENTE = :NEW.CDCLIENTE
               AND DTFATURAM = :NEW.DTEFETCLIE;
         END IF;
      END IF;

      IF UPDATING THEN
         SELECT COUNT(*)
           INTO V_EXISTE
           FROM EFECLIFAT
          WHERE CDFILIAL = :NEW.CDFILIAL
            AND CDSERVFILI = :NEW.CDSERVFILI
            AND CDCLIENTE = :NEW.CDCLIENTE
            AND DTFATURAM = :NEW.DTEFETCLIE;

         IF (V_EXISTE = 0) THEN
            INSERT INTO EFECLIFAT
               (CDFILIAL, CDSERVFILI, CDCLIENTE, DTFATURAM, QTCOMEFATU, CDFILIFATU, NRAPURACFAT)
            VALUES
               (:NEW.CDFILIAL, :NEW.CDSERVFILI, :NEW.CDCLIENTE, :NEW.DTEFETCLIE, :NEW.QTCOMEFETCLI, :NEW.CDFILIFATU, :NEW.NRAPURACFAT);
         ELSE
            UPDATE EFECLIFAT
               SET QTCOMEFATU = :NEW.QTCOMEFETCLI
             WHERE CDFILIAL = :NEW.CDFILIAL
               AND CDSERVFILI = :NEW.CDSERVFILI
               AND CDCLIENTE = :NEW.CDCLIENTE
               AND DTFATURAM = :NEW.DTEFETCLIE;
         END IF;
      END IF;
   END IF;

   IF DELETING THEN
      SELECT NVL(MAX(IDCOPALTEFEPLA), 'N')
        INTO V_IDCOPALTEFEPLA
        FROM PARAMFILIAL
       WHERE CDFILIAL = :OLD.CDFILIAL;

      IF (V_IDCOPALTEFEPLA = 'S') THEN
         DELETE FROM EFECLIFAT
          WHERE CDFILIAL = :OLD.CDFILIAL
            AND CDSERVFILI = :OLD.CDSERVFILI
            AND CDCLIENTE = :OLD.CDCLIENTE
            AND DTFATURAM = :OLD.DTEFETCLIE;

      END IF;
   END IF;
END;
/
-- VERSAO --
BEGIN ATUVEROBJ('ALTERA_EFECLIFAT','5.05.025'); END;
/

