SET TERM ^ ;

CREATE OR ALTER trigger ttbpdv_cfe_b10u for tbpdv_cfe
active before update position 10
AS
DECLARE VARIABLE VENDEDOR_COMISSAO NUMERIC(15,2);
DECLARE VARIABLE CORRETOR_COMISSAO NUMERIC(15,2);
BEGIN
  IF(OLD.REPRESENTANTE_ID       <> NEW.REPRESENTANTE_ID
  OR OLD.REPRESENTANTE_COMISSAO <> NEW.REPRESENTANTE_COMISSAO
  OR OLD.ESTABELECIMENTO_ID     <> NEW.ESTABELECIMENTO_ID
  OR OLD.VENDEDOR_ID            <> NEW.VENDEDOR_ID
  OR OLD.CORRETOR_ID            <> NEW.CORRETOR_ID)THEN
  BEGIN
     --EXECUTE PROCEDURE SPI_GERAR_COMISSAO(NEW.ID,'CFE');
    IF(COALESCE(NEW.REPRESENTANTE_ID,0)      <> COALESCE(OLD.REPRESENTANTE_ID,0)
    OR COALESCE(NEW.REPRESENTANTE_COMISSAO,0.00) <> COALESCE(OLD.REPRESENTANTE_COMISSAO,0.00))THEN
    BEGIN
      IF(COALESCE(NEW.REPRESENTANTE_COMISSAO,0.00) > 0 AND COALESCE(NEW.REPRESENTANTE_ID,0) > 0)THEN
      BEGIN
         EXECUTE PROCEDURE SPI_GERAR_COMISSAO(NEW.ID,'CFE',1);
      END
      ELSE
      BEGIN
           DELETE FROM TBCOMISSAO A
             WHERE A.TABELA_ID        = NEW.ID
               AND A.ORIGEM           = 'CFE'
               AND A.REPRESENTANTE_ID > 0;
      END
    END

    IF(COALESCE(NEW.VENDEDOR_ID,0) <> COALESCE(OLD.VENDEDOR_ID,0))THEN
    BEGIN
        /* ATUALIZACAO DE VENDEDOR */
        UPDATE  TBPDV_CFE_ITEM C SET C.VENDEDOR_ID = NEW.VENDEDOR_ID WHERE C.PDV_CFE_ID = NEW.ID;

       :VENDEDOR_COMISSAO = COALESCE((SELECT FIRST 1 B.COMISSAO FROM TBREPRESENTANTE_VENDEDOR B WHERE B.CODIGO = NEW.VENDEDOR_ID AND B.GERAR_COMISSAO = 1),0);
       IF(:VENDEDOR_COMISSAO > 0)THEN
       BEGIN
           EXECUTE PROCEDURE SPI_GERAR_COMISSAO(NEW.ID,'CFE',2);
       END
       ELSE
       BEGIN
           DELETE FROM TBCOMISSAO A
             WHERE A.TABELA_ID     = NEW.ID
               AND A.ORIGEM        = 'CFE'
               AND A.VENDEDOR_ID   > 0;
       END
    END

    IF(COALESCE(NEW.CORRETOR_ID,0) <> COALESCE(OLD.CORRETOR_ID,0))THEN
    BEGIN
       :CORRETOR_COMISSAO = COALESCE((SELECT FIRST 1 B.COMISSAO FROM TBCORRETOR B WHERE B.ID = NEW.CORRETOR_ID AND B.GERAR_COMISSAO = 1),0);
       IF(:CORRETOR_COMISSAO > 0)THEN
       BEGIN
           EXECUTE PROCEDURE SPI_GERAR_COMISSAO(NEW.ID,'CFE',3);
       END
       ELSE
       BEGIN
           DELETE FROM TBCOMISSAO A
             WHERE A.TABELA_ID     = NEW.ID
               AND A.ORIGEM        = 'CFE'
               AND A.CORRETOR_ID   > 0;
       END
    END
  END
END
^

SET TERM ; ^

