CREATE OR REPLACE TRIGGER GERA_LOG_COMPCARD
AFTER INSERT OR UPDATE OR DELETE ON COMPCARD FOR EACH ROW
DECLARE
  V_USUARIO      VARCHAR2(40);
  V_DSREMOTEADDR VARCHAR2(15);
  V_DSREMOTEHOST VARCHAR2(15);
  V_DSSERVERRDM  VARCHAR2(20);
  V_DSSERVMETHOD VARCHAR2(30);
  V_DSREMOTEOPER VARCHAR2(12);
  V_OPERACAO     VARCHAR2(1);
  V_CDPRATOANT   VARCHAR2(10);
  V_CDPRATOATUAL VARCHAR2(10);
  V_CDFILIAL     VARCHAR2(4);
  V_CDSERVFILI   VARCHAR2(5);
  V_CDTIPOPRAT   VARCHAR2(2);
  V_DTMESCARD    DATE;
  V_DTCARDAPIO   DATE;
BEGIN
   NMUSUARIO(V_USUARIO);
   WEBTUNNING(V_DSREMOTEADDR,
              V_DSREMOTEHOST,
              V_DSSERVERRDM,
              V_DSSERVMETHOD,
              V_DSREMOTEOPER);

   SELECT CDSERVFILI, DTMESCARD, DTCARDAPIO
     INTO V_CDSERVFILI, V_DTMESCARD, V_DTCARDAPIO
     FROM CARDADIA
    WHERE CDFILIAL   = NVL(:NEW.CDFILIAL, :OLD.CDFILIAL)
      AND NRCARDAPIO = NVL(:NEW.NRCARDAPIO, :OLD.NRCARDAPIO);

   IF INSERTING THEN
      V_OPERACAO     := 'I'; --insert
      V_CDPRATOANT   := null;
      V_CDPRATOATUAL := :NEW.CDPRATO;
      V_CDTIPOPRAT   := :NEW.CDTIPOPRAT;
      V_CDFILIAL     := :NEW.CDFILIAL;
   ELSE
      IF UPDATING THEN
         V_OPERACAO     := 'U'; --update
         V_CDPRATOANT   := :OLD.CDPRATO;
         V_CDPRATOATUAL := :NEW.CDPRATO;
         V_CDTIPOPRAT   := :NEW.CDTIPOPRAT;
         V_CDFILIAL     := :NEW.CDFILIAL;
      ELSE
         V_OPERACAO     := 'D'; --delete
         V_CDPRATOANT   := :OLD.CDPRATO;
         V_CDPRATOATUAL := null;
         V_CDTIPOPRAT   := :OLD.CDTIPOPRAT;
         V_CDFILIAL     := :OLD.CDFILIAL;
      END IF;
   END IF;
   
   INSERT INTO HISTLOGCOMPCARD (CDFILIAL, CDSERVFILI, DTMESCARD, DTCARDAPIO, CDTIPOPRAT, 
                                CDPRATOANT, CDPRATOATUAL, CDOPERADOR, IDOPERACAO, DTALTERACAO)
   VALUES (V_CDFILIAL, V_CDSERVFILI, V_DTMESCARD, V_DTCARDAPIO, V_CDTIPOPRAT, 
           V_CDPRATOANT, V_CDPRATOATUAL, V_DSREMOTEOPER, V_OPERACAO, SYSDATE);

END;