CREATE OR ALTER TRIGGER TTBNFS_PARCELAMENTO_B13U FOR TBNFS_PARCELAMENTO
ACTIVE BEFORE UPDATE POSITION 10
AS
begin
  IF((OLD.REPRESENTANTE_ID      <> NEW.REPRESENTANTE_ID
  or OLD.REPRESENTANTE_COMISSAO <> NEW.REPRESENTANTE_COMISSAO
  or OLD.VALOR                  <> NEW.VALOR
  or OLD.ESTABELECIMENTO_CODIGO <> NEW.ESTABELECIMENTO_CODIGO) AND OLD.AVULSO = 0)THEN
  BEGIN
     EXECUTE PROCEDURE SPI_GERAR_COMISSAO(NEW.NFS_CONTROLE,'NFS');
  END
  
  IF((OLD.REPRESENTANTE_ID      <> NEW.REPRESENTANTE_ID
  or OLD.REPRESENTANTE_COMISSAO <> NEW.REPRESENTANTE_COMISSAO
  or OLD.VALOR                  <> NEW.VALOR
  or OLD.ESTABELECIMENTO_CODIGO <> NEW.ESTABELECIMENTO_CODIGO) AND OLD.AVULSO = 1)THEN
  BEGIN
     EXECUTE PROCEDURE SPI_GERAR_COMISSAO(NEW.CONTROLE,'AVU');
  END
end;


CREATE OR ALTER TRIGGER TTBNFS_PARCELAMENTO_A01D FOR TBNFS_PARCELAMENTO
ACTIVE AFTER DELETE POSITION 9
AS
begin
  IF(OLD.AVULSO = '1')THEN
  BEGIN
     DELETE FROM TBCOMISSAO WHERE TABELA_ID = OLD.CONTROLE AND ORIGEM = 'AVU';
  END
end;

CREATE TRIGGER TTBNFS_PARCELAMENTO_B07I FOR TBNFS_PARCELAMENTO
ACTIVE BEFORE INSERT POSITION 7
AS
begin
   IF(NEW.AVULSO = 1)THEN
   BEGIN
      EXECUTE PROCEDURE SPI_GERAR_COMISSAO(NEW.CONTROLE,'AVU');
   END
   ELSE
   BEGIN
      EXECUTE PROCEDURE SPI_GERAR_COMISSAO(NEW.NFS_CONTROLE,'NFS');
   END
end;



CREATE TRIGGER TTBPDV_CFE_FORMA_PAG_B01U FOR TBPDV_CFE_FORMA_PAGAMENTO
ACTIVE BEFORE UPDATE POSITION 9
AS
begin
  IF(OLD.VALOR <> NEW.VALOR)THEN
  BEGIN
     EXECUTE PROCEDURE SPI_GERAR_COMISSAO(NEW.PDV_CFE_ID,'CFE');
  END
end;


CREATE TRIGGER TTBPDV_CFE_B10U FOR TBPDV_CFE
ACTIVE BEFORE UPDATE POSITION 10
AS
begin
  IF(OLD.REPRESENTANTE_ID      <> NEW.REPRESENTANTE_ID
  or OLD.REPRESENTANTE_COMISSAO <> NEW.REPRESENTANTE_COMISSAO
  or OLD.ESTABELECIMENTO_ID     <> NEW.ESTABELECIMENTO_ID)THEN
  BEGIN
     EXECUTE PROCEDURE SPI_GERAR_COMISSAO(NEW.ID,'CFE');
  END
end;

CREATE TRIGGER TTBPDV_CFE_B10D FOR TBPDV_CFE
ACTIVE BEFORE DELETE POSITION 10
AS
begin
   DELETE FROM TBCOMISSAO WHERE TABELA_ID = OLD.ID AND ORIGEM = 'CFE';
end;

CREATE TRIGGER TTBNFS_A01D FOR TBNFS
ACTIVE AFTER DELETE POSITION 9
AS
begin
  delete from TBCOMISSAO where tabela_id = old.controle and origem = 'NFS';
end;