SET TERM ^ ;

ALTER TABLE TBMODELO_COR ADD ECOMMERCE SMALLINT DEFAULT 0^

CREATE OR ALTER TRIGGER TTBMODELO_COR_B9U FOR TBMODELO_COR
ACTIVE BEFORE UPDATE POSITION 9
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

   HISTORICO = '';

   /*IF (OLD.PERCENTUAL_TALAO <> NEW.PERCENTUAL_TALAO) THEN
       BEGIN
       HISTORICO = HISTORICO||'COR: '||OLD.COR_ID||'-'||COALESCE((SELECT FIRST 1 C.DESCRICAO FROM TBCOR C WHERE C.CODIGO = OLD.COR_ID),'')||' -> %TALÃO '||OLD.PERCENTUAL_TALAO||'->'||NEW.PERCENTUAL_TALAO;
       END*/
   IF (COALESCE(OLD.ECOMMERCE,0) <> COALESCE(NEW.ECOMMERCE,0)) THEN
      BEGIN
         IF(COALESCE(NEW.ECOMMERCE,0) = 1)THEN
         BEGIN
            HISTORICO = HISTORICO||'COR: '||FN_LPAD(OLD.COR_ID,4,0)||'-'||COALESCE((SELECT FIRST 1 C.DESCRICAO FROM TBCOR C WHERE C.CODIGO = OLD.COR_ID),'')||' INCLUIDA AO ECOMMERCE';
         END
         IF(COALESCE(NEW.ECOMMERCE,0) = 0)THEN
         BEGIN
            HISTORICO = HISTORICO||'COR: '||FN_LPAD(OLD.COR_ID,4,0)||'-'||COALESCE((SELECT FIRST 1 C.DESCRICAO FROM TBCOR C WHERE C.CODIGO = OLD.COR_ID),'')||' EXCLUIDA DO ECOMMERCE';
         END
      END

   IF (HISTORICO <> '') THEN
       BEGIN
       INSERT INTO TBHISTORICO (
       TABELA, TABELA_ID, USUARIO, IP, HISTORICO) VALUES (
      'TBMODELO', OLD.MODELO_ID,
      (SELECT FIRST 1 MON$USER FROM MON$ATTACHMENTS WHERE MON$ATTACHMENT_ID = CURRENT_CONNECTION),
      (SELECT FIRST 1 MON$REMOTE_ADDRESS FROM MON$ATTACHMENTS WHERE MON$ATTACHMENT_ID = CURRENT_CONNECTION),
       :HISTORICO);
       END
END^

SET TERM ; ^