-- 16080 - Cadastro de Máquinas/Equipamentos (Triggers) -------------------------------------------------------------------------
-- TBPATRIMONIO

DROP TRIGGER TBPATRIMONIO_B0I;

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_b01i for tbpatrimonio
active before insert position 0
AS
BEGIN
  IF (NEW.ID IS NULL) THEN
    NEW.ID = GEN_ID(GTBPATRIMONIO,1);
END
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_b02i for tbpatrimonio
active before insert position 1
As
/*
**********************************
*                                *
*     VerIfica se a etiqueta     *
*      de serviço já existe      *
*                                *
**********************************
*/
Declare Variable vEtiqPat Varchar(20);
Declare Variable vEtiqComp Varchar(20);
Begin
    If (New.Etiqueta > '') Then
    Begin
        For
            Select
            (Select First 1 P.Id From Tbpatrimonio             p Where p.Etiqueta = New.Etiqueta) EtiquetaPatrimonio,
            (Select First 1 C.Id From Tbpatrimonio_Componentes c Where c.Etiqueta = New.Etiqueta) EtiquetaComponente
            From Rdb$Database
        Into :vEtiqPat, :vEtiqComp
        Do
        Begin
            If ((vEtiqPat > 0) Or (vEtiqComp > 0))  Then
            Begin
                 Exception "..." '[ETIQUETA DE SERVIÇO] INVÁLIDA. ESTA ETIQUETA JÁ ESTÁ SENDO UTILIZADA.'||
                ' . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ';  
            End
        End
    End
End
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_b1i for tbpatrimonio
inactive before insert position 2
AS
--*****************************
--*                           *
--*       Registra log        *
--*       de  gravação        *
--*                           *
--*****************************

DECLARE VARIABLE HISTORICO VARCHAR(500);
begin

   HISTORICO = 'Reg. incluído.';

   if (HISTORICO <> '') Then
   Begin
       INSERT INTO TBHISTORICO
              (
              TABELA,
              TABELA_ID,
              USUARIO, IP,
              HISTORICO
              )
       VALUES(
              'TBPATRIMONIO',
              NEW.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 ; ^

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_b03i for tbpatrimonio
active before insert position 2
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    IF(NEW.ID > 0) THEN
    BEGIN
        HISTORICO = HISTORICO||'REGISTRO INCLUIDO';
    END
    
    IF(HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBPATRIMONIO', NEW.ID, HISTORICO);
    END
END
^

SET TERM ; ^

DROP TRIGGER TTBPATRIMONIO_B1U;

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_b01u for tbpatrimonio
active before update position 0
As
/*
********************************************
*                                          *
* 1 - VerIfica se há configurações já      *
*     registradas para o "TIPO" atual.     *
*                                          *
********************************************
*/
Declare Variable vTipo Integer;
Begin
    If (Old.Tipo_Id > New.Tipo_Id) Then
    Begin
        For
            Select
                First 1
                c.id
            From
                Tbpatrimonio_Configuracao c
            Where
                c.patrimonio_id = Old.Id
        Into :vTipo
        Do
        Begin
            If (vTipo > 0) Then
            Begin
                 Exception "..." 'ALTERAÇÃO DE [TIPO] NÃO PERMITIDA. JÁ EXISTEM CONFIGURAÇÕES REGISTRADAS.'||
                ' . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ';  
            End
        End
    End
End
^

SET TERM ; ^

DROP TRIGGER TTBPATRIMONIO_B2U;

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_b02u for tbpatrimonio
active before update position 1
AS
/*
**********************************
*                                *
*     VerIfica se a etiqueta     *
*      de serviço já existe      *
*                                *
**********************************
*/
Declare Variable vEtiqPat Varchar(20);
Declare Variable vEtiqComp Varchar(20);
Begin
    If (New.Etiqueta <> Old.Etiqueta) Then
    Begin
        For
            Select
            (Select First 1 p.Id From Tbpatrimonio             p Where p.Etiqueta = New.Etiqueta) EtiquetaPatrimonio,
            (Select First 1 c.Id From Tbpatrimonio_Componentes c Where c.Etiqueta = New.Etiqueta) EtiquetaComponente
            From Rdb$Database
        Into :vEtiqPat, :vEtiqComp
        Do
        Begin
            If ((vEtiqPat > 0) Or (vEtiqComp > 0))  Then
            Begin
                 Exception "..." '[ETIQUETA DE SERVIÇO] INVÁLIDA. ESTA ETIQUETA JÁ ESTÁ SENDO UTILIZADA.'||
                ' . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ';  
            End
        End
    End
End
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_b0u for tbpatrimonio
inactive before update position 2
AS
--*****************************
--*                           *
--*       Registra log        *
--*       de alteração        *
--*                           *
--*****************************

DECLARE VARIABLE HISTORICO VARCHAR(500);
begin

      HISTORICO = '';

   if (old.produto_id <> new.produto_id) then
       begin
       historico = historico||' Prod.: '||OLD.produto_id||'->'||NEW.produto_id;
       end
   if (old.patrimonio <> new.patrimonio) then
       begin
       historico = historico||' Pat.: '||OLD.patrimonio||'->'||NEW.patrimonio;
       end
   if (old.descricao <> new.descricao) then
       begin
       historico = historico||' Desc.: '||OLD.descricao||'->'||NEW.descricao;
       end
   if (old.referencia <> new.referencia) then
       begin
       historico = historico||' Mod.: '||OLD.referencia||'->'||NEW.referencia;
       end
   if (old.serie <> new.serie) then
       begin
       historico = historico||' Série: '||OLD.serie||'->'||NEW.serie;
       end
   if (old.marca <> new.marca) then
       begin
       historico = historico||' Fab.: '||OLD.marca||'->'||NEW.marca;
       end
   if (old.observacoes <> new.observacoes) then
       begin
       historico = historico||' Obs.: [MODIFIC.]';
       end
   if (old.vida_util <> new.vida_util) then
       begin
       historico = historico||' V.Util: '||OLD.vida_util||'->'||NEW.vida_util;
       end
   if (old.area <> new.area) then
       begin
       historico = historico||' Área: '||OLD.area||'->'||NEW.area;
       end
   if (old.tipo <> new.tipo) then
       begin
       historico = historico||' Tipo: '||OLD.tipo||'->'||NEW.tipo;
       end
   if (old.conta_contabil <> new.conta_contabil) then
       begin
       historico = historico||' C.Cont.: '||OLD.conta_contabil||'->'||NEW.conta_contabil;
       end
   if (old.lre <> new.lre) then
       begin
       historico = historico||' LRE: '||OLD.lre||'->'||NEW.lre;
       end
   if (old.folha_lre <> new.folha_lre) then
       begin
       historico = historico||' F.LRE: '||OLD.folha_lre||'->'||NEW.folha_lre;
       end
   if (old.status <> new.status) then
       begin
       historico = historico||' Stts.: '||OLD.status||'->'||NEW.status;
       end
   if (old.centro_de_custo <> new.centro_de_custo) then
       begin
       historico = historico||' C.Custo: '||OLD.centro_de_custo||'->'||NEW.centro_de_custo;
       end
   if (old.ordem <> new.ordem) then
       begin
       historico = historico||' Ord.: '||OLD.ordem||'->'||NEW.ordem;
       end
   if (old.data_conclusao <> new.data_conclusao) then
       begin
       historico = historico||' Dt.Conc.: '||OLD.data_conclusao||'->'||NEW.data_conclusao;
       end
   if (old.estabelecimento_id <> new.estabelecimento_id) then
       begin
       historico = historico||' Estab.: '||OLD.estabelecimento_id||'->'||NEW.estabelecimento_id;
       end
   if (old.modelo_id <> new.modelo_id) then
       begin
       historico = historico||' Mod.: '||OLD.modelo_id||'->'||NEW.modelo_id;
       end
   if (old.tipo_id <> new.tipo_id) then
       begin
       historico = historico||' Tipo.: '||OLD.tipo_id||'->'||NEW.tipo_id;
       end
   if (old.subtipo_id <> new.subtipo_id) then
       begin
       historico = historico||' Subtipo.: '||OLD.subtipo_id||'->'||NEW.subtipo_id;
       end
   if (old.fabricante_id <> new.fabricante_id) then
       begin
       historico = historico||' Fab.: '||OLD.fabricante_id||'->'||NEW.fabricante_id;
       end
   if (old.etiqueta <> new.etiqueta) then
       begin
       historico = historico||' Etiq.: '||OLD.etiqueta||'->'||NEW.etiqueta;
       end
   if (old.service_tag <> new.service_tag) then
       begin
       historico = historico||' Ser.Tag: '||OLD.service_tag||'->'||NEW.service_tag;
       end

   if (HISTORICO <> '') Then
   Begin
       INSERT INTO TBHISTORICO
              (
              TABELA,
              TABELA_ID,
              USUARIO, IP,
              HISTORICO
              )
       VALUES(
              'TBPATRIMONIO',
              NEW.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 ; ^

SET TERM ^ ;

CREATE trigger ttbpatrimonio_b03u for tbpatrimonio
active before update position 2
AS
DECLARE VARIABLE HISTORICO VARCHAR(3000);
BEGIN

    HISTORICO = '';

    IF (OLD.PRODUTO_ID <> NEW.PRODUTO_ID) THEN
    BEGIN
        HISTORICO = HISTORICO||' PRODUTO:'||OLD.PRODUTO_ID||'->'||NEW.PRODUTO_ID;
    END
    
    IF (OLD.PATRIMONIO <> NEW.PATRIMONIO) THEN
    BEGIN
        HISTORICO = HISTORICO||' PATRIMONIO:'||OLD.PATRIMONIO||'->'||NEW.PATRIMONIO;
    END
    
    IF (OLD.DESCRICAO <> NEW.DESCRICAO) THEN
    BEGIN
        HISTORICO = HISTORICO||' DESC:'||OLD.DESCRICAO||'->'||NEW.DESCRICAO;
    END
    
    IF (OLD.REFERENCIA <> NEW.REFERENCIA) THEN
    BEGIN
        HISTORICO = HISTORICO||' MODELO:'||OLD.REFERENCIA||'->'||NEW.REFERENCIA;
    END
    
    IF (OLD.SERIE <> NEW.SERIE) THEN
    BEGIN
        HISTORICO = HISTORICO||' SERIE:'||OLD.SERIE||'->'||NEW.SERIE;
    END
    
    IF (OLD.MARCA <> NEW.MARCA) THEN
    BEGIN
        HISTORICO = HISTORICO||' FABRIC:'||OLD.MARCA||'->'||NEW.MARCA;
    END
    
    IF (OLD.OBSERVACOES <> NEW.OBSERVACOES) THEN
    BEGIN
        HISTORICO = HISTORICO||' OBSRVACOES ALTERADA';
    END
    
    IF (OLD.VIDA_UTIL <> NEW.VIDA_UTIL) THEN
    BEGIN
        HISTORICO = HISTORICO||' V.UTIL:'||OLD.VIDA_UTIL||'->'||NEW.VIDA_UTIL;
    END
    
    IF (OLD.AREA <> NEW.AREA) THEN
    BEGIN
        HISTORICO = HISTORICO||' AREA:'||OLD.AREA||'->'||NEW.AREA;
    END
    
    IF (OLD.TIPO <> NEW.TIPO) THEN
    BEGIN
        HISTORICO = HISTORICO||' TIPO:'||OLD.TIPO||'->'||NEW.TIPO;
    END
    
    IF (OLD.CONTA_CONTABIL <> NEW.CONTA_CONTABIL) THEN
    BEGIN
        HISTORICO = HISTORICO||' C.CONT:'||OLD.CONTA_CONTABIL||'->'||NEW.CONTA_CONTABIL;
    END
    
    IF (OLD.LRE <> NEW.LRE) THEN
    BEGIN
        HISTORICO = HISTORICO||' LRE:'||OLD.LRE||'->'||NEW.LRE;
    END
    
    IF (OLD.FOLHA_LRE <> NEW.FOLHA_LRE) THEN
    BEGIN
        HISTORICO = HISTORICO||' F.LRE:'||OLD.FOLHA_LRE||'->'||NEW.FOLHA_LRE;
    END
    
    IF (OLD.STATUS <> NEW.STATUS) THEN
    BEGIN
        HISTORICO = HISTORICO||' STATUS.:'||OLD.STATUS||'->'||NEW.STATUS;
    END
    
    IF (OLD.CENTRO_DE_CUSTO <> NEW.CENTRO_DE_CUSTO) THEN
    BEGIN
        HISTORICO = HISTORICO||' C.CUSTO:'||OLD.CENTRO_DE_CUSTO||'->'||NEW.CENTRO_DE_CUSTO;
    END
    
    IF (OLD.ORDEM <> NEW.ORDEM) THEN
    BEGIN
        HISTORICO = HISTORICO||' ORDEM:'||OLD.ORDEM||'->'||NEW.ORDEM;
    END
    
    IF (OLD.DATA_CONCLUSAO <> NEW.DATA_CONCLUSAO) THEN
    BEGIN
        HISTORICO = HISTORICO||' DATA CONC:'||OLD.DATA_CONCLUSAO||'->'||NEW.DATA_CONCLUSAO;
    END
    
    IF (OLD.ESTABELECIMENTO_ID <> NEW.ESTABELECIMENTO_ID) THEN
    BEGIN
        HISTORICO = HISTORICO||' ESTAB:'||OLD.ESTABELECIMENTO_ID||'->'||NEW.ESTABELECIMENTO_ID;
    END
    
    IF (OLD.MODELO_ID <> NEW.MODELO_ID) THEN
    BEGIN
        HISTORICO = HISTORICO||' MODELO:'||OLD.MODELO_ID||'->'||NEW.MODELO_ID;
    END
    
    IF (OLD.TIPO_ID <> NEW.TIPO_ID) THEN
    BEGIN
        HISTORICO = HISTORICO||' TIPO:'||OLD.TIPO_ID||'->'||NEW.TIPO_ID;
    END
    
    IF (OLD.SUBTIPO_ID <> NEW.SUBTIPO_ID) THEN
    BEGIN
        HISTORICO = HISTORICO||' SUBTIPO:'||OLD.SUBTIPO_ID||'->'||NEW.SUBTIPO_ID;
    END
    
    IF (OLD.FABRICANTE_ID <> NEW.FABRICANTE_ID) THEN
    BEGIN
        HISTORICO = HISTORICO||' FABRIC:'||OLD.FABRICANTE_ID||'->'||NEW.FABRICANTE_ID;
    END
    
    IF (OLD.ETIQUETA <> NEW.ETIQUETA) THEN
    BEGIN
        HISTORICO = HISTORICO||' ETIQUETA:'||OLD.ETIQUETA||'->'||NEW.ETIQUETA;
    END
       
    IF (OLD.SERVICE_TAG <> NEW.SERVICE_TAG) THEN
    BEGIN
        HISTORICO = HISTORICO||' SERVICE TAG:'||OLD.SERVICE_TAG||'->'||NEW.SERVICE_TAG;
    END
    
    IF (HISTORICO <> '') THEN
    BEGIN
        HISTORICO = 'REGISTRO ALTERADO:'||HISTORICO;
        EXECUTE PROCEDURE SPI_HISTORICO('TBPATRIMONIO', OLD.ID, FN_ELIPSES(HISTORICO, 500));
    END
END
^

SET TERM ; ^

DROP TRIGGER TTBPATRIMONIO_B1D;

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_b01d for tbpatrimonio
active before delete position 0
As
/*
*************************************
*                                   *
* 1 - VerIfica se há vínculos com   *
*     patrimonio ou componentes     *
*                                   *
*************************************
*/
Declare Variable Vinculo1 Integer;
Declare Variable Vinculo2 Integer;
Declare Variable Vinculo3 Integer;
Begin
    For
        select
        (select first 1 c.id  from tbpatrimonio_configuracao c  where c.patrimonio_id  = OLD.id),
        (select first 1 cp.id from tbpatrimonio_componentes  cp where cp.patrimonio_id = OLD.id),
        (select first 1 cc.id from tbpatrimonio_ccusto       cc where cc.patrimonio_id = OLD.id)
        from
        RDB$DATABASE
    Into :Vinculo1, :Vinculo2, :Vinculo3
    Do
    Begin
        If ((Vinculo1 > 0) or (vinculo2 > 0) or (vinculo3 > 0))  Then
        Begin
             Exception "..." 'EXCLUSÃO NÃO PERMITIDA. JÁ EXISTEM REGISTROS VINCULADOS A ESTE ITEM'||
            ' . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ';  
        End
    End
End
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_b0d for tbpatrimonio
inactive before delete position 0
AS
--*****************************
--*                           *
--*       Registra log        *
--*       de  exclusão        *
--*                           *
--*****************************

DECLARE VARIABLE HISTORICO VARCHAR(500);
begin

   HISTORICO = 'Reg. excluído.';

   if (HISTORICO <> '') Then
   Begin
       INSERT INTO TBHISTORICO
              (
              TABELA,
              TABELA_ID,
              USUARIO, IP,
              HISTORICO
              )
       VALUES(
              'TBPATRIMONIO',
              OLD.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 ; ^

SET TERM ^ ;

CREATE trigger ttbpatrimonio_b02d for tbpatrimonio
active before delete position 1
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    IF(OLD.ID > 0) THEN
    BEGIN
        HISTORICO = HISTORICO||'REGISTRO EXCLUIDO';
    END
    
    IF(HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBPATRIMONIO', OLD.ID, HISTORICO);
    END
END
^

SET TERM ; ^

---------------------------------------------------------------------------------------------------------------------------------
-- TBPATRIMONIO_CCUSTO

DROP TRIGGER TBPATRIMONIO_CCUSTO_BI;

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_ccusto_b01i for tbpatrimonio_ccusto
active before insert position 0
AS
BEGIN
  IF (NEW.ID IS NULL) THEN
    NEW.ID = GEN_ID(GTBPATRIMONIO_CCUSTO,1);
END
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER trigger tbpatrimonio_ccusto_b1i for tbpatrimonio_ccusto
inactive before insert position 1
AS
--*****************************
--*                           *
--*       Registra log        *
--*       de  gravação        *
--*                           *
--*****************************

DECLARE VARIABLE HISTORICO VARCHAR(500);
begin

   HISTORICO = 'Alocado para C. Custo ' || new.ccusto;

   if (HISTORICO <> '') Then
   Begin
       INSERT INTO TBHISTORICO
              (
              TABELA,
              TABELA_ID,
              USUARIO, IP,
              HISTORICO
              )
       VALUES(
              'TBPATRIMONIO',
              NEW.PATRIMONIO_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 ; ^

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_ccusto_b02i for tbpatrimonio_ccusto
active before insert position 1
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    IF(NEW.ID > 0) THEN
    BEGIN
        HISTORICO = HISTORICO||'ALOCACAO '||FN_LPAD(NEW.ID, 5, '0')||' INCLUIDA';
    END
    
    IF(HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBPATRIMONIO', NEW.PATRIMONIO_ID, HISTORICO);
    END
END
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_ccusto_b0u for tbpatrimonio_ccusto
inactive before update position 0
AS
--*****************************
--*                           *
--*       Registra log        *
--*       de alteração        *
--*                           *
--*****************************

DECLARE VARIABLE HISTORICO VARCHAR(500);
begin

      HISTORICO = '';

   if (old.ccusto <> new.ccusto) then
       begin
       historico = historico||' C.Custo: '||OLD.ccusto||'->'||NEW.ccusto;
       end
   if (old.data_inicio <> new.data_inicio) then
       begin
       historico = historico||' Data Inicial: '||OLD.data_inicio||'->'||NEW.data_inicio;
       end
   if (old.data_final <> new.data_final) then
       begin
       historico = historico||' Data Final: '||OLD.data_final||'->'||NEW.data_final;
       end


   if (HISTORICO <> '') Then
   Begin
       historico = 'Alocação alterada: ' || new.id || ' = ' || historico;
       INSERT INTO TBHISTORICO
              (
              TABELA,
              TABELA_ID,
              USUARIO, IP,
              HISTORICO
              )
       VALUES(
              'TBPATRIMONIO',
              new.patrimonio_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 ; ^

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_ccusto_b01u for tbpatrimonio_ccusto
active before update position 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(2000);
BEGIN

    HISTORICO = '';
    
    IF (OLD.CCUSTO <> NEW.CCUSTO) THEN
    BEGIN
        HISTORICO = HISTORICO||' C.CUSTO:'||OLD.CCUSTO||'->'||NEW.CCUSTO;
    END

    IF (OLD.DATA_INICIO <> NEW.DATA_INICIO) THEN
    BEGIN
        HISTORICO = HISTORICO||' DATA INICIAL:'||OLD.DATA_INICIO||'->'||NEW.DATA_INICIO;
    END

    IF (OLD.DATA_FINAL <> NEW.DATA_FINAL) THEN
    BEGIN
        HISTORICO = HISTORICO||' DATA FINAL:'||OLD.DATA_FINAL||'->'||NEW.DATA_FINAL;
    END

    IF (OLD.OBSERVACAO <> NEW.OBSERVACAO) THEN
    BEGIN
        HISTORICO = HISTORICO||' OBSERVACAO ALTERADA';
    END

    IF (HISTORICO <> '') THEN
    BEGIN
        HISTORICO = 'ALOCACAO '||FN_LPAD(OLD.ID, 5, '0')||' ALTERADA:'||HISTORICO;
        EXECUTE PROCEDURE SPI_HISTORICO('TBPATRIMONIO', OLD.PATRIMONIO_ID, FN_ELIPSES(HISTORICO, 500));
    END
END
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER trigger tbpatrimonio_ccusto_b0d for tbpatrimonio_ccusto
inactive before delete position 0
AS
--*****************************
--*                           *
--*       Registra log        *
--*       de  gravação        *
--*                           *
--*****************************

DECLARE VARIABLE HISTORICO VARCHAR(500);
begin

   HISTORICO = 'Alocação C. Custo ' || old.ccusto || ' excluída';

   if (HISTORICO <> '') Then
   Begin
       INSERT INTO TBHISTORICO
              (
              TABELA,
              TABELA_ID,
              USUARIO, IP,
              HISTORICO
              )
       VALUES(
              'TBPATRIMONIO',
              old.PATRIMONIO_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 ; ^

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_ccusto_b01d for tbpatrimonio_ccusto
active before delete position 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    IF(OLD.ID > 0) THEN
    BEGIN
        HISTORICO = HISTORICO||'ALOCACAO '||FN_LPAD(OLD.ID, 5, '0')||' EXCLUIDA';
    END
    
    IF(HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBPATRIMONIO', OLD.PATRIMONIO_ID, HISTORICO);
    END
END
^

SET TERM ; ^

---------------------------------------------------------------------------------------------------------------------------------
-- TBPATRIMONIO_COMPONENTES

ALTER SEQUENCE GTBPATRIMONIO_COMPONENTES RESTART WITH 4270 INCREMENT BY 1;

DROP TRIGGER TBPATRIMONIO_COMPONENTES_BI;

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_componentes_b01i for tbpatrimonio_componentes
active before insert position 0
AS
DECLARE VARIABLE ORDEM INTEGER;
BEGIN

    ORDEM = COALESCE((SELECT A.ORDEM FROM TBPATRIMONIO_COMPONENTES A WHERE A.ORDEM = NEW.ORDEM), 0);

    IF (ORDEM > 0) THEN
    BEGIN
        EXCEPTION "..." 'A ORDEM NÃO PODE SER DUPLICADA, CONTATE O ADMINISTRADOR DO SISTEMA!';
    END

    IF (NEW.ORDEM IS NULL) THEN
        NEW.ORDEM = GEN_ID(GTBPATRIMONIO_COMPONENTES,1);
END
^

SET TERM ; ^

DROP TRIGGER TTBPATRIMONIO_COMPONENTES_B2I;

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_componentes_b02i for tbpatrimonio_componentes
active before insert position 1
As
/*
**********************************
*                                *
*     VerIfica se a etiqueta     *
*      de serviço já existe      *
*                                *
**********************************
*/
Declare Variable vEtiqPat Varchar(20);
Declare Variable vEtiqComp Varchar(20);
Begin
    If (New.Etiqueta <> '') Then
    Begin
        For
            Select
            (Select First 1 p.Id From Tbpatrimonio             p Where p.Etiqueta = New.Etiqueta)EtiquetaPatrimonio,
            (Select First 1 c.Id From Tbpatrimonio_Componentes c Where c.Etiqueta = New.Etiqueta)EtiquetaComponente
            From Rdb$Database
        Into :vEtiqPat, :vEtiqComp
        Do
        Begin
            If ((vEtiqPat > 0) Or (vEtiqComp > 0))  Then
            Begin
                 Exception "..." '[ETIQUETA DE SERVIÇO] INVÁLIDA. ESTA ETIQUETA JÁ ESTÁ SENDO UTILIZADA.'||
                ' . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ';  
            End
        End
    End
End
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_componentes_b1i for tbpatrimonio_componentes
inactive before insert position 2
AS
--*****************************
--*                           *
--*       Registra log        *
--*       de  gravação        *
--*                           *
--*****************************

DECLARE VARIABLE HISTORICO VARCHAR(500);
begin

   HISTORICO = 'Reg. incluído.';

   if (HISTORICO <> '') Then
   Begin
       INSERT INTO TBHISTORICO
              (
              TABELA,
              TABELA_ID,
              USUARIO, IP,
              HISTORICO
              )
       VALUES(
              'TBPATRIMONIO_COMPONENTES',
              NEW.ORDEM,
              (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 ; ^

SET TERM ^ ;

CREATE trigger ttbpatrimonio_componentes_b03i for tbpatrimonio_componentes
active before insert position 2
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    IF(NEW.ID > 0) THEN
    BEGIN
        HISTORICO = HISTORICO||'COMPONENTE '||FN_LPAD(NEW.ID, 5, '0')||' INCLUIDO';
    END
    
    IF(HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBPATRIMONIO', NEW.PATRIMONIO_ID, HISTORICO);
    END
END
^

SET TERM ; ^

DROP TRIGGER TTBPATRIMONIO_COMPONENTES_B1U;

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_componentes_b01u for tbpatrimonio_componentes
active before update position 0
As
/*
********************************************
*                                          *
* 1 - VerIfica se há configurações já      *
*     registradas para o "TIPO" atual.     *
*                                          *
********************************************
*/
Declare Variable vTipo Integer;
Begin
    If (Old.Tipo_Id > New.Tipo_Id) Then
    Begin
        For
            Select
                First 1
                c.id
            From
                Tbpatrimonio_Configuracao c
            Where
                c.componente_id = Old.Id
        Into :vTipo
        Do
        Begin
            If (vTipo > 0) Then
            Begin
                 Exception "..." 'ALTERAÇÃO DE [TIPO] NÃO PERMITIDA. JÁ EXISTEM CONFIGURAÇÕES REGISTRADAS.'||
                ' . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ';  
            End
        End
    End
End
^

SET TERM ; ^

DROP TRIGGER TTBPATRIMONIO_COMPONENTES_B2U;

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_componentes_b02u for tbpatrimonio_componentes
active before update position 1
AS
/*
**********************************
*                                *
*     VerIfica se a etiqueta     *
*      de serviço já existe      *
*                                *
**********************************
*/
Declare Variable vEtiqPat Varchar(20);
Declare Variable vEtiqComp Varchar(20);
Begin
    If (New.Etiqueta <> Old.Etiqueta) Then
    Begin
        For
            Select
            (Select First 1 p.Id From Tbpatrimonio             p Where p.Etiqueta = New.Etiqueta)EtiquetaPatrimonio,
            (Select First 1 c.Id From Tbpatrimonio_Componentes c Where c.Etiqueta = New.Etiqueta)EtiquetaComponente
            From Rdb$Database
        Into :vEtiqPat, :vEtiqComp
        Do
        Begin
            If ((vEtiqPat > 0) Or (vEtiqComp > 0))  Then
            Begin
                 Exception "..." '[ETIQUETA DE SERVIÇO] INVÁLIDA. ESTA ETIQUETA JÁ ESTÁ SENDO UTILIZADA.'||
                ' . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ';  
            End
        End
    End
End
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_componentes_b0u for tbpatrimonio_componentes
inactive before update position 2
AS
--*****************************
--*                           *
--*       Registra log        *
--*       de alteração        *
--*                           *
--*****************************

DECLARE VARIABLE HISTORICO VARCHAR(500);
begin

      HISTORICO = '';

   if (old.patrimonio_id <> new.patrimonio_id) then
       begin
       historico = historico||' Imobiliz.: '||OLD.patrimonio_id||'->'||NEW.patrimonio_id;
       end
   if (old.produto_id <> new.produto_id) then
       begin
       historico = historico||' Prod.: '||OLD.produto_id||'->'||NEW.produto_id;
       end
   if (old.descricao <> new.descricao) then
       begin
       historico = historico||' Desc.: '||OLD.descricao||'->'||NEW.descricao;
       end
   if (old.etiqueta <> new.etiqueta) then
       begin
       historico = historico||' Etiq.: '||OLD.etiqueta||'->'||NEW.etiqueta;
       end
   if (old.lre <> new.lre) then
       begin
       historico = historico||' LRE: '||OLD.lre||'->'||NEW.lre;
       end
   if (old.folha_lre <> new.folha_lre) then
       begin
       historico = historico||' F.LRE: '||OLD.folha_lre||'->'||NEW.folha_lre;
       end
   if (old.referencia <> new.referencia) then
       begin
       historico = historico||' Mod.: '||OLD.referencia||'->'||NEW.referencia;
       end
   if (old.serie <> new.serie) then
       begin
       historico = historico||' Série: '||OLD.serie||'->'||NEW.serie;
       end
   if (old.marca <> new.marca) then
       begin
       historico = historico||' Fab.: '||OLD.marca||'->'||NEW.marca;
       end
   if (old.relevancia <> new.relevancia) then
       begin
       historico = historico||' Relev.: '||OLD.relevancia||'->'||NEW.relevancia;
       end
   if (old.dias_manutencao <> new.dias_manutencao) then
       begin
       historico = historico||' Dias Man..: '||OLD.dias_manutencao||'->'||NEW.dias_manutencao;
       end
   if (old.status <> new.status) then
       begin
       historico = historico||' Satuts: '||OLD.status||'->'||NEW.status;
       end
   if (old.modelo_id <> new.modelo_id) then
       begin
       historico = historico||' Mod.: '||OLD.modelo_id||'->'||NEW.modelo_id;
       end
   if (old.tipo_id <> new.tipo_id) then
       begin
       historico = historico||' Tipo.: '||OLD.tipo_id||'->'||NEW.tipo_id;
       end
   if (old.subtipo_id <> new.subtipo_id) then
       begin
       historico = historico||' Subtipo: '||OLD.subtipo_id||'->'||NEW.subtipo_id;
       end
   if (old.fabricante_id <> new.fabricante_id) then
       begin
       historico = historico||' Fab.: '||OLD.fabricante_id||'->'||NEW.fabricante_id;
       end
   if (old.service_tag <> new.service_tag) then
       begin
       historico = historico||' Ser.Tag.: '||OLD.service_tag||'->'||NEW.service_tag;
       end
   if (old.observacoes <> new.observacoes) then
       begin
       historico = historico||' Obs.: [MODIFIC.]';
       end
   if (old.data <> new.data) then
       begin
       historico = historico||' data.:'||formatdate(old.data)||'->'||formatdate(new.data);
       end

   if (HISTORICO <> '') Then
   Begin
       INSERT INTO TBHISTORICO
              (
              TABELA,
              TABELA_ID,
              USUARIO, IP,
              HISTORICO
              )
       VALUES(
              'TBPATRIMONIO_COMPONENTES',
              NEW.ORDEM,
              (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 ; ^

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_componentes_b03u for tbpatrimonio_componentes
active before update position 2
AS
DECLARE VARIABLE HISTORICO VARCHAR(3000);
BEGIN

    HISTORICO = '';
	
	IF (OLD.PATRIMONIO_ID <> NEW.PATRIMONIO_ID) THEN
	BEGIN
		HISTORICO = HISTORICO||' IMOBILIZ: '||OLD.PATRIMONIO_ID||'->'||NEW.PATRIMONIO_ID;
	END

    IF (OLD.PRODUTO_ID <> NEW.PRODUTO_ID) THEN
    BEGIN
        HISTORICO = HISTORICO||' PRODUTO:'||OLD.PRODUTO_ID||'->'||NEW.PRODUTO_ID;
    END

    IF (OLD.DESCRICAO <> NEW.DESCRICAO) THEN
    BEGIN
        HISTORICO = HISTORICO||' DESC:'||OLD.DESCRICAO||'->'||NEW.DESCRICAO;
    END

    IF (OLD.ETIQUETA <> NEW.ETIQUETA) THEN
    BEGIN
        HISTORICO = HISTORICO||' ETIQUETA:'||OLD.ETIQUETA||'->'||NEW.ETIQUETA;
    END

    IF (OLD.LRE <> NEW.LRE) THEN
    BEGIN
        HISTORICO = HISTORICO||' LRE:'||OLD.LRE||'->'||NEW.LRE;
    END
    
    IF (OLD.FOLHA_LRE <> NEW.FOLHA_LRE) THEN
    BEGIN
        HISTORICO = HISTORICO||' F.LRE:'||OLD.FOLHA_LRE||'->'||NEW.FOLHA_LRE;
    END

    IF (OLD.REFERENCIA <> NEW.REFERENCIA) THEN
    BEGIN
        HISTORICO = HISTORICO||' MODELO:'||OLD.REFERENCIA||'->'||NEW.REFERENCIA;
    END

    IF (OLD.SERIE <> NEW.SERIE) THEN
    BEGIN
        HISTORICO = HISTORICO||' SERIE:'||OLD.SERIE||'->'||NEW.SERIE;
    END

    IF (OLD.MARCA <> NEW.MARCA) THEN
    BEGIN
        HISTORICO = HISTORICO||' FABRIC:'||OLD.MARCA||'->'||NEW.MARCA;
    END

    IF (OLD.RELEVANCIA <> NEW.RELEVANCIA) THEN
    BEGIN
        HISTORICO = HISTORICO||' RELEV:'||OLD.RELEVANCIA||'->'||NEW.RELEVANCIA;
    END

    IF (OLD.DIAS_MANUTENCAO <> NEW.DIAS_MANUTENCAO) THEN
    BEGIN
        HISTORICO = HISTORICO||' DIAS MANUT:'||OLD.DIAS_MANUTENCAO||'->'||NEW.DIAS_MANUTENCAO;
    END

    IF (OLD.STATUS <> NEW.STATUS) THEN
    BEGIN
        HISTORICO = HISTORICO||' SATUTS:'||OLD.STATUS||'->'||NEW.STATUS;
    END

    IF (OLD.MODELO_ID <> NEW.MODELO_ID) THEN
    BEGIN
        HISTORICO = HISTORICO||' MODELO:'||OLD.MODELO_ID||'->'||NEW.MODELO_ID;
    END
    
    IF (OLD.TIPO_ID <> NEW.TIPO_ID) THEN
    BEGIN
        HISTORICO = HISTORICO||' TIPO:'||OLD.TIPO_ID||'->'||NEW.TIPO_ID;
    END
    
    IF (OLD.SUBTIPO_ID <> NEW.SUBTIPO_ID) THEN
    BEGIN
        HISTORICO = HISTORICO||' SUBTIPO:'||OLD.SUBTIPO_ID||'->'||NEW.SUBTIPO_ID;
    END
    
    IF (OLD.FABRICANTE_ID <> NEW.FABRICANTE_ID) THEN
    BEGIN
        HISTORICO = HISTORICO||' FABRIC:'||OLD.FABRICANTE_ID||'->'||NEW.FABRICANTE_ID;
    END

    IF (OLD.SERVICE_TAG <> NEW.SERVICE_TAG) THEN
    BEGIN
        HISTORICO = HISTORICO||' SERVICE TAG:'||OLD.SERVICE_TAG||'->'||NEW.SERVICE_TAG;
    END

    IF (OLD.OBSERVACOES <> NEW.OBSERVACOES) THEN
    BEGIN
        HISTORICO = HISTORICO||' OBSRVACOES ALTERADA';
    END

    IF (OLD.DATA <> NEW.DATA) THEN
    BEGIN
        HISTORICO = HISTORICO||' DATA:'||FN_DATE_TO_STRING(OLD.DATA)||'->'||FN_DATE_TO_STRING(NEW.DATA);
    END
    
    IF (HISTORICO <> '') THEN
    BEGIN
        HISTORICO = 'COMPONENTE '||FN_LPAD(OLD.ID, 5, '0')||' ALTERADO:'||HISTORICO;
        EXECUTE PROCEDURE SPI_HISTORICO('TBPATRIMONIO', OLD.PATRIMONIO_ID, FN_ELIPSES(HISTORICO, 500));
    END
END
^

SET TERM ; ^

DROP TRIGGER TTBPATRIMONIO_COMPONENTES_B1D;

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_componentes_b01d for tbpatrimonio_componentes
active before delete position 0
As
/*
*************************************
*                                   *
* 1 - VerIfica se há vínculos com   *
*     patrimonio ou componentes     *
*                                   *
*************************************
*/
Declare Variable Vinculo1 Integer;
Begin
    For
        select
        (select first 1 c.id  from tbpatrimonio_configuracao c  where c.componente_id = OLD.id)
        from
        RDB$DATABASE
    Into :Vinculo1
    Do
    Begin
        If (Vinculo1 > 0) Then
        Begin
             Exception "..." 'EXCLUSÃO NÃO PERMITIDA. JÁ EXISTEM REGISTROS VINCULADOS A ESTE ITEM'||
            ' . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ';  
        End
    End
End
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_componentes_b0d for tbpatrimonio_componentes
inactive before delete position 1
AS
--*****************************
--*                           *
--*       Registra log        *
--*       de  exclusão        *
--*                           *
--*****************************

DECLARE VARIABLE HISTORICO VARCHAR(500);
begin

   HISTORICO = 'Reg. excluído.';

   if (HISTORICO <> '') Then
   Begin
       INSERT INTO TBHISTORICO
              (
              TABELA,
              TABELA_ID,
              USUARIO, IP,
              HISTORICO
              )
       VALUES(
              'TBPATRIMONIO_COMPONENTES',
              OLD.ORDEM,
              (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 ; ^

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_componentes_b02d for tbpatrimonio_componentes
active before delete position 1
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    IF(OLD.ID > 0) THEN
    BEGIN
        HISTORICO = HISTORICO||'COMPONENTE '||FN_LPAD(OLD.ID, 5, '0')||' EXCLUIDO';
    END
    
    IF(HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBPATRIMONIO', OLD.PATRIMONIO_ID, HISTORICO);
    END
END
^

SET TERM ; ^

---------------------------------------------------------------------------------------------------------------------------------
-- TBPATRIMONIO_CONFIGURACAO

DROP TRIGGER TBPATRIMONIO_CONFIGURACAO_BI;

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_configuracao_b01i for tbpatrimonio_configuracao
active before insert position 0
AS
BEGIN
  IF (NEW.ID IS NULL) THEN
    NEW.ID = GEN_ID(GTBPATRIMONIO_CONFIGURACAO,1);
END
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_configuracao_b1i for tbpatrimonio_configuracao
inactive before insert position 1
AS
--*****************************
--*                           *
--*       Registra log        *
--*       de  gravação        *
--*                           *
--*****************************

DECLARE VARIABLE HISTORICO VARCHAR(500);
begin
  HISTORICO = 'Config. incluída:' || new.parametro_id || ' = ' || new.descricao;
    if ((new.patrimonio_id > 0) and (new.componente_id is null)) then
    begin
       if (HISTORICO <> '') Then
       Begin
           INSERT INTO TBHISTORICO
                  (
                  TABELA,
                  TABELA_ID,
                  USUARIO, IP,
                  HISTORICO
                  )
           VALUES(
                  'TBPATRIMONIO',
                  new.patrimonio_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
    else
    if ((new.componente_id > 0) and (new.patrimonio_id is null)) then
    begin
       if (HISTORICO <> '') Then
       Begin
           INSERT INTO TBHISTORICO
                  (
                  TABELA,
                  TABELA_ID,
                  USUARIO, IP,
                  HISTORICO
                  )
           VALUES(
                  'TBPATRIMONIO_COMPONENTES',
                  new.componente_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
end
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_configuracao_b02i for tbpatrimonio_configuracao
active before insert position 1
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    IF(NEW.ID > 0 AND NEW.COMPONENTE_ID IS NULL) THEN
    BEGIN
        HISTORICO = HISTORICO||'CONFIGURACAO '||FN_LPAD(NEW.ID, 4, '0')||' INCLUIDA';
    END

    IF(NEW.ID > 0 AND NEW.COMPONENTE_ID > 0) THEN
    BEGIN
        HISTORICO = HISTORICO||'CONFIGURACAO '||FN_LPAD(NEW.ID, 4, '0')||' INCLUIDA NO COMPONENTE '||FN_LPAD(NEW.COMPONENTE_ID, 5, '0');
    END
    
    IF(HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBPATRIMONIO', NEW.PATRIMONIO_ID, HISTORICO);
    END
END
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_configuracao_b0u for tbpatrimonio_configuracao
inactive before update position 0
AS
--*****************************
--*                           *
--*       Registra log        *
--*       de  gravação        *
--*                           *
--*****************************

DECLARE VARIABLE HISTORICO VARCHAR(500);
begin
    HISTORICO = '';

   if (old.descricao <> new.descricao) then
       begin
       historico = historico||' Desc.: '||OLD.descricao||'->'||NEW.descricao;
       end

    if ((new.patrimonio_id > 0) and (new.componente_id is null)) then
    begin
       if (HISTORICO <> '') Then
       Begin
           HISTORICO = 'Config. alterada:' || new.parametro_id || ' = ' || HISTORICO;
           INSERT INTO TBHISTORICO
                  (
                  TABELA,
                  TABELA_ID,
                  USUARIO, IP,
                  HISTORICO
                  )
           VALUES(
                  'TBPATRIMONIO',
                  new.patrimonio_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
    else
    if ((new.componente_id > 0) and (new.patrimonio_id is null)) then
    begin
       if (HISTORICO <> '') Then
       Begin
           HISTORICO = 'Config. alterada:' || new.parametro_id || ' = ' || HISTORICO;
           INSERT INTO TBHISTORICO
                  (
                  TABELA,
                  TABELA_ID,
                  USUARIO, IP,
                  HISTORICO
                  )
           VALUES(
                  'TBPATRIMONIO_COMPONENTES',
                  new.componente_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
end
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_configuracao_b01u for tbpatrimonio_configuracao
active before update position 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(3000);
BEGIN

    HISTORICO = '';
    
    IF (OLD.PARAMETRO_ID <> NEW.PARAMETRO_ID) THEN
    BEGIN
        HISTORICO = HISTORICO||' PARAM:'||OLD.PARAMETRO_ID||'->'||NEW.PARAMETRO_ID;
    END

    IF (OLD.DESCRICAO <> NEW.DESCRICAO) THEN
    BEGIN
        HISTORICO = HISTORICO||' DESC:'||OLD.DESCRICAO||'->'||NEW.DESCRICAO;
    END
    
    IF (HISTORICO <> '') THEN
    BEGIN
        IF (OLD.COMPONENTE_ID IS NULL) THEN
        BEGIN
            HISTORICO = 'CONFIGURACAO '||FN_LPAD(OLD.ID, 4, '0')||' ALTERADA:'||HISTORICO;
        END

        IF (OLD.COMPONENTE_ID > 0) THEN
        BEGIN
            HISTORICO = 'CONFIGURACAO '||FN_LPAD(OLD.ID, 4, '0')||' DO COMPONENTE '||FN_LPAD(OLD.COMPONENTE_ID, 5, '0')||' ALTERADA:'||HISTORICO;
        END

        EXECUTE PROCEDURE SPI_HISTORICO('TBPATRIMONIO', OLD.PATRIMONIO_ID, FN_ELIPSES(HISTORICO, 500));
    END
END
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_configuracao_b0d for tbpatrimonio_configuracao
inactive before delete position 0
AS
--*****************************
--*                           *
--*       Registra log        *
--*       de  gravação        *
--*                           *
--*****************************

DECLARE VARIABLE HISTORICO VARCHAR(500);
begin
  HISTORICO = 'Config. excluida:' || old.parametro_id || ' = ' || old.descricao;
    if ((old.patrimonio_id > 0) and (old.componente_id is null)) then
    begin
       if (HISTORICO <> '') Then
       Begin
           INSERT INTO TBHISTORICO
                  (
                  TABELA,
                  TABELA_ID,
                  USUARIO, IP,
                  HISTORICO
                  )
           VALUES(
                  'TBPATRIMONIO',
                  old.patrimonio_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
    else
    if ((old.componente_id > 0) and (old.patrimonio_id is null)) then
    begin
       if (HISTORICO <> '') Then
       Begin
           INSERT INTO TBHISTORICO
                  (
                  TABELA,
                  TABELA_ID,
                  USUARIO, IP,
                  HISTORICO
                  )
           VALUES(
                  'TBPATRIMONIO_COMPONENTES',
                  old.componente_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
end
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER trigger ttbpatrimonio_configuracao_b01d for tbpatrimonio_configuracao
active before delete position 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    IF(OLD.ID > 0 AND OLD.COMPONENTE_ID IS NULL) THEN
    BEGIN
        HISTORICO = HISTORICO||'CONFIGURACAO '||FN_LPAD(OLD.ID, 4, '0')||' EXCLUIDA';
    END

    IF(OLD.ID > 0 AND OLD.COMPONENTE_ID > 0) THEN
    BEGIN
        HISTORICO = HISTORICO||'CONFIGURACAO '||FN_LPAD(OLD.ID, 4, '0')||' EXCLUIDA NO COMPONENTE '||FN_LPAD(OLD.COMPONENTE_ID, 5, '0');
    END
    
    IF(HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBPATRIMONIO', OLD.PATRIMONIO_ID, HISTORICO);
    END
END
^

SET TERM ; ^

