CREATE OR REPLACE TRIGGER GERA_LOGPREVPAXM AFTER INSERT OR UPDATE OR DELETE ON PREVISAOPAXM
FOR EACH ROW
DECLARE
  V_QTTOTPAXAT   PREVISAOPAXM.QTTOTPAXAT%TYPE;
  V_QTPAXSBY     PREVISAOPAXM.QTPAXSBY%TYPE;
  V_CDLOGPRPAXLP VARCHAR2(20);
BEGIN
   NOVO_CODIGO_NT('LOGPREVPAXM',V_CDLOGPRPAXLP,1);
   V_CDLOGPRPAXLP := SUBSTR(V_CDLOGPRPAXLP,11,10);

/*   SELECT LPAD((NVL(MAX(CDLOGPRPAXLP),0)+1),10,'0')
   INTO V_CDLOGPRPAXLP
   FROM LOGPREVPAXM;*/

   IF UPDATING THEN
   BEGIN

      V_QTTOTPAXAT:= NVL(:NEW.QTTOTPAXAT, 0);
      V_QTPAXSBY  := NVL(:NEW.QTPAXSBY, 0);

      IF (:OLD.QTTOTPAXAT  <> :NEW.QTTOTPAXAT) OR (:OLD.QTPAXSBY <> :NEW.QTPAXSBY) THEN
        INSERT INTO LOGPREVPAXM
         (CDFILIAL, CDCIAPAXLP,NRVOOLP,CDTRECHOLP,CDCLASSELP,DTHRPLAPVLP,
          CDLOGPRPAXLP,DTHRINCLP,QTTOTPAXATLP,CDUSRRESPLP,QTPAXSBYLP,
          IDTPMANUTLP,
          NRORG, NRORGINCLUSAO, NRORGULTATU,
          DTINCLUSAO, DTULTATU,
          CDOPERINCLUSAO, CDOPERULTATU
          )
        VALUES
         (:NEW.CDFILIAL, :NEW.CDCIA,:NEW.NRVOO,:NEW.CDTRECHO,:NEW.CDCLASSE,:NEW.DTHRPLAVOOPV,
          V_CDLOGPRPAXLP,SYSDATE,V_QTTOTPAXAT,:NEW.CDUSRRESPPP,V_QTPAXSBY,
          '2',
          :NEW.NRORG,:NEW.NRORG,:NEW.NRORG,
          SYSDATE, SYSDATE,
          :NEW.CDOPERULTATU, :NEW.CDOPERULTATU);
      END IF;
   END;
   ELSIF DELETING THEN
      INSERT INTO LOGPREVPAXM
       (CDFILIAL, CDCIAPAXLP,NRVOOLP,CDTRECHOLP,CDCLASSELP,DTHRPLAPVLP,
        CDLOGPRPAXLP,DTHRINCLP,QTTOTPAXATLP,CDUSRRESPLP,QTPAXSBYLP,
        IDTPMANUTLP,
        NRORG, NRORGINCLUSAO, NRORGULTATU,
        DTINCLUSAO, DTULTATU,
        CDOPERINCLUSAO, CDOPERULTATU
       )
      VALUES
       (:OLD.CDFILIAL, :OLD.CDCIA,:OLD.NRVOO,:OLD.CDTRECHO,:OLD.CDCLASSE,:OLD.DTHRPLAVOOPV,
        V_CDLOGPRPAXLP,SYSDATE,NVL(:OLD.QTTOTPAXAT, 0.00),:OLD.CDUSRRESPPP,NVL(:OLD.QTPAXSBY, 0.00),
        '3',
        :OLD.NRORG,:OLD.NRORG,:OLD.NRORG,
        SYSDATE, SYSDATE,
        :OLD.CDOPERULTATU, :OLD.CDOPERULTATU);
   ELSE
      INSERT INTO LOGPREVPAXM
       (CDFILIAL, CDCIAPAXLP,NRVOOLP,CDTRECHOLP,CDCLASSELP,DTHRPLAPVLP,
        CDLOGPRPAXLP,DTHRINCLP,QTTOTPAXATLP,CDUSRRESPLP,QTPAXSBYLP,
        IDTPMANUTLP,
        NRORG, NRORGINCLUSAO, NRORGULTATU,
        DTINCLUSAO, DTULTATU,
        CDOPERINCLUSAO, CDOPERULTATU)
      VALUES
       (:NEW.CDFILIAL, :NEW.CDCIA,:NEW.NRVOO,:NEW.CDTRECHO,:NEW.CDCLASSE,:NEW.DTHRPLAVOOPV,
        V_CDLOGPRPAXLP,SYSDATE,NVL(:NEW.QTTOTPAXAT, 0.00),:NEW.CDUSRRESPPP,NVL(:NEW.QTPAXSBY, 0.00),
        '1',
        :NEW.NRORG,:NEW.NRORG,:NEW.NRORG,
        SYSDATE, SYSDATE,
        :NEW.CDOPERULTATU, :NEW.CDOPERULTATU);
   END IF;
END;
/