CREATE GENERATOR GTBPDV;

CREATE TABLE TBPDV (
    ID                       INTEGER NOT NULL,
    DESCRICAO                VARCHAR(50),
    STATUS                   INTEGER,
    NUMERO_CAIXA             INTEGER,
    IMP_MODELO               VARCHAR(30),
    IMP_PORTA                VARCHAR(250),
    SAT_MODELO               VARCHAR(20),
    SAT_GRAVAR_LOG           VARCHAR(255),
    SAT_VERSAO_XML           VARCHAR(10),
    SAT_COD_ATIVACAO         VARCHAR(50),
    SAT_SH_CNPJ              VARCHAR(14),
    SAT_SH_ASSINATURA        VARCHAR(344),
    SAT_NUMERO_SERIE         INTEGER,
    MFE_CHAVE_ACESSO         VARCHAR(50),
    ESTABELECIMENTO_ID       INTEGER,
    ABATER_ICMS              INTEGER DEFAULT 0
);


SET TERM ^ ;

CREATE OR ALTER TRIGGER TTBPDV_B01I FOR TBPDV
ACTIVE BEFORE INSERT POSITION 0
as
begin
  if (new.id is null) then
    new.id = gen_id(gTBPDV,1);

end
^

CREATE OR ALTER TRIGGER TTBPDV_B01U FOR TBPDV
ACTIVE BEFORE UPDATE POSITION 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

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

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

CREATE OR ALTER TRIGGER TTBPDV_B02D FOR TBPDV
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('TBPDV',OLD.id, HISTORICO);
    END
END
^

CREATE OR ALTER TRIGGER TTBPDV_B02I FOR TBPDV
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('TBPDV',NEW.id, HISTORICO);
    END
END
^

COMMENT ON COLUMN TBPDV.STATUS IS 
'1 - ativo
0 - inativo';
