CREATE TRIGGER TTBMAQUINA_B01I FOR TBMAQUINA
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF (NEW.ID IS NULL) THEN
    NEW.ID = GEN_ID(GTBMAQUINA,1);
END;

CREATE TRIGGER TTBMAQUINA_B02I FOR TBMAQUINA
ACTIVE BEFORE INSERT POSITION 0
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('TBMAQUINA',NEW.ID, HISTORICO);
    END
END;

CREATE TRIGGER TTBMAQUINA_B01U FOR TBMAQUINA
ACTIVE BEFORE UPDATE POSITION 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';
    
    IF (OLD.DESCRICAO <> NEW.DESCRICAO) THEN
    BEGIN
        HISTORICO = HISTORICO||' Descricao na Maq.: '||OLD.ID||', Alterada: '|| OLD.DESCRICAO||'->'||NEW.DESCRICAO;
    END
    
    IF (OLD.STATUS <> NEW.STATUS) THEN
    BEGIN
        if (NEW.STATUS = '1') then
           HISTORICO = HISTORICO||' Maq. ID: '||OLD.ID||', Status Ativa.';
        if (NEW.STATUS = '0') then
           HISTORICO = HISTORICO||' Maq. ID: '||OLD.ID||', Status Inativa.';
    END
    
    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBMAQUINA', NEW.ID, HISTORICO);
    END
END;

CREATE TRIGGER TTBMAQUINA_B01D FOR TBMAQUINA
ACTIVE BEFORE DELETE POSITION 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    IF (OLD.ID > 0) THEN
    BEGIN
        HISTORICO = HISTORICO||'Maq. ID: '||OLD.ID||', Excluida.';
    END

    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBMAQUINA',OLD.ID, HISTORICO);
    END
END;



