CREATE TABLE TBINVENTARIO_MATERIA_PRIMA (
    ID INTEGER NOT NULL,
    DESCRICAO VARCHAR(100),
    DATAHORA TIMESTAMP DEFAULT 'NOW',
    USUARIO_ID INTEGER);

ALTER TABLE TBINVENTARIO_MATERIA_PRIMA
ADD CONSTRAINT PK_TBINVENTARIO_MATERIA_PRIMA
PRIMARY KEY (ID);

CREATE SEQUENCE GTBINVENTARIO_MATERIA_PRIMA;

create trigger ttbinventario_materia_prima_bi for tbinventario_materia_prima
active before insert position 0
as
begin
  if (new.id is null) then
    new.id = gen_id(gtbinventario_materia_prima,1);
end;

CREATE trigger ttbinventario_mat_prima_b01i for tbinventario_materia_prima
active before insert position 1
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('TBINVENTARIO_MATERIA_PRIMA',NEW.ID, HISTORICO);
    END
END;


CREATE trigger ttbinventario_mat_prima_b01u for tbinventario_materia_prima
active before update position 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN
    HISTORICO = '';

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

    IF (HISTORICO <> '') THEN
    BEGIN
        HISTORICO = ' REGISTRO ALTERADO: '||HISTORICO;
        EXECUTE PROCEDURE SPI_HISTORICO('TBINVENTARIO_MATERIA_PRIMA',NEW.ID, HISTORICO);
    END
END;

CREATE trigger ttbinventario_mat_prima_b01d for tbinventario_materia_prima
active before delete position 0
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('TBINVENTARIO_MATERIA_PRIMA',OLD.ID, HISTORICO);
    END
END;

CREATE trigger ttbinventario_mat_prima_b02d for tbinventario_materia_prima
active before delete position 1
AS
BEGIN
   IF(OLD.ID > 0) THEN
   BEGIN
      DELETE FROM TBINVENTARIO_MAT_PRIMA_DETALHE WHERE INVENTARIO_ID = OLD.ID;
   END
END;


UPDATE OR INSERT INTO TBMENU (CONTROLE, GRUPO, SUBGRUPO, TIPO, URL, DESCRICAO, DATAHORA)
                      VALUES (15290, 'EST', 'EST', '1   ', '', 'REGISTRO DE INVENTÁRIO POR TIPO DE PRODUTO', '2022-02-03 08:21:08')
                    MATCHING (CONTROLE);

COMMIT WORK;




