unit uentrada;

interface

uses
  Windows, Messages, SysUtils, CLIPBRD, variants, Classes, Graphics, Controls, Forms, Dialogs,
  Db, DBTables, Grids, DBGrids, ExtCtrls, StdCtrls, Mask, DBCtrls, ComCtrls,
  ToolWin, Buttons, ActnList;

type

THackDBGrid = class(TDBGrid);

  Tfentrada = class(TForm)
    PageControl1: TPageControl;
    TabSheet1: TTabSheet;
    TabSheet2: TTabSheet;
    ScrollBox1: TScrollBox;
    Panel1: TPanel;
    Panel3: TPanel;
    ScrollBox2: TScrollBox;
    Label4: TLabel;
    DBEdit3: TDBEdit;
    DBGrid1: TDBGrid;
    Panel2: TPanel;
    Label1: TLabel;
    DBText1: TDBText;
    dsentrada: TDataSource;
    dsitem: TDataSource;
    DBRadioGroup1: TDBRadioGroup;
    ToolBar1: TToolBar;
    DBGrid2: TDBGrid;
    EditCodigo: TDBEdit;
    Label6: TLabel;
    ToolBar2: TToolBar;
    btnPrimeiro: TSpeedButton;
    btnVoltar: TSpeedButton;
    btnAvancar: TSpeedButton;
    btnUltimo: TSpeedButton;
    Panel7: TPanel;
    btncancelar: TSpeedButton;
    Panel8: TPanel;
    SpeedButton8: TSpeedButton;
    SpeedButton1: TSpeedButton;
    SpeedButton2: TSpeedButton;
    btnnovo: TSpeedButton;
    btngravar: TSpeedButton;
    Label2: TLabel;
    DBEdit1: TDBEdit;
    Label3: TLabel;
    DBEdit2: TDBEdit;
    DBEdit6: TDBEdit;
    Label7: TLabel;
    DBEdit4: TDBEdit;
    Label5: TLabel;
    Label8: TLabel;
    Panel4: TPanel;
    ActionList1: TActionList;
    totalizar: TAction;
    preencher: TAction;
    Label9: TLabel;
    Label10: TLabel;
    Label11: TLabel;
    Label12: TLabel;
    Label13: TLabel;
    Panel5: TPanel;
    Panel6: TPanel;
    Panel9: TPanel;
    Label15: TLabel;
    DBEdit5: TDBEdit;
    GroupBox5: TGroupBox;
    Label34: TLabel;
    Label35: TLabel;
    Bevel1: TBevel;
    Bevel2: TBevel;
    SpeedButton9: TSpeedButton;
    MaskEdit1: TMaskEdit;
    MaskEdit2: TMaskEdit;
    RadioButton1: TRadioButton;
    RadioButton2: TRadioButton;
    totalizar1: TAction;
    Panel13: TPanel;
    novo: TAction;
    avancar: TAction;
    voltar: TAction;
    DBEdit8: TDBEdit;
    excluir: TAction;
    campos: TAction;
    conta: TAction;
    DBLookupComboBox1: TDBLookupComboBox;
    Label24: TLabel;
    foco: TAction;
    estoque: TAction;
    Panel15: TPanel;
    Panel16: TPanel;
    preencherfornecedor: TAction;
    fimagem: TAction;
    IMAGE1: TDBImage;
    RadioButton3: TRadioButton;
    Label14: TLabel;
    Label16: TLabel;
    ComboBox1: TComboBox;
    ComboBox2: TComboBox;
    Bevel3: TBevel;
    Label17: TLabel;
    ComboBox3: TComboBox;
    btndelete: TSpeedButton;
    formatar: TAction;
    SpeedButton3: TSpeedButton;
    StatusBar1: TStatusBar;
    Panel10: TPanel;
    Label18: TLabel;
    DBEdit7: TDBEdit;
    ajuda: TAction;
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure EditCodigoKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure DBGrid1KeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure SpeedButton1Click(Sender: TObject);
    procedure SpeedButton2Click(Sender: TObject);
    procedure btnPrimeiroClick(Sender: TObject);
    procedure btnVoltarClick(Sender: TObject);
    procedure btnAvancarClick(Sender: TObject);
    procedure btnUltimoClick(Sender: TObject);
    procedure btncancelarClick(Sender: TObject);
    procedure Label2Click(Sender: TObject);
    procedure Label6Click(Sender: TObject);
    procedure Label7Click(Sender: TObject);
    procedure Label5Click(Sender: TObject);
    procedure Label8Click(Sender: TObject);
    procedure DBGrid1ColExit(Sender: TObject);
    procedure FormActivate(Sender: TObject);
    procedure totalizarExecute(Sender: TObject);
    procedure preencherExecute(Sender: TObject);
    procedure FormKeyPress(Sender: TObject; var Key: Char);
    procedure DBGrid1Enter(Sender: TObject);
    procedure DBGrid1Exit(Sender: TObject);
    procedure RadioButton1Click(Sender: TObject);
    procedure RadioButton2Click(Sender: TObject);
    procedure MaskEdit1KeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure MaskEdit2KeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure PageControl1Change(Sender: TObject);
    procedure SpeedButton9Click(Sender: TObject);
    procedure totalizar1Execute(Sender: TObject);
    procedure DBRadioGroup1Exit(Sender: TObject);
    procedure SpeedButton8Click(Sender: TObject);
    procedure novoExecute(Sender: TObject);
    procedure avancarExecute(Sender: TObject);
    procedure voltarExecute(Sender: TObject);
    procedure DBEdit1KeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure DBEdit6KeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure DBEdit4KeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure DBEdit8KeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure excluirExecute(Sender: TObject);
    procedure camposExecute(Sender: TObject);
    procedure contaExecute(Sender: TObject);
    procedure DBLookupComboBox1Click(Sender: TObject);
    procedure focoExecute(Sender: TObject);
    procedure estoqueExecute(Sender: TObject);
    procedure preencherfornecedorExecute(Sender: TObject);
    procedure fimagemExecute(Sender: TObject);
    procedure IMAGE1KeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure DBLookupComboBox2Click(Sender: TObject);
    procedure DBLookupComboBox3Click(Sender: TObject);
    procedure ComboBox1DropDown(Sender: TObject);
    procedure ComboBox2DropDown(Sender: TObject);
    procedure ComboBox3DropDown(Sender: TObject);
    procedure ComboBox1Change(Sender: TObject);
    procedure ComboBox2Change(Sender: TObject);
    procedure ComboBox3Change(Sender: TObject);
    procedure ComboBox1Enter(Sender: TObject);
    procedure ComboBox2Enter(Sender: TObject);
    procedure ComboBox3Enter(Sender: TObject);
    procedure btndeleteClick(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
    procedure formatarExecute(Sender: TObject);
    procedure DBEdit8Exit(Sender: TObject);
    procedure SpeedButton3Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure EditCodigoExit(Sender: TObject);
    procedure ajudaExecute(Sender: TObject);
  private
    procedure AppHint(Sender : TObject);
    { Private declarations }
  public
  BOK : boolean;
  ST,tipo, loja, foc: String;
  it:integer;
    { Public declarations }
  end;

var
  fentrada: Tfentrada;

implementation

uses UnitRelatorioEntrada, ulistafornecedor, UnitMenu, ulistaproduto,
  UnitFornecedor, UnitProduto, udm;





procedure tfentrada.AppHint(Sender: TObject);
begin
  StatusBar1.Panels[0].Text := Application.Hint;
end;
{$R *.DFM}

procedure Tfentrada.FormClose(Sender: TObject;
  var Action: TCloseAction);
begin



	        Application.OnHint := nil;

        fdm.tbentrada.close;
        fdm.tbentradaitem.close;
        fdm.tbfatura.close;
end;

procedure Tfentrada.EditCodigoKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin


        if key = VK_F3 then
         Label6Click(Self);

        if key = vk_F12 then begin
         Application.CreateForm (Tflistafornecedor, flistafornecedor);
          fdm.tbfornecedor.open;
           flistafornecedor.st :='entrada';
            flistafornecedor.show;
             end;

          if key = 13 then
           preencherfornecedorexecute(self);

end;

procedure Tfentrada.DBGrid1KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
        if key = vk_F12 then begin
         Application.CreateForm (Tflistaproduto, flistaproduto);
          flistaproduto.st :='entrada';
           flistaproduto.table1.open;
            flistaproduto.showmodal;
             
             end;

        if key = vk_F4 then
        if image1.Visible = true then
         image1.Hide
        else
         fimagemexecute(self);

         if key = 13 then
          dbgrid1.selectedindex := dbgrid1.selectedindex + 1
          else if key = 27 then begin
          fdm.tbentradaitem.edit;
          fdm.tbentradaitem.post;
         dbgrid1.selectedindex := dbgrid1.selectedindex - 1;
         end;

        if dbgrid1.SelectedIndex in [3,4] then
        if (key =38) or (key = 40) then
         fdm.tbentradaitem.cancel;
end;

procedure Tfentrada.SpeedButton1Click(Sender: TObject);
begin
        novoexecute(self);
end;

procedure Tfentrada.SpeedButton2Click(Sender: TObject);
begin
        fdm.tbentrada.edit;
         fdm.tbentrada.post;
          btnGravar.Enabled:=false;
           btncancelar.enabled := false;
end;

procedure Tfentrada.btnPrimeiroClick(Sender: TObject);
begin
        fdm.tbentrada.first;
end;

procedure Tfentrada.btnVoltarClick(Sender: TObject);
begin
        fdm.tbentrada.prior;
end;

procedure Tfentrada.btnAvancarClick(Sender: TObject);
begin
        fdm.tbentrada.Next;
end;

procedure Tfentrada.btnUltimoClick(Sender: TObject);
begin
        fdm.tbentrada.last;
end;

procedure Tfentrada.btncancelarClick(Sender: TObject);
begin
        fdm.tbentrada.cancel;
          btnGravar.Enabled:=false;
           btncancelar.enabled := false;
end;

procedure Tfentrada.Label2Click(Sender: TObject);
begin
        BOK := inputquery('Localizar Entrada','Entre com o número da entrada:',ST);
         if BOK then
          if not fdm.tbentrada.Locate ('entrada',ST,[]) then
           ShowMessage ('Entrada não localizada !!!');
            ST := '';
end;

procedure Tfentrada.Label6Click(Sender: TObject);
begin
        BOK := inputquery('Localizar Código de Fornecedor','Entre com o código do fornecedor:',ST);
         if BOK then
          if not fdm.tbentrada.Locate ('Codigo',ST,[]) then
           ShowMessage ('Código não localizado !!!');
            ST := '';
end;

procedure Tfentrada.Label7Click(Sender: TObject);
begin
        BOK := inputquery('Localizar Nota','Entre com o número da nota:',ST);
         if BOK then
          if not fdm.tbentrada.Locate ('nota',ST,[]) then
           ShowMessage ('Nota não localizada !!!');
            ST := '';
end;

procedure Tfentrada.Label5Click(Sender: TObject);
begin
        BOK := inputquery('Localizar Pedido','Entre com o nº do pedido:',ST);
         if BOK then
          if not fdm.tbentrada.Locate ('pedido',ST,[]) then
           ShowMessage ('Pedido não encontrado !!!');
            ST := '';
end;

procedure Tfentrada.Label8Click(Sender: TObject);
begin
        BOK := inputquery('Localizar Nome Fantasia','Entre com o nome fantasia do fornecedor:',ST);
         if BOK then
          if not fdm.tbentrada.Locate ('fantasia',Uppercase(ST),[]) then
           ShowMessage ('Nome não localizado !!!');
            ST := '';
end;

procedure Tfentrada.DBGrid1ColExit(Sender: TObject);
begin



     if dbgrid1.selectedindex = 0 then
      preencherexecute (self);

          if dbgrid1.selectedindex = 0 then begin
          fdm.tbentradaitem.edit;
          dbgrid1.Columns[1].Field.text := uppercase(dbgrid1.Columns[1].Field.text);
          end;

     if dbgrid1.selectedindex in [3,4] then
      totalizarexecute(self);

end;

procedure Tfentrada.FormActivate(Sender: TObject);
begin

   if pagecontrol1.ActivePageIndex = 0 then


end;

procedure Tfentrada.totalizarExecute(Sender: TObject);
var
tot : real;
bookmark : tbookmarkstr;
begin

     fdm.tbentradaitem.edit;
     fdm.tbentradaitem.fields[10].asfloat := fdm.tbentradaitem.fields[8].asfloat * fdm.tbentradaitem.fields[9].asfloat;

     bookmark := fdm.tbentradaitem.Bookmark;

     try
      fdm.tbentradaitem.DisableControls;
      tot := 0;

    try
    fdm.tbentradaitem.First;

    while not fdm.tbentradaitem.Eof do begin

    tot := tot + fdm.tbentradaitem.fields[10].asfloat;
    fdm.tbentradaitem.next;
    end;
    finally

    fdm.tbentradaitem.EnableControls;
    end;
    finally
    fdm.tbentradaitem.Bookmark := bookmark;
    end;

    fdm.tbentrada.edit;
    fdm.tbentrada['total'] := tot;
    fdm.tbentrada.post;

end;

procedure Tfentrada.preencherExecute(Sender: TObject);
var
  prod:string;
begin

       if fdm.tbproduto.Locate('codigo',fdm.tbentradaitem['codigo'],[]) then begin

        if fdm.tbproduto['produto'] <> null then prod := fdm.tbproduto['produto'];
         if fdm.tbproduto['descricao'] <> null then prod := prod + ' ' + fdm.tbproduto['descricao'];


        fdm.tbentradaitem.edit;

     fdm.tbentradaitem['nome'] :=  prod;

         fdm.tbentradaitem['vrunit'] := fdm.tbproduto['vrunit'];
         fdm.tbentradaitem['un'] := fdm.tbproduto['un'];
          dbgrid1.selectedindex := 3;
           end else begin
        beep;
        showmessage('Este produto não foi localizado!!!');
        dbgrid1.selectedindex := 0 ;
        end;
end;

procedure Tfentrada.FormKeyPress(Sender: TObject; var Key: Char);
begin
 if key=#13 then begin
  Key := #0;
       Perform(WM_nextdlgctl,0,0)
 end else if Key = #27 then
   Perform(WM_nextdlgctl,1,0);
end;

procedure Tfentrada.DBGrid1Enter(Sender: TObject);
begin


        if (dbedit1.text = '') or
        (dbedit6.text = '' )or
        (fdm.tbentrada['fantasia'] = null) then begin
        showmessage('primeiramente, preencha os campos acima!!!');
        dbedit6.setfocus;
     end else begin

        keypreview := false;
        SpeedButton2Click(self);
        dbgrid1.SelectedIndex := 0;
        foc:='1';
        end;
end;

procedure Tfentrada.DBGrid1Exit(Sender: TObject);
begin
        keypreview := true;
        foc := '0';
end;

procedure Tfentrada.RadioButton1Click(Sender: TObject);
begin
        fdm.tbentradaitem.Filtered := false;

        if (maskedit1.text <>'  /  /    ') and (maskedit2.text <>'  /  /    ') then
        fdm.tbentradaitem.filter := 'operacao = ''E'' and data >=''' + maskedit1.text + ''' and data<=''' +  maskedit2.text + ''''
        else
        fdm.tbentradaitem.filter := 'operacao = ''E''';
        fdm.tbentradaitem.filtered := true;
        tipo := 'E';
        totalizar1execute(self);
end;

procedure Tfentrada.RadioButton2Click(Sender: TObject);
begin
        fdm.tbentradaitem.Filtered := false;

        if (maskedit1.text <>'  /  /    ') and (maskedit2.text <>'  /  /    ') then
        fdm.tbentradaitem.filter := 'operacao = ''D'' and data >=''' + maskedit1.text + ''' and data<=''' +  maskedit2.text + ''''
        else
        fdm.tbentradaitem.filter := 'operacao = ''D''';
        fdm.tbentradaitem.filtered := true;
        tipo := 'D';
        totalizar1execute(self);
end;

procedure Tfentrada.MaskEdit1KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
        if key = 13 then
         maskedit2.setfocus;
end;

procedure Tfentrada.MaskEdit2KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
        if key = 13 then begin
        fdm.tbentradaitem.Filtered := false;

        

        if radiobutton3.Checked = false then begin
        if (maskedit1.text <>'  /  /    ') and (maskedit2.text <>'  /  /    ') then
        fdm.tbentradaitem.filter := 'operacao = ''' + tipo + ''' and data >=''' + maskedit1.text + ''' and data<=''' +  maskedit2.text + ''''
        else
        fdm.tbentradaitem.filter := 'operacao = ''' + tipo + '''';
        end;

        if radiobutton3.Checked = true then
        if (maskedit1.text <>'  /  /    ') and (maskedit2.text <>'  /  /    ') then
        fdm.tbentradaitem.filter := 'data >=''' + maskedit1.text + ''' and data<=''' +  maskedit2.text + '''';

        fdm.tbentradaitem.filtered := true;
        totalizar1execute(self);
        end;
end;

procedure Tfentrada.PageControl1Change(Sender: TObject);
begin
        fdm.tbentradaitem.filtered := false;

        if pagecontrol1.ActivePageIndex = 0 then begin
         fdm.tbentradaitem.MasterFields := 'entrada';
           keypreview := true;

        end else begin
        fdm.tbentradaitem.MasterFields := '';
        SpeedButton2Click(self);
        fdm.tbentradaitem.filter := 'operacao = ''E''';
        fdm.tbentradaitem.filtered := true;
        totalizar1execute(self);
        keypreview := false;
        tipo := 'E';
        radiobutton1.Checked := true;

  THackDBGrid(DBGrid2).FixedCols := 10;
        end;

end;

procedure Tfentrada.SpeedButton9Click(Sender: TObject);
begin
         maskedit1.clear;
         maskedit2.clear;

        fdm.tbentradaitem.Filtered := false;
        radiobutton3.Checked := true;
        tipo := 'T';
        
        totalizar1execute(self);

end;

procedure Tfentrada.totalizar1Execute(Sender: TObject);
var
tot : real;
bookmark : tbookmarkstr;
begin

     bookmark := fdm.tbentradaitem.Bookmark;

     try
      fdm.tbentradaitem.DisableControls;
      tot := 0;

    try
    fdm.tbentradaitem.First;

    while not fdm.tbentradaitem.Eof do begin
    if fdm.tbentradaitem['total'] <> null then
    tot := tot + fdm.tbentradaitem.fields[10].asfloat;
    fdm.tbentradaitem.next;
    end;
    finally

    fdm.tbentradaitem.EnableControls;
    end;
    finally
    fdm.tbentradaitem.Bookmark := bookmark;
    end;

        panel13.caption := 'Total: ' + format('%n', [tot]);


end;

procedure Tfentrada.DBRadioGroup1Exit(Sender: TObject);

begin


      fdm.tbentradaitem.DisableControls;

    fdm.tbentradaitem.First;

    while not fdm.tbentradaitem.Eof do begin
    fdm.tbentradaitem.edit;
    fdm.tbentradaitem['operacao'] := fdm.tbentrada['natureza'];
    fdm.tbentradaitem.post;
    fdm.tbentradaitem.next;
    end;

    fdm.tbentradaitem.EnableControls;



end;

procedure Tfentrada.SpeedButton8Click(Sender: TObject);
var
bookmark :TBookmarkstr;

begin

     bookmark := fdm.tbentrada.Bookmark;

      fdm.tbentrada.Filter := 'entrada = ''' + dbedit1.text + '''';
       fdm.tbentrada.Filtered := true;

        Application.CreateForm(tfrentrada, frentrada);

  fmenu.logotipoExecute(self);

  if fileexists (extractfilepath(paramstr(0)) + '\imagem\logo.bmp') then begin
  frentrada.image1.Picture.assign(clipboard);
  clipboard.clear;
  end;
  if fileexists (extractfilepath(paramstr(0)) + '\imagem\dado.txt') then
   frentrada.memo1.lines.loadfromfile (extractfilepath(paramstr(0)) + '\imagem\dado.txt');

         if fdm.tbentrada['natureza'] = 'D' then
          frentrada.ldevolucao.Caption := '( devolução ) '
         else
          frentrada.ldevolucao.Caption := '';

          frentrada.quickentrada.previewmodal;
           frentrada.Release;
            fdm.tbentrada.Filtered := false;
              fdm.tbentrada.Bookmark := bookmark;
end;

procedure Tfentrada.novoExecute(Sender: TObject);
begin
        if foc = '1' then begin
         fdm.tbentradaitem.Insert;
          dbgrid1.SelectedIndex := 0;

       end else begin

        btnGravar.Enabled:=true;
        btncancelar.Enabled := true;
       fdm.tbentrada.Refresh;

        with fdm.query1 do begin
         close;
          sql.clear;
           sql.add('select max(entrada) as codigo from tbentrada');
            open;
         end;

        fdm.tbentrada.insert;
        if fdm.query1['codigo'] <> null then
         fdm.tbentrada['entrada'] := fdm.query1['codigo'] + 1
        else
        fdm.tbentrada['entrada']:='1';
        fdm.tbentrada['natureza']:='E';
        fdm.tbentrada['data']:=DateTostr(now);
        dbedit6.setfocus;
        fdm.query1.close;
        end;

end;

procedure Tfentrada.avancarExecute(Sender: TObject);
begin

        fdm.tbentradaitem.Filtered := false;

        if (maskedit1.text <>'  /  /    ') and (maskedit2.text <>'  /  /    ') then begin
        fdm.tbentradaitem.filter := 'data >=''' + maskedit1.text + ''' and data<=''' +  maskedit2.text + '''';
        fdm.tbentradaitem.filtered := true;
        end else
        fdm.tbentradaitem.filtered := false;
        tipo := 'T';
        totalizar1execute(self);


end;

procedure Tfentrada.voltarExecute(Sender: TObject);
begin
        fdm.tbentrada.prior;
end;

procedure Tfentrada.DBEdit1KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
        if key = VK_F3 then
         Label2Click(Self);
end;

procedure Tfentrada.DBEdit6KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
        if key = VK_F3 then
         Label7Click(Self);
end;

procedure Tfentrada.DBEdit4KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
        if key = VK_F3 then
         Label5Click(Self);
end;

procedure Tfentrada.DBEdit8KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
        if key = VK_F3 then
         Label8Click(Self);
end;

procedure Tfentrada.excluirExecute(Sender: TObject);
var
 doc:string;

begin

        doc := fdm.tbentrada['nota'];

        fdm.tbpagar.Filter:='docparcela = ''' + doc +'''';
         fdm.tbpagar.Filtered := true;

       fdm.tbpagar.Last;

       while fdm.tbpagar['docparcela'] <> null do begin
        fdm.tbpagar.delete;
         fdm.tbpagar.next;
           end;

        fdm.tbpagar.Filtered := false;

end;

procedure Tfentrada.camposExecute(Sender: TObject);
begin

        fdm.tbpagar['dataemissao'] := fdm.tbentrada['data'];
        fdm.tbpagar['docparcela'] := fdm.tbentrada['nota'];
        fdm.tbpagar['codigo'] := fdm.tbentrada['codigo'];
        fdm.tbpagar['fantasia'] := fdm.tbentrada['fantasia'];
        fdm.tbpagar['nome'] := fdm.tbentrada['nome'];
        fdm.tbpagar['numeropedido'] := fdm.tbentrada['pedido'];
        fdm.tbpagar['valortitulo'] := fdm.tbentrada['total'];
        fdm.tbpagar['valordocumento'] := (fdm.tbentrada['total']/fdm.tbfatura['parcelas']);
        fdm.tbpagar['vrdesconto'] := (fdm.tbentrada['total']/fdm.tbfatura['parcelas']);
       // tbpagar['loja'] := loja;
        fdm.tbpagar.post;
end;

procedure Tfentrada.contaExecute(Sender: TObject);
var
 IT, qt : Integer;

begin

    if (fdm.tbfatura['descricao']= 'À VISTA') or (fdm.tbfatura['descricao']= 'APRES.') then begin
     fdm.tbpagar.insert;
      fdm.tbpagar['venc1'] := fdm.tbfatura['DESCRICAO'];
       camposexecute(self);

        end else begin


     it :=fdm.tbfatura['parcelas'];

   if it = 1 then begin
    fdm.tbpagar.insert;
     fdm.tbpagar['datavencimento'] := (fdm.tbentrada['data'] + fdm.tbfatura['Cond.Pgto1']);
       camposexecute(self);

       end else begin


     qt := 0;

    While qt < it do Begin

    fdm.tbpagar.insert;

    if qt = 0 then begin
    fdm.tbpagar['datavencimento'] := (fdm.tbentrada['data'] + fdm.tbfatura['Cond.Pgto1']);
    fdm.tbpagar['letra'] := 'A';

    end else if qt = 1 then begin
    fdm.tbpagar['datavencimento'] := (fdm.tbentrada['data'] + fdm.tbfatura['Cond.Pgto2']);
    fdm.tbpagar['letra'] := 'B';

    end else if qt = 2 then begin
    fdm.tbpagar['datavencimento'] := (fdm.tbentrada['data'] + fdm.tbfatura['Cond.Pgto3']);
    fdm.tbpagar['letra'] := 'C';


    end else if qt = 3 then begin
    fdm.tbpagar['datavencimento'] := (fdm.tbentrada['data'] + fdm.tbfatura['Cond.Pgto4']);
    fdm.tbpagar['letra'] := 'D';

    end else if qt = 4 then begin
    fdm.tbpagar['datavencimento'] := (fdm.tbentrada['data'] + fdm.tbfatura['Cond.Pgto5']);
    fdm.tbpagar['letra'] := 'E';

    end else if qt = 5 then begin
    fdm.tbpagar['datavencimento'] := (fdm.tbentrada['data'] + fdm.tbfatura['Cond.Pgto6']);
    fdm.tbpagar['letra'] := 'F';
    end;

    camposexecute(self);

    qt := qt  + 1 ;

    end;
    end;
    end;

end;

procedure Tfentrada.DBLookupComboBox1Click(Sender: TObject);
begin
    if fdm.tbentrada['total']= null then begin
    showmessage('Não há valor para esta entrada, verificar!!!');
    fdm.tbentrada.edit;
    fdm.tbentrada['Condfatura'] := null;
    abort;
    end;


     fdm.tbpagar.open;
     if fdm.tbpagar.Locate ('docparcela',dbedit6.text,[]) then begin
      if application.MessageBox('Já foi gerado conta (s) desta entrada, deseja subscrever?','Gerar Conta',4 + MB_ICONWARNING) = mryes then begin
        excluirexecute(self);
         contaexecute(self);
          end;
      end else

      if application.MessageBox('Tem certeza que deseja gerar conta(s) a pagar?','Gerar Conta',4 + MB_ICONWARNING) = mryes then begin
        excluirexecute(self);
         contaexecute(self);
          end;

      fdm.tbpagar.close;

end;

procedure Tfentrada.focoExecute(Sender: TObject);
begin

        if image1.Visible= true then begin
         if dbgrid1.Focused = true then
          image1.SetFocus
         else
         dbgrid1.SetFocus;
        end else begin

        it := it + 1;

        if it = 3 then it:=1;

        case it of

        1: dbedit1.setfocus;
        2: dbgrid1.setfocus;
        end;
        end;

end;
procedure Tfentrada.estoqueExecute(Sender: TObject);
var
tot, tot1: real;
begin
       if dbgrid1.Focused = true then begin

        with fdm.Query1 do begin
         close;
          sql.clear;
           sql.add ('select codigo, nome, sum(qtd)as entrada from tbentradaitem');
            sql.add (' where codigo = "'+ dbgrid1.columns[0].field.text + '" group by codigo, nome');
            open;
        end;

        with fdm.Query2 do begin
         close;
          sql.clear;
           sql.add ('select codigo, nome, sum(qtd) as saida from tbpedidoitem');
            sql.add (' where codigo = "'+ dbgrid1.columns[0].field.text + '" group by codigo, nome');
            open;
        end;

        fdm.tbproduto.Open;


        if fdm.tbproduto.Locate('codigo',fdm.query1['codigo'],[]) then
        tot1:= fdm.tbproduto.FieldByName('minimo').asfloat
        else
        tot1 := 0;

        FDM.tbproduto.close;


        tot := (fdm.query1.fields[2].asfloat - fdm.query2.fields[2].asfloat);

        if fdm.query1['nome'] <> null then
            showmessage('ESTOQUE = ' + floattostr(tot) + ' ' + fdm.query1['nome']+#13+
            'ESTOQUE MÍNIMO = '+ floattostr(tot1))
        else
        showmessage('Estoque Vazio!!!');
end;

        FDM.Query1.close;
        fdm.Query2.Close;

end;

procedure Tfentrada.preencherfornecedorExecute(Sender: TObject);
begin

                 fdm.tbfornecedor.Open;

               if fdm.tbfornecedor.Locate ('codigo',editcodigo.text,[]) then begin

               fdm.tbentrada.edit;
              fdm.tbentrada['fantasia'] := fdm.tbfornecedor['fantasia'];
             fdm.tbentrada['nome'] := fdm.tbfornecedor['fornecedor'];
            fdm.tbentrada['cgc'] := fdm.tbfornecedor['cgc'];
           fdm.tbentrada['fone'] := fdm.tbfornecedor['fone'];
          dbgrid1.setfocus;
         dbgrid1.selectedindex := 0;

          end else begin
          Showmessage('Não há nenhum fornecedor código: ' +  EditCodigo.text +' cadastrado !!!');
           editcodigo.setfocus;
            end;

       fdm.tbfornecedor.Close;


end;

procedure Tfentrada.fimagemExecute(Sender: TObject);
 var
  pt : String;
begin

     fdm.tbproduto.open;
     fdm.tbproduto.Locate('codigo',fdm.tbentradaitem['codigo'],[]);

      if fdm.tbproduto['imagem'] <> null then begin
       pt := fdm.tbproduto['imagem'] ;
       if fileexists (pt) then
        image1.Picture.LoadFromFile (pt);
        end else
      image1.Picture.LoadFromFile(extractfilepath(paramstr(0)) + '\imagem\imagem.wmf');
     image1.show;
end;

procedure Tfentrada.IMAGE1KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
       if image1.Width < 430 then begin
        if key = 107 then begin
         image1.width := image1.width + 10;
          image1.height := image1.height + 10;
           image1.left := image1.left - 5;
            image1.top := image1.top - 5;
           end;
           end;

        if image1.Width > 120 then begin
        if key = 109 then begin
         image1.width := image1.width - 10;
          image1.height := image1.height - 10;
           image1.left := image1.left + 5;
            image1.top := image1.top + 5;
             end;
              end;

        if key = 27 then begin
         image1.Hide;
          dbgrid1.setfocus;
           end;

end;

procedure Tfentrada.DBLookupComboBox2Click(Sender: TObject);
begin
      if fdm.tbentradaitem['Fantasia'] <> null Then
       ST:= fdm.tbentradaitem['Fantasia'];

        BOK:= InputQuery ('Filtrar', 'Entre com o nome do fornecedor', St);
      if BOK then begin

        fdm.tbentradaitem.Filtered := false;

        if (maskedit1.text <>'  /  /    ') and (maskedit2.text <>'  /  /    ') then
        fdm.tbentradaitem.filter := 'operacao = ''' + tipo + ''' and data >=''' + maskedit1.text + ''' and data<=''' +  maskedit2.text + '''  and fantasia = ''' + UpperCase(st) + ''''
        else
        fdm.tbentradaitem.filter := 'operacao = ''' + tipo + ''' and fantasia = ''' + UpperCase(st) + '''';
        fdm.tbentradaitem.filtered := true;
        totalizar1execute(self);
        end;

end;

procedure Tfentrada.DBLookupComboBox3Click(Sender: TObject);
begin
      if fdm.tbentradaitem['codigo'] <> null Then
       ST:= fdm.tbentradaitem['codigo'];

        BOK:= InputQuery ('Filtrar', 'Entre com o código do produto',st);
      if BOK then begin

        fdm.tbentradaitem.Filtered := false;

        if (maskedit1.text <>'  /  /    ') and (maskedit2.text <>'  /  /    ') then
        fdm.tbentradaitem.filter := 'operacao = ''' + tipo + ''' and data >=''' + maskedit1.text + ''' and data<=''' +  maskedit2.text + '''  and codigo = ''' + UpperCase(st) + ''''
        else
        fdm.tbentradaitem.filter := 'operacao = ''' + tipo + ''' and codigo = ''' + UpperCase(st) + '''';
        fdm.tbentradaitem.filtered := true;

        totalizar1execute(self);
        end;

end;

procedure Tfentrada.ComboBox1DropDown(Sender: TObject);
begin
        with fdm.Query1 do begin
         close;
          sql.Clear;
           sql.add ('select distinct fantasia from tbentradaitem order by fantasia');
            open;
             end;

        ComboBox1.items.Clear;

      fdm.Query1.First;
      while not fdm.Query1.Eof do begin
      if fdm.Query1['fantasia'] <> null then
      combobox1.Items.Add (fdm.Query1['fantasia']);
      fdm.query1.Next;
      end;

      fdm.Query1.Close;
end;

procedure Tfentrada.ComboBox2DropDown(Sender: TObject);
begin
        with fdm.Query1 do begin
         close;
          sql.Clear;
           sql.add ('select distinct nome from tbentradaitem order by nome');
            open;
             end;

        ComboBox2.items.Clear;

      fdm.Query1.First;
      while not fdm.Query1.Eof do begin
      if fdm.Query1['nome'] <> null then
      combobox2.Items.Add (fdm.Query1['nome']);
      fdm.query1.Next;
      end;

      fdm.Query1.Close;
end;

procedure Tfentrada.ComboBox3DropDown(Sender: TObject);
begin
        with fdm.Query1 do begin
         close;
          sql.Clear;
           sql.add ('select distinct CODIGO from tbentradaitem order by CODIGO');
            open;
             end;

        ComboBox3.items.Clear;

      fdm.query1.First;
      while not fdm.Query1.Eof do begin
      if fdm.Query1['codigo'] <> null then
      combobox3.Items.Add (fdm.Query1['codigo']);
      fdm.query1.Next;
      end;

      fdm.Query1.Close;

end;

procedure Tfentrada.ComboBox1Change(Sender: TObject);
begin
        fdm.tbentradaitem.Filtered := false;

        if (maskedit1.text <>'  /  /    ') and (maskedit2.text <>'  /  /    ') then
        fdm.tbentradaitem.filter := 'operacao = ''' + tipo + ''' and data >=''' + maskedit1.text + ''' and data<=''' +  maskedit2.text + ''' and fantasia=''' +  combobox1.text + ''''
        else
        fdm.tbentradaitem.filter := 'operacao = ''' + tipo + ''' and fantasia=''' +  uppercase (combobox1.text) + '''';
        fdm.tbentradaitem.filtered := true;
        totalizar1execute(self);
end;

procedure Tfentrada.ComboBox2Change(Sender: TObject);
begin
        fdm.tbentradaitem.Filtered := false;

        if (maskedit1.text <>'  /  /    ') and (maskedit2.text <>'  /  /    ') then
                fdm.tbentradaitem.filter := 'operacao = ''' + tipo + ''' and data >=''' + maskedit1.text + ''' and data<=''' +  maskedit2.text + ''' and nome=''' +  combobox2.text + ''''
        else
        fdm.tbentradaitem.filter := 'operacao = ''' + tipo + ''' and nome=''' +  uppercase(combobox2.text) + '''';
        fdm.tbentradaitem.filtered := true;
        totalizar1execute(self);
end;

procedure Tfentrada.ComboBox3Change(Sender: TObject);
begin
        fdm.tbentradaitem.Filtered := false;

        if (maskedit1.text <>'  /  /    ') and (maskedit2.text <>'  /  /    ') then
        fdm.tbentradaitem.filter := 'operacao = ''' + tipo + ''' and data >=''' + maskedit1.text + ''' and data<=''' +  maskedit2.text + ''' and codigo=''' +  combobox3.text + ''''
        else
        fdm.tbentradaitem.filter := 'operacao = ''' + tipo + ''' and codigo=''' +  combobox3.text + '''';
        fdm.tbentradaitem.filtered := true;
        totalizar1execute(self);
end;

procedure Tfentrada.ComboBox1Enter(Sender: TObject);
begin
        combobox2.clear;
         combobox3.clear;
end;

procedure Tfentrada.ComboBox2Enter(Sender: TObject);
begin
        combobox1.clear;
         combobox3.clear;
end;

procedure Tfentrada.ComboBox3Enter(Sender: TObject);
begin
        combobox2.clear;
         combobox1.clear;
end;

procedure Tfentrada.btndeleteClick(Sender: TObject);
begin
    if Application.MessageBox('Deseja apagar enta entrada?','Deletar',4 + MB_ICONQUESTION) = mrYes then begin

        fdm.tbentradaitem.Last;

        while not fdm.tbentradaitem.Bof do begin
         fdm.tbentradaitem.delete;
          fdm.tbentradaitem.prior;
           end;

         if fdm.tbentradaitem['codigo'] <> null then
          fdm.tbentradaitem.delete;

           fdm.tbentrada.delete;

         end;
end;

procedure Tfentrada.FormShow(Sender: TObject);
begin
        fdm.tbentrada.Last;
end;

procedure Tfentrada.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
        IF btngravar.Enabled = true then begin
         case application.MessageBox('Deseja salvar as alterações?', 'Sair de Cadastro de Cliente',mb_yesnocancel + MB_ICONQUESTION )of

         idyes : begin
         fdm.tbentrada.edit;
          fdm.tbentrada.post;
           fdm.tbentradaitem.edit;
            fdm.tbentradaitem.post;
             canclose:=true;
              end;

         idno : begin
          fdm.tbentrada.cancel;
           fdm.tbentradaitem.cancel;
            canclose:=true;
             end;

         idcancel :
           canclose:=false;
end;
end;

end;

procedure Tfentrada.formatarExecute(Sender: TObject);
begin

 (fdm.tbentrada.fieldbyname ('entrada') as tfloatfield).displayformat := '000000';
 (fdm.tbentrada.fieldbyname ('data') as tdatetimefield).editmask := '99/99/9999';
 (fdm.tbentrada.fieldbyname ('pedido') as tfloatfield).displayformat := '000000';
 (fdm.tbentrada.fieldbyname ('total') as tfloatfield).displayformat := '###,##0.00';
 (fdm.tbentrada.fieldbyname ('nota') as tfloatfield).displayformat := '000000';
 (fdm.tbentrada.fieldbyname ('codigo') as tfloatfield).displayformat := '000000';

 (fdm.tbentradaitem.fieldbyname ('codigo') as tfloatfield).displayformat := '000000';
 (fdm.tbentradaitem.fieldbyname ('vrunit') as tfloatfield).displayformat := '###,##0.00';
 (fdm.tbentradaitem.fieldbyname ('total') as tfloatfield).displayformat := '###,##0.00';
 (fdm.tbentradaitem.fieldbyname ('qtd') as tfloatfield).displayformat := '00';

end;

procedure Tfentrada.DBEdit8Exit(Sender: TObject);
begin
        fdm.tbentradaitem.DisableControls;
        fdm.tbentradaitem.First;

        while not fdm.tbentradaitem.Eof do begin
        fdm.tbentradaitem.Edit;
        fdm.tbentradaitem['nota']:= dbedit6.text;
        fdm.tbentradaitem['fantasia']:= fdm.tbentrada['fantasia'];
        fdm.tbentradaitem['operacao']:= fdm.tbentrada['natureza'];
        fdm.tbentradaitem.Next;
        end;

        fdm.tbentradaitem.EnableControls;

end;

procedure Tfentrada.SpeedButton3Click(Sender: TObject);
var
st:string;
begin

        Application.CreateForm(tfrentrada, frentrada);

        fmenu.logotipoExecute(self);

        st:='C';

        if inputquery ('Opções de impressão','- Digite "C" para imprimir a consulta normal:' + #13 + '- Digite "F" para imprimir por fornecedor:', st) then


          if uppercase(st) ='C' then  begin

  if fileexists (extractfilepath(paramstr(0)) + '\imagem\logo.bmp') then begin
  frentrada.image2.Picture.assign(clipboard);
  clipboard.clear;
  end;

  if fileexists (extractfilepath(paramstr(0)) + '\imagem\dado.txt') then
   frentrada.memo2.lines.loadfromfile (extractfilepath(paramstr(0)) + '\imagem\dado.txt');
    frentrada.ltotallista.caption :=  panel13.caption;
     frentrada.quickLISTA.previewmodal;
      end;



          if uppercase(st) ='F' then  begin

  if fileexists (extractfilepath(paramstr(0)) + '\imagem\logo.bmp') then begin
  frentrada.image3.Picture.assign(clipboard);
  clipboard.clear;
  end;

  if fileexists (extractfilepath(paramstr(0)) + '\imagem\dado.txt') then
   frentrada.memo3.lines.loadfromfile (extractfilepath(paramstr(0)) + '\imagem\dado.txt');
    frentrada.ltotallista.caption :=  panel13.caption;
     fdm.tbentradaitem.IndexFieldNames := 'fantasia;codigo';
      frentrada.quickfornecedor.previewmodal;
       end;

   frentrada.Release;
   fdm.tbentradaitem.Indexname:= 'bylink';
end;

procedure Tfentrada.FormCreate(Sender: TObject);
begin
        Application.OnHint := AppHint;
end;

procedure Tfentrada.EditCodigoExit(Sender: TObject);
begin
        fdm.tbentradaitem.DisableControls;
        fdm.tbentradaitem.First;

        while not fdm.tbentradaitem.Eof do begin
        fdm.tbentradaitem.Edit;
        fdm.tbentradaitem['fantasia'] := fdm.tbentrada['fantasia'];
        fdm.tbentradaitem.Next;
        end;

        fdm.tbentradaitem.EnableControls;

end;

procedure Tfentrada.ajudaExecute(Sender: TObject);
var
  Comp: Trichedit; // * variável Comp da classe TMemo
  texto : string;
begin
  Comp := Trichedit.Create (Self);  // * cria o componente Memo
  Comp.Parent := Self;    // * exibe o componente criado

  if fileexists (extractfilepath(paramstr(0)) + '\ajuda\ajudaentrada.txt') then
   comp.lines.loadfromfile (extractfilepath(paramstr(0)) + '\ajuda\ajudaentrada.txt');

  texto := comp.Text;
  comp.Destroy;

  Showmessage (texto);


end;

end.
