SET TERM ^ ;

CREATE OR ALTER trigger ttbnfs_referenciada_b02i for tbnfs_referenciada
active before insert position 2
AS
DECLARE VARIABLE NUMERO_NOTAFISCAL INTEGER;
DECLARE VARIABLE DATA_EMISSAO DATE;
DECLARE VARIABLE CFOP_CODIGO VARCHAR(10);
DECLARE VARIABLE SERIE VARCHAR(3);
DECLARE VARIABLE CONTROLE INTEGER;
BEGIN

    IF(NEW.PDV_CFE_ID > 0 AND CHAR_LENGTH(NEW.CHAVE_ACESSO) = 44 AND NEW.CONTROLE IS NULL) THEN
    BEGIN   

        FOR SELECT FIRST 1
            T.CONTROLE,
            T.DATA_EMISSAO,
            T.CFOP_CODIGO,
            T.NUMERO_NOTAFISCAL,
            T.SERIE

        FROM TBNFS T
        WHERE T.CHAVE_ACESSO = NEW.CHAVE_ACESSO
        INTO :CONTROLE, :DATA_EMISSAO, :CFOP_CODIGO, :NUMERO_NOTAFISCAL, :SERIE
        DO BEGIN
            NEW.NFS_CONTROLE        = 0;
            NEW.CONTROLE            = :CONTROLE;
            NEW.DATA_EMISSAO        = :DATA_EMISSAO;
            NEW.CFOP_CODIGO         = :CFOP_CODIGO;
            NEW.NUMERO_NOTAFISCAL   = :NUMERO_NOTAFISCAL;
            NEW.SERIE               = :SERIE;
        END

    END
END
^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER trigger ttbnfs_referenciada_b9i for tbnfs_referenciada
active before insert position 9
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
begin

   HISTORICO = 'CHAVE NF.REF INCLUIDA '||NEW.CHAVE_ACESSO;

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

