SET TERM ^ ;

CREATE OR ALTER trigger ttbremessa_item_processado_b14u for tbremessa_item_processado
active before update position 0
AS
declare variable vinculo integer;
begin
  if(new.entrada_cd is distinct from old.entrada_cd and new.entrada_cd = 1)then
  begin
        vinculo = 0;
        vinculo = coalesce(( select first 1 g.id
                        from tbremessa_consumo v, tbremessa_consumo_vinculo g
                        where v.remessa = new.remessa
                        and v.talao = new.controle
                        and g.consumo_id = v.id),0);
                
        if((new.controle between 6000 and 6999) or (vinculo = 0))then
        begin
            if(new.controle between 6000 and 6999)then
            begin
                new.situacao = 3;
            end else
            begin
                new.situacao = 2;
            end

            new.DATA_PRODUCAO = (SELECT FIRST 1 T.DATA_PRODUCAO FROM TBTURNO T WHERE T.TURNO_CORRENTE = '1');
            new.HORA_PRODUCAO = CURRENT_TIMESTAMP;
            new.TURNO         = (SELECT FIRST 1 T.CODIGO FROM TBTURNO T WHERE T.TURNO_CORRENTE = '1');

            update tbpedido_item_processado p set p.situacao = 3 where p.remessa = new.remessa and p.remessa_acumulado_controle = new.controle;
        end else
        begin
    
            if(new.situacao = 1)then
            begin
                Exception "..." 'ATENCAO, TALAO NAO CORTADO, OPERACAO CANCELADA!';
            end
        
            if(new.situacao = 3)then
            begin
                Exception "..." 'ATENCAO, TALAO LIBERADO PARA PRODUCAO, OPERACAO CANCELADA!';
            end
    
        end
    
        new.data_entrada_cd = current_timestamp;
        new.data_prod_entrada_cd = fn_data_producao();
  end
end
^

SET TERM ; ^

