CREATE OR REPLACE TRIGGER CAD_AUTO_ALMOXLOCALPROD
AFTER INSERT ON ITLANCTOEST FOR EACH ROW
DECLARE
   V_CDALMOXARIFE  VARCHAR2(6);
   V_CDLOCALESTOQ  VARCHAR2(6);
   V_CDALMOXPRCLI  VARCHAR2(6);
   V_CDLOCALPRCLI  VARCHAR2(6);
   V_IDUTILALMOX   VARCHAR2(1);
   V_IDUTILLCESTQ  VARCHAR2(1);
BEGIN
   IF (:NEW.IDTIPOMOVI = '2') THEN

      BEGIN
         SELECT CDALMOXARIFE, CDLOCALESTOQ,
                CDALMOXPRCLI, CDLOCALPRCLI
           INTO  V_CDALMOXARIFE, V_CDLOCALESTOQ,
                 V_CDALMOXPRCLI, V_CDLOCALPRCLI
           FROM PRODFILI
          WHERE CDFILIAL = :NEW.CDFILIMOVI AND
                CDPRODUTO = :NEW.CDPRODMOVI;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_CDALMOXARIFE := NULL; V_CDLOCALESTOQ := NULL;
            V_CDALMOXPRCLI := NULL; V_CDLOCALPRCLI := NULL;
         END;


      BEGIN
         SELECT IDUTILALMOX, IDUTILLCESTQ
           INTO V_IDUTILALMOX, V_IDUTILLCESTQ
           FROM PARAMFILIAL
           WHERE CDFILIAL = :NEW.CDFILIMOVI;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_IDUTILALMOX := 'N';
            V_IDUTILLCESTQ := 'N';
         END;

      IF V_IDUTILALMOX = 'S' THEN
         IF (V_CDALMOXARIFE IS NULL)OR(V_CDALMOXARIFE = ' ')OR
            (V_CDALMOXPRCLI IS NULL)OR(V_CDALMOXPRCLI = ' ')THEN

            UPDATE PRODFILI
               SET CDALMOXARIFE = :NEW.CDALMOXARIFE,
                   CDALMOXPRCLI = :NEW.CDALMOXARIFE
             WHERE
                CDFILIAL = :NEW.CDFILIMOVI AND
                CDPRODUTO = :NEW.CDPRODMOVI;
         END IF;
      END IF;

      IF V_IDUTILLCESTQ = 'S' THEN
         IF (V_CDLOCALESTOQ IS NULL)OR( V_CDLOCALESTOQ = ' ') OR
            (V_CDLOCALPRCLI IS NULL)OR( V_CDLOCALPRCLI = ' ') THEN

            UPDATE PRODFILI
               SET CDLOCALESTOQ = :NEW.CDLOCALESTOQ,
                   CDLOCALPRCLI = :NEW.CDLOCALESTOQ
             WHERE
                CDFILIAL = :NEW.CDFILIMOVI AND
                CDPRODUTO = :NEW.CDPRODMOVI;
         END IF;
      ELSE
         UPDATE PRODFILI
            SET CDLOCALESTOQ = ' ',
                CDLOCALPRCLI = ' '
          WHERE
             CDFILIAL = :NEW.CDFILIMOVI AND
             CDPRODUTO = :NEW.CDPRODMOVI;
      END IF;
   END IF;
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('CAD_AUTO_ALMOXLOCALPROD','5.45.xxx'); END;
/
