SET TERM ^ ;

CREATE OR ALTER trigger ttbcomissao_b02d for tbcomissao
active before delete position 0
AS
BEGIN
   IF(COALESCE(OLD.SALDO,0) = 0 OR COALESCE(OLD.SALDO,0) < COALESCE(OLD.VALOR,0)) THEN
   BEGIN
      --EXCEPTION "..." 'COMISSAO '||FN_LPAD(OLD.ID,5,0)||', DT.EMISSAO:'||FN_DATE(OLD.DATA_EMISSAO,'DD/MM/YYYY')||', VALOR:'||OLD.VALOR||' JA UTILIZADA, EXCLUSAO CANCELADA!';
   END

   IF(COALESCE(OLD.PREVISAO_ID, 0) > 0) THEN
   BEGIN
      DELETE FROM TBCAIXABANCO_PREVISAO A WHERE A.CONTROLE = OLD.PREVISAO_ID;
   END
END
^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER trigger ttbcaixabanco_previsao_b03i for tbcaixabanco_previsao
active before insert or update position 0
AS
begin

    IF(INSERTING)THEN
    BEGIN
        if(new.DATA_COMPETENCIA is not null)then
        begin
           new.DATA_COMPETENCIA = FN_START_OF_MONTH_2(new.DATA_COMPETENCIA);
        end
    
        if(new.DATA_COMPETENCIA is null)then
        begin
           new.DATA_COMPETENCIA = FN_START_OF_MONTH_2(new.DATA_PREVISAO);
        end

    END
    IF(UPDATING)THEN
    BEGIN
        if(new.DATA_COMPETENCIA is not null)then
        begin
           new.DATA_COMPETENCIA = FN_START_OF_MONTH_2(new.DATA_COMPETENCIA);
        end
    END

       if (NEW.VALOR_TOTAL <= 0) THEN
           BEGIN
             --EXCEPTION "..." 'VALOR DA PROVISAO NAO PODE SER ZERADO!';
           END

end
^

SET TERM ; ^

