unit DevolucaoNF;

interface

uses
  Windows, system.UItypes, IB_Access,  Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, TelaComum, IB_Grid, StdCtrls, Mask, IB_Controls, ImgList,
  ExtCtrls, Buttons, IB_Components, Rotinas, IB_EditButton, System.ImageList;

type
  TfrmDevolucaoNF = class(TfrmTelaComum)
    GroupBox3: TGroupBox;
    dbNF: TIB_Edit;
    btnPesquisaNF: TBitBtn;
    IB_Edit1: TIB_Edit;
    IB_Edit3: TIB_Edit;
    GroupBox7: TGroupBox;
    edtCidadeTransporte: TIB_Edit;
    dbNomeFantasia: TIB_Edit;
    dbInscricao: TIB_Edit;
    edtUF: TIB_LookupCombo;
    IB_Edit2: TIB_Edit;
    qryNF: TIB_Query;
    dtNF: TIB_DataSource;
    qryHistorico: TIB_Query;
    GroupBox1: TGroupBox;
    edtCFOP: TIB_Edit;
    IB_Edit20: TIB_Edit;
    dbNovoCFOP: TIB_Edit;
    btnPesquisaCFOP: TBitBtn;
    IB_Edit5: TIB_Edit;
    IB_RadioGroup2: TIB_RadioGroup;
    qryCFOP: TIB_Query;
    dtCFOP: TIB_DataSource;
    edtDataEmissao: TIB_Date;
    edtDataSaida: TIB_Date;
    qryNovaNF: TIB_Query;
    dtNovaNF: TIB_DataSource;
    qryNovoCFOP: TIB_Query;
    dtNovoCFOP: TIB_DataSource;
    qryRegras_Imposto: TIB_Query;
    qryPesquisa: TIB_Query;
    qryItens: TIB_Query;
    qryNovosItens: TIB_Query;
    edtSerie: TLabeledEdit;
    edtNumero: TLabeledEdit;
    edtHora: TLabeledEdit;
    edtdataCadastro: TIB_Date;
    procedure btnPesquisaNFClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure btnPesquisaCFOPClick(Sender: TObject);
    procedure BtGravarClick(Sender: TObject);
  private
    function NovoCFOPBaseRegraImposto: integer;
    procedure DadosNF;
    procedure AtualizaParametrosUltimaGerada;
    procedure GravaNovaNF;
    function UltimoNumero: Integer;
    { Private declarations }
  public
    { Public declarations }
  end;

var
  frmDevolucaoNF: TfrmDevolucaoNF;
  codigoDeErro_Tabela:Integer;

implementation

uses ModeloPesquisa, DataModulo, ConfigacaoSistema;

{$R *.dfm}

procedure TfrmDevolucaoNF.btnPesquisaNFClick(Sender: TObject);
begin
  inherited;
   frmModeloPesquisa        := TfrmModeloPesquisa.Create(Application);
   frmModeloPesquisa.Tabela := qryNF;
   frmModeloPesquisa.lblTitulo.Caption := 'Pesquisa NF';
   if frmModeloPesquisa.ShowModal = mrOk then
      qryNF.Locate('NUMERO' , frmModeloPesquisa.TbPrincipal.FieldByName('NUMERO').Value , []);
   frmModeloPesquisa.Destroy;

   if qryNF.FieldByName('ENTRADA_SAIDA').AsString = 'E' then
   begin
     MessageDlg('NF de entrada não posso gerar NF de devolução', mtError, [mbOK], 0);
     qryNF.Close;
     qryNF.Open;
      if not qryNF.Bof then
      begin
         qryNF.First;
         qryNF.Prior;
      end;
     Exit;
   end;

   edtNumero.Text := IntToStr(UltimoNumero +1);
   edtSerie.Text  :=qryNF.FieldByName('SERIE').AsString;
   edtHora.Text   :=TimeToStr(Time);

   edtdataCadastro.Text   :=DateToStr(Date);
   edtDataEmissao.Text    :=DateToStr(Date);
   edtDataSaida.Text      :=DateToStr(Date);

   NovoCFOPBaseRegraImposto;

   Screen.OnActiveControlChange := TrocaCor;
end;

procedure TfrmDevolucaoNF.FormCreate(Sender: TObject);
begin
  inherited;
   if (Dados.qryParametro_NF.FieldByName('ULTIMA_NF_CADASTRADA').AsString = '') or (Dados.qryParametro_NF.FieldByName('SERIE_NF').AsString = '') then
   begin
      if MessageDlg('É necessário informar a Numeração e Série da NF'+#13+#10+'nos parâmetros do sistema.'+#13+#10+''+#13+#10+'Deseja informar agora?', mtWarning, [mbYes, mbNo], 0) = Mryes then
      begin
         frmConfiguracao := TfrmConfiguracao.Create(Application);
         frmConfiguracao.pgPrincipal.ActivePage := frmConfiguracao.tabNF;
         frmConfiguracao.ShowModal;
         frmConfiguracao.Destroy;
         Screen.OnActiveControlChange := TrocaCor;
      end;
      Exit;
   end;

  qryNF.Open;
  if not qryNF.Bof then
  begin
     qryNF.First;
     qryNF.Prior;
  end;

  qryNovaNF.Open;


  qryCFOP.Open;
  if not qryCFOP.Bof then
  begin
     qryCFOP.First;
     qryCFOP.Prior;
  end;

  qryNovoCFOP.Open;
  if not qryNovoCFOP.Bof then
  begin
     qryNovoCFOP.First;
     qryNovoCFOP.Prior;
  end;

  qryHistorico.Open;
  qryRegras_Imposto.Open;

end;

procedure TfrmDevolucaoNF.btnPesquisaCFOPClick(Sender: TObject);
begin
  inherited;
   frmModeloPesquisa        := TfrmModeloPesquisa.Create(Application);
   frmModeloPesquisa.Tabela := qryNovoCFOP;
   frmModeloPesquisa.lblTitulo.Caption := 'Pesquisa CFOP de Entrada';
   if frmModeloPesquisa.ShowModal = mrOk then
      qryNovoCFOP.Locate('NUMERO' , frmModeloPesquisa.TbPrincipal.FieldByName('COD_CFOP').Value , []);
   frmModeloPesquisa.Destroy;
   qryNovaNF.FieldByName('COD_CFOP').Value:=qryNovoCFOP.FIeldbyName('COD_CFOP').Value;
   Screen.OnActiveControlChange := TrocaCor;

end;

procedure TfrmDevolucaoNF.BtGravarClick(Sender: TObject);
begin
  if qryNovoCFOP.FieldByName('COD_CFOP').IsNull then
  begin
     MessageDlg('Informe o CFOP da nova NF', mtWarning, [mbOK], 0);
     dbNovoCFOP.SetFocus;
  end;
  if (MessageDlg('Confirma os dados da NF de devolução com base na NF de Saída?', mtConfirmation, [mbYes, mbNo], 0) in [mrYes]) then
  begin
    Mostrar_TelaEspera;
    DadosNF;
    AtualizaParametrosUltimaGerada;
    Destruir_TelaEspera;
    Close;
  end;
  inherited;
end;

function TfrmDevolucaoNF.NovoCFOPBaseRegraImposto:integer;
begin
  qryRegras_Imposto.Filtered:=False;
  qryRegras_Imposto.Filter:=' COD_CFOP ='+qryNF.FieldbyName('COD_CFOP').AsString;
  qryRegras_Imposto.Filtered:=True;

  if NOT qryRegras_Imposto.IsEmpty then
  begin
    qryNovoCFOP.Locate('COD_CFOP',qryRegras_Imposto.FieldbyName('CFOP_DEVOLUCAO').AsString,[]);
    Result:=qryRegras_Imposto.FieldbyName('CFOP_DEVOLUCAO').AsInteger;
  end
  else Result:=0;
end;

procedure TfrmDevolucaoNF.DadosNF;
var i,j:integer;
begin

  qryNovaNF.Insert;

  for i := 0 to (qryNF.FieldCount-1) do
    qryNovaNF.Fields[i].Value:=qryNF.Fields[i].Value;

   Dados.qryParametro_NF.RefreshAll;

  qryNovaNF.FIeldByName('FINALIDADE_EMISSAO').Value := 'DEVOLUÇÃO';
  qryNovaNF.FIeldByName('REFERENCIA_NFE').Value     := qryNF.FieldByName('CHAVE_ACESSO').AsString;

  qryNovaNF.FieldByName('NUMERO').AsString     := edtNumero.Text;
  qryNovaNF.FieldByName('ENTRADA_SAIDA').Value  :='E';
  qryNovaNF.FieldByName('DATA_CADASTRO').Value  :=edtdataCadastro.Text;
  qryNovaNF.FieldByName('DATA_EMISSAO').Value   :=edtDataEmissao.Text;
  qryNovaNF.FieldByName('DATA_SAIDA').Value     :=edtDataSaida.Text;
  qryNovaNF.FieldByName('HORA_SAIDA').Value     :=edtHora.Text;
  qryNovaNF.FieldByName('COD_FILIAL').Value     :=dados.qrFilial.FieldByName('COD_FILIAL').Value;
  qryNovaNF.FieldByName('COD_USUARIO').Value    :=dados.qrUsuario.FieldByName('COD_USUARIO').Value;
  qryNovaNF.FieldByName('COD_CFOP').Value       :=qryNovoCFOP.fieldByName('COD_CFOP').Value;
  qryNovaNF.FieldByName('CHAVE_ACESSO').Clear;
  qryNovaNF.FieldByName('PROTOCOLO_AUTORIZACAO').Clear;

  GravaNovaNF;

  qryItens.Close;
  qryItens.ParamByName('VARNF').Value:=qryNF.FieldbyName('NUMERO').Value;
  qryItens.Open;

  qryNovosItens.Close;
  qryNovosItens.ParamByName('VARNF').Value:=qryNovaNF.FieldbyName('NUMERO').Value;
  qryNovosItens.Open;

  for i:= 0 to qryItens.RecordCount do
  begin
    qryNovosItens.Insert;
    for j := 1 to (qryItens.FieldCount -1) do
    begin
      qryNovosItens.Fields[j].Value:=qryItens.Fields[j].Value;
    end;

    qryNovosItens.FieldByName('COD_CFOP').Value      :=qryNovaNF.FieldByName('COD_CFOP').Value;
    qryNovosItens.FieldByName('COD_FILIAL_NF').Value :=qryNovaNF.FieldByName('COD_FILIAL').Value;
    qryNovosItens.FieldByName('COD_NF').Value        :=qryNovaNF.FieldByName('NUMERO').Value;
    qryNovosItens.PostRetaining;

    if NOT qryItens.Eof then
      qryItens.Next;
  end;

end;

function TfrmDevolucaoNF.UltimoNumero:Integer;
begin
  //===================== Update nos paramentros com o codigo da ultima NF gerada para a numeracao continuar em sequencia =====================
  qryPesquisa.Close;
  qryPesquisa.SQL.Clear;
  qryPesquisa.SQL.Add(' select max(numero) as numero from NF ');
  qryPesquisa.Open;

  Result:=qryPesquisa.FieldByName('NUMERO').asInteger;
end;

procedure TfrmDevolucaoNF.AtualizaParametrosUltimaGerada;
begin

  Dados.qryParametro_NF.Edit;
  Dados.qryParametro_NF.FieldByName('ULTIMA_NF_CADASTRADA').Value := UltimoNumero;
  Dados.qryParametro_NF.Post;

end;

procedure TfrmDevolucaoNF.GravaNovaNF;
begin
  try
    qryNovaNF.PostRetaining;
  except
    if (codigoDeErro_Tabela = 335544665) then
    begin
      qryNovaNF.FieldByName('NUMERO').Value:=UltimoNumero;
      GravaNovaNF;
    end;
  end;
  qryNovaNF.RefreshAll;
end;

end.
