CREATE OR ALTER TRIGGER TTBPDV_CFE_A02U FOR TBPDV_CFE
ACTIVE AFTER UPDATE POSITION 2
AS
BEGIN
  /* ALTERACAO DE REPRESENTANTE*/
  IF(OLD.REPRESENTANTE_ID <> NEW.REPRESENTANTE_ID
  OR (OLD.REPRESENTANTE_COMISSAO <> NEW.REPRESENTANTE_COMISSAO)
  OR OLD.VENDEDOR_ID    <> NEW.VENDEDOR_ID
  OR OLD.CORRETOR_ID     <> NEW.CORRETOR_ID) THEN
  BEGIN
     /*GERAR COMISSAO*/
        DELETE FROM TBCOMISSAO A WHERE A.ORIGEM = 'CFE' AND A.TABELA_ID = NEW.ID;

        EXECUTE PROCEDURE SPI_CFE_GERAR_COMISSAO(NEW.ID);

        EXECUTE PROCEDURE SPI_GERAR_COMISSAO(NEW.ID,'CFE');

  END


  /* SITUACAO AUTORIZADO */
  IF(OLD.SITUACAO = 1 AND NEW.SITUACAO = 2) THEN
  BEGIN /*GERAR COMISSAO*/
        EXECUTE PROCEDURE SPI_CFE_GERAR_COMISSAO(NEW.ID);

        EXECUTE PROCEDURE SPI_GERAR_COMISSAO(NEW.ID,'CFE');

  END ELSE
  /* SITUACAO CANCELADO */
  IF((OLD.SITUACAO = 2 AND NEW.SITUACAO = 3) OR (OLD.SITUACAO = 1 AND NEW.SITUACAO = 3) OR (OLD.SITUACAO = 2 AND NEW.SITUACAO = 1) ) THEN
  BEGIN
        /*APAGAR COMISSAO*/
        DELETE FROM TBCOMISSAO A WHERE A.ORIGEM = 'CFE' AND A.TABELA_ID = NEW.ID;
  END

END^

CREATE OR ALTER TRIGGER TBCHEQUE_A01U FOR TBCHEQUE
ACTIVE AFTER UPDATE POSITION 0
AS
BEGIN
  IF(OLD.SITUACAO <> NEW.SITUACAO)THEN
  BEGIN
     IF(NEW.SITUACAO = 1)THEN
     BEGIN
        EXECUTE PROCEDURE SPI_GERAR_COMISSAO(NEW.ID,'CHE');
     END

     IF((OLD.SITUACAO = 1) AND (NEW.SITUACAO <> OLD.SITUACAO))THEN
     BEGIN
        DELETE FROM TBCOMISSAO COM WHERE COM.ORIGEM = 'CHE' AND COM.TABELA_ID = OLD.ID;
     END
  END
END^

CREATE OR ALTER TRIGGER TBCHEQUE_A01U FOR TBCHEQUE
ACTIVE AFTER UPDATE POSITION 0
AS
BEGIN
  IF(OLD.SITUACAO <> NEW.SITUACAO)THEN
  BEGIN
     IF(NEW.SITUACAO = 1)THEN
     BEGIN
        EXECUTE PROCEDURE SPI_GERAR_COMISSAO(NEW.ID,'CHE');
     END

     IF((NEW.SITUACAO = 3 AND OLD.SITUACAO = 1) OR (NEW.SITUACAO = 2 AND OLD.SITUACAO = 1))THEN
     BEGIN
        DELETE FROM TBCOMISSAO COM WHERE COM.ORIGEM = 'CHE' AND COM.TABELA_ID = OLD.ID;
     END
  END
END^

CREATE OR ALTER TRIGGER TTBCHEQUE_B02D FOR TBCHEQUE
ACTIVE BEFORE DELETE POSITION 1
AS
BEGIN
    DELETE FROM TBCHEQUE_ITEM A WHERE A.CHEQUE_ID = OLD.ID;

    DELETE FROM TBCOMISSAO COM WHERE COM.TABELA_ID = OLD.ID AND COM.ORIGEM = 'CHE';
END^

CREATE OR ALTER TRIGGER TTBCAIXABANCO_LANC_REG_B2D FOR TBCAIXABANCO_LANCAMENTO_REG
ACTIVE BEFORE DELETE POSITION 2
AS
DECLARE VARIABLE CHEQUE_SIT INTEGER;
DECLARE VARIABLE COMISSAO_ID INTEGER;
BEGIN

    IF (OLD.LANCAMENTO_CLASS_ID > 0) THEN
    BEGIN
    
        CHEQUE_SIT = COALESCE((SELECT FIRST 1 A.SITUACAO FROM TBCHEQUE A WHERE A.ID = OLD.CHEQUE_ID), -1);
        
        IF(CHEQUE_SIT = 5 AND OLD.CHEQUE_ID > 0)THEN
        BEGIN
            EXCEPTION "..." 'CHEQUE: '||FN_LPAD(OLD.CHEQUE_ID, 4, '0')||' VINCULADO AO REGISTRO COM SITUACAO DEVOLVIDO. EXCLUSAO NAO AUTORIZADA!';
        END
        
        IF((OLD.LANCAMENTO_ANTECIPADO_ID IS NULL OR OLD.LANCAMENTO_ANTECIPADO_ID = 0))THEN
        BEGIN
             UPDATE TBCAIXABANCO_LANC_CLASS_SALDO SET
               SALDO = SALDO + OLD.VALOR_TOTAL
               WHERE ID = OLD.LANCAMENTO_CLASS_ID;
        END
    END

    IF (((OLD.NFS_PARCELAMENTO_CONTROLE > 0) OR (OLD.NFE_PARCELAMENTO_CONTROLE > 0)) AND OLD.CODORIGEM IN ('CPA', 'CRE') AND COALESCE(OLD.CAIXABANCO_CONTROLE,0) = 0 AND OLD.MOVCONTMESTRE_ID > 0) THEN
    BEGIN

        DELETE FROM TBMOVCONTMESTRE WHERE ID = OLD.MOVCONTMESTRE_ID;

    END

    :COMISSAO_ID = COALESCE((SELECT FIRST 1 A.ID FROM TBCOMISSAO A WHERE A.TABELA_ID = OLD.CONTROLE AND A.ORIGEM = 'LAN'),0);
    IF(:COMISSAO_ID > 0)THEN
    BEGIN
      DELETE FROM TBCOMISSAO A WHERE A.ID = :COMISSAO_ID;
    END

END^

CREATE OR ALTER TRIGGER TTBNFS_PARCELAMENTO_A01U FOR TBNFS_PARCELAMENTO
ACTIVE AFTER UPDATE POSITION 1
AS
DECLARE VARIABLE PDV_CFE_ID INTEGER;

BEGIN
  IF((  (NEW.VALOR_SALDO                <> OLD.VALOR_SALDO)
    OR  (NEW.PAGAMENTO_FORMA            <> OLD.PAGAMENTO_FORMA))
    AND COALESCE(NEW.COLABORADOR_ID, 0) > 0) THEN
  BEGIN
       EXECUTE PROCEDURE SPU_SALDO_COLABORADOR(NEW.COLABORADOR_ID);
  END

  IF(NEW.PAGAMENTO_FORMA <> OLD.PAGAMENTO_FORMA
  OR NEW.VALOR           <> OLD.VALOR) THEN
  BEGIN
     :PDV_CFE_ID = COALESCE((SELECT FIRST 1 CFE_PAG.PDV_CFE_ID FROM TBPDV_CFE_FORMA_PAGAMENTO CFE_PAG WHERE CFE_PAG.ID = NEW.PDV_CFE_FORMA_PAGAMENTO_ID),0);

     IF(:PDV_CFE_ID > 0)THEN
     BEGIN
        EXECUTE PROCEDURE SPI_CFE_GERAR_COMISSAO(:PDV_CFE_ID);

        EXECUTE PROCEDURE SPI_GERAR_COMISSAO(:PDV_CFE_ID,'CFE');
     END

     IF(NEW.AVULSO = '1')THEN
     BEGIN
       EXECUTE PROCEDURE SPI_GERAR_COMISSAO(NEW.CONTROLE,'AVU');
     END
  END
END^

CREATE OR ALTER TRIGGER TBCAIXABANCO_LANC_REG_A01I FOR TBCAIXABANCO_LANCAMENTO_REG
ACTIVE AFTER INSERT POSITION 0
AS
DECLARE VARIABLE COMISSAO VARCHAR(1);
BEGIN
   COMISSAO = '0';

   IF(NEW.NFS_PARCELAMENTO_CONTROLE > 0) THEN
   BEGIN
     :COMISSAO = COALESCE((SELECT FIRST 1 OP.COMISSAO FROM TBCONTA_RECEBER_OPERACAO OP WHERE OP.CODIGO = NEW.OPERACAO_CODIGO AND OP.COMISSAO = '1'),'0');

     IF(:COMISSAO = '1')THEN
     BEGIN
        EXECUTE PROCEDURE SPI_GERAR_COMISSAO(NEW.CONTROLE,'LAN');
     END
   END
END^

CREATE OR ALTER TRIGGER TBCAIXABANCO_LANCAMENTO_REG_AU0 FOR TBCAIXABANCO_LANCAMENTO_REG
ACTIVE AFTER UPDATE POSITION 0
AS
DECLARE VARIABLE COMISSAO_ID INTEGER;
BEGIN
  IF(NEW.VALOR_TOTAL     <> OLD.VALOR_TOTAL
  OR NEW.OPERACAO_CODIGO <> OLD.OPERACAO_CODIGO)THEN
   BEGIN
       :COMISSAO_ID = COALESCE((SELECT FIRST 1 A.ID FROM TBCOMISSAO A WHERE A.TABELA_ID = NEW.CONTROLE AND A.ORIGEM = 'LAN'),0);
       IF(:COMISSAO_ID > 0)THEN
       BEGIN
          DELETE FROM TBCOMISSAO A WHERE A.ID = :COMISSAO_ID;

          EXECUTE PROCEDURE SPI_GERAR_COMISSAO(NEW.CONTROLE,'LAN');
       END
   END
END^

CREATE OR ALTER TRIGGER TTBCAIXABANCO_LANC_REG_B1D_01 FOR TBCAIXABANCO_LANCAMENTO_REG
ACTIVE BEFORE DELETE POSITION 1
AS
BEGIN

  IF (OLD.CONTROLE > 0) THEN
      BEGIN
        UPDATE TBCCUSTO_COTA_DETALHE SET
        STATUSEXCLUSAO = '1'
        WHERE TABELA = OLD.CODORIGEM
          AND TABELA_ID = OLD.CONTROLE;
      END

   IF(OLD.NFS_PARCELAMENTO_CONTROLE > 0)THEN
   BEGIN
      DELETE FROM TBCOMISSAO A WHERE A.TABELA_ID = OLD.CONTROLE AND A.ORIGEM = 'LAN';
   END
END^

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

  :PDV_CFE_ID = COALESCE((SELECT FIRST 1 CFE_PAG.PDV_CFE_ID FROM TBPDV_CFE_FORMA_PAGAMENTO CFE_PAG WHERE CFE_PAG.ID = OLD.PDV_CFE_FORMA_PAGAMENTO_ID),0);

  IF(:PDV_CFE_ID > 0)THEN
  BEGIN
     EXECUTE PROCEDURE SPI_CFE_GERAR_COMISSAO(:PDV_CFE_ID);

     EXECUTE PROCEDURE SPI_GERAR_COMISSAO(:PDV_CFE_ID,'CFE');
  END
END^

CREATE OR ALTER TRIGGER TBCOMISSAO_BI2 FOR TBCOMISSAO
ACTIVE BEFORE INSERT POSITION 2
AS
DECLARE VARIABLE PREVISAO_ID INTEGER;
BEGIN
   :PREVISAO_ID = GEN_ID(GTBCAIXABANCO_PREVISAO,1);

     EXECUTE PROCEDURE SPI_PROVISAO_COMISSAO (
        NEW.ESTABELECIMENTO_ID,
        FN_PARAMETRO('TBESTABELECIMENTO.COMISSAO_CAIXABANCO',NEW.ESTABELECIMENTO_ID),
        NEW.DATA_EMISSAO,
        NEW.DATA_EMISSAO,
        NEW.VALOR,
        :PREVISAO_ID,
        FN_PARAMETRO('TBESTABELECIMENTO.COMISSAO_CCUSTO',NEW.ESTABELECIMENTO_ID),
        FN_PARAMETRO('TBESTABELECIMENTO.COMISSAO_CLASSIF_FINANCEIRA',NEW.ESTABELECIMENTO_ID),
        0,
        FN_PARAMETRO('TBESTABELECIMENTO.COMISSAO_PAGAMENTO_FORMA',NEW.ESTABELECIMENTO_ID));

    NEW.PREVISAO_ID = :PREVISAO_ID;

END^

CREATE OR ALTER TRIGGER TTBNFS_PARCELAMENTO_A01I FOR TBNFS_PARCELAMENTO
ACTIVE AFTER INSERT POSITION 9
AS
DECLARE VARIABLE PDV_CFE_ID INTEGER;
BEGIN
  :PDV_CFE_ID = COALESCE((SELECT FIRST 1 CFE_PAG.PDV_CFE_ID FROM TBPDV_CFE_FORMA_PAGAMENTO CFE_PAG WHERE CFE_PAG.ID = NEW.PDV_CFE_FORMA_PAGAMENTO_ID),0);

  IF(:PDV_CFE_ID > 0)THEN
  BEGIN
     EXECUTE PROCEDURE SPI_CFE_GERAR_COMISSAO(:PDV_CFE_ID);

     EXECUTE PROCEDURE SPI_GERAR_COMISSAO(:PDV_CFE_ID,'CFE');
  END

  IF(NEW.AVULSO = '1') THEN
  BEGIN
     EXECUTE PROCEDURE SPI_GERAR_COMISSAO(NEW.CONTROLE,'AVU');
  END
END^

CREATE OR ALTER TRIGGER TTBNFS_A01D FOR TBNFS
ACTIVE AFTER DELETE POSITION 9
AS
BEGIN
  DELETE FROM TBCOMISSAO WHERE TABELA_ID = OLD.CONTROLE AND ORIGEM = 'NFS';
END^

CREATE OR ALTER TRIGGER TTBPDV_CFE_A01U FOR TBPDV_CFE
ACTIVE AFTER UPDATE POSITION 1
AS
DECLARE VARIABLE CAIXA_ID INTEGER;

DECLARE VARIABLE ESTABELECIMENTO_ID INTEGER;
DECLARE VARIABLE NUMERO_NOTAFISCAL INTEGER;
DECLARE VARIABLE DATA DATE;
DECLARE VARIABLE HISTORICO_CONTABIL VARCHAR(100);
DECLARE VARIABLE CONTA_DEBITO VARCHAR(50);
DECLARE VARIABLE CONTA_CREDITO VARCHAR(50);
DECLARE VARIABLE VALOR NUMERIC(18,2);
DECLARE VARIABLE VFALHAS VARCHAR(50);
DECLARE VARIABLE DOCUMENTO_TIPO VARCHAR(3);
DECLARE VARIABLE DOCUMENTO INTEGER;
DECLARE VARIABLE PAGAMENTO_FORMA_ID INTEGER;
DECLARE VARIABLE PARCELA INTEGER;
DECLARE VARIABLE VALOR_PARCELA DECIMAL(15,2);
DECLARE VARIABLE TARIFA DECIMAL(15,4);
DECLARE VARIABLE VALOR_LIQUIDO DECIMAL(15,2);
DECLARE VARIABLE NSU VARCHAR(50);
DECLARE VARIABLE ADQUIRENTE_ID INTEGER;
DECLARE VARIABLE BANDEIRA_CARTAO VARCHAR(100);
DECLARE VARIABLE CODIGO_AUTORIZACAO VARCHAR(50);
DECLARE VARIABLE CONCILIACAO VARCHAR(1);

BEGIN

  SELECT T.PDV_CAIXA_ID FROM TBPDV_MOVIMENTO_CAIXA T WHERE T.ID = NEW.PDV_MOVIMENTO_CAIXA_ID INTO CAIXA_ID;

  /* SITUACAO AUTORIZADO */
  IF(OLD.SITUACAO = 1 AND NEW.SITUACAO = 2) THEN
  BEGIN
        EXECUTE PROCEDURE SP_CFE_PEDIDO(NEW.ID, 1);

        EXECUTE PROCEDURE SP_CFE_CONFERENCIA(NEW.ID, 1);

        EXECUTE PROCEDURE SP_CFE_ESTOQUE(NEW.ID, NEW.ESTABELECIMENTO_ID, NEW.CLIENTE_ID, :CAIXA_ID,
            NEW.NUMERO_CFE, NEW.SERIE, NEW.DATA_EMISSAO, 1);

        EXECUTE PROCEDURE SP_CFE_PARCELAMENTO (NEW.ID, 1);

        EXECUTE PROCEDURE SP_CFE_FORMA_PAGAMENTO(NEW.ID, 2);

        EXECUTE PROCEDURE SPU_PREPEDIDO_CLIENTE(NEW.ID, NEW.CLIENTE_ID, 1);

        IF(NEW.NATUREZA = 1) THEN
        BEGIN

            FOR SELECT
                    ESTABELECIMENTO_ID,
                    NUMERO_NOTAFISCAL,
                    DATA,
                    HISTORICO_CONTABIL,
                    CONTA_DEBITO,
                    CONTA_CREDITO,
                    VALOR,
                    VFALHAS
                FROM SPI_NF_CONTABIL('CFI', NEW.ID, 0) T
            INTO :ESTABELECIMENTO_ID, :NUMERO_NOTAFISCAL, :DATA,
                :HISTORICO_CONTABIL, :CONTA_DEBITO, :CONTA_CREDITO,
                :VALOR, :VFALHAS
            DO BEGIN
    
            END

        END


        SELECT * FROM SP_FORMA_PAGAMENTO_CARTAO('CFE', NEW.ID, 1)
        INTO :DOCUMENTO_TIPO, :DOCUMENTO, :PAGAMENTO_FORMA_ID, :PARCELA, :VALOR_PARCELA, :TARIFA, :VALOR_LIQUIDO,
                 :NSU, :ADQUIRENTE_ID, :BANDEIRA_CARTAO, :CODIGO_AUTORIZACAO, :CONCILIACAO;

        /*GERAR COMISSAO
        EXECUTE PROCEDURE SPI_CFE_GERAR_COMISSAO(NEW.ID);

        EXECUTE PROCEDURE SPI_GERAR_COMISSAO(NEW.ID,'CFE');
        */

  END ELSE
  /* SITUACAO CANCELADO */
  IF((OLD.SITUACAO = 2 AND NEW.SITUACAO = 3) OR (OLD.SITUACAO = 1 AND NEW.SITUACAO = 3) OR (OLD.SITUACAO = 2 AND NEW.SITUACAO = 1) ) THEN
  BEGIN

        EXECUTE PROCEDURE SP_CFE_PARCELAMENTO (NEW.ID, 2);

        EXECUTE PROCEDURE SP_CFE_ESTOQUE(NEW.ID, NEW.ESTABELECIMENTO_ID, NEW.CLIENTE_ID, :CAIXA_ID,
            NEW.NUMERO_CFE, NEW.SERIE, NEW.DATA_EMISSAO, 2, 0);

        EXECUTE PROCEDURE SP_CFE_PEDIDO(NEW.ID, 2);

        EXECUTE PROCEDURE SP_CFE_CONFERENCIA(NEW.ID, 2);

        EXECUTE PROCEDURE SPU_PREPEDIDO_CLIENTE(NEW.ID, NEW.CLIENTE_ID, 2);

        IF(OLD.NATUREZA = 1) THEN
        BEGIN
            EXECUTE PROCEDURE SPD_MOVCONTABIL(NEW.ID, 'CFI');
        END

        EXECUTE PROCEDURE SP_CFE_FORMA_PAGAMENTO(NEW.ID, 1);

        DELETE FROM TBNFS_FORMA_PAGAMENTO T WHERE T.DOCUMENTO_TIPO = 'CFE' AND T.DOCUMENTO_ID = NEW.ID;

        /*APAGAR COMISSAO*/
        DELETE FROM TBCOMISSAO A WHERE A.ORIGEM = 'CFE' AND A.TABELA_ID = NEW.ID;
  END

END^

CREATE OR ALTER 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 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
       :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^