CREATE INDEX ITBPAGAMENTO_FORMA_07
ON TBPAGAMENTO_FORMA (PDV_ADQUIRENTE_ID);

SET TERM ^ ;

CREATE trigger ttbpagamento_forma_b02iu for tbpagamento_forma
active before insert or update position 2
AS
BEGIN
    IF(INSERTING) THEN
    BEGIN
        IF(NEW.PDV_ADQUIRENTE_ID > 0) THEN
        BEGIN
            NEW.EMPRESA_ID = COALESCE((SELECT FIRST 1 T.EMPRESA_ID FROM TBPDV_ADQUIRENTE T WHERE T.ID = NEW.PDV_ADQUIRENTE_ID), 0);
        END
    END

    IF(UPDATING) THEN
    BEGIN
        IF(OLD.PDV_ADQUIRENTE_ID IS DISTINCT FROM NEW.PDV_ADQUIRENTE_ID) THEN
        BEGIN
            NEW.EMPRESA_ID = COALESCE((SELECT FIRST 1 T.EMPRESA_ID FROM TBPDV_ADQUIRENTE T WHERE T.ID = NEW.PDV_ADQUIRENTE_ID), 0);
        END
    END
END
^

SET TERM ; ^


SET TERM ^ ;

CREATE trigger ttbpdv_adquirente_b02u for tbpdv_adquirente
active before update position 2
AS
BEGIN
    IF(OLD.EMPRESA_ID IS DISTINCT FROM NEW.EMPRESA_ID) THEN
    BEGIN
        UPDATE TBPAGAMENTO_FORMA T SET T.EMPRESA_ID = NEW.EMPRESA_ID WHERE T.PDV_ADQUIRENTE_ID = NEW.ID;
    END
END
^

SET TERM ; ^


SET TERM ^ ;

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

  IF(OLD.CARTAO_BANDEIRA_ID <> NEW.CARTAO_BANDEIRA_ID)THEN
  BEGIN
     NEW.BANDEIRA_CARTAO = COALESCE((SELECT FIRST 1 BANDEIRA.DESCRICAO FROM TBCARTAO_BANDEIRA BANDEIRA WHERE BANDEIRA.ID = NEW.CARTAO_BANDEIRA_ID),'');
  END

  IF(OLD.PAGAMENTO_FORMA_ID <> NEW.PAGAMENTO_FORMA_ID)THEN
  BEGIN
     NEW.ADQUIRENTE_ID = COALESCE((SELECT FIRST 1 PDV_ADQ.ADQUIRENTE_ID
                                        FROM TBPAGAMENTO_FORMA B, TBPDV_ADQUIRENTE PDV_ADQ
                                        WHERE B.CODIGO = NEW.PAGAMENTO_FORMA_ID AND B.NFE_TIPPAG IN ('03','04')
                                        AND B.EMPRESA_ID > 0 AND B.STATUS = '1' AND B.EMPRESA_ID = PDV_ADQ.EMPRESA_ID),0);

     IF(NEW.ADQUIRENTE_ID = 0)THEN
     BEGIN
        NEW.NSU                = '';
        NEW.CODIGO_AUTORIZACAO = '';
        NEW.BANDEIRA_CARTAO    = '';
     END
  END
END
^

SET TERM ; ^

