unit UNota;

interface

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

type

  Tfnota = class(TForm)
    DSNota: TDataSource;
    dsitem: TDataSource;
    ActionList1: TActionList;
    Formatar: TAction;
    Totalizar: TAction;
    PProduto: TAction;
    FormProduto: TAction;
    PCliente: TAction;
    Novo: TAction;
    avancar: TAction;
    voltar: TAction;
    foco: TAction;
    excluir: TAction;
    conta: TAction;
    campos: TAction;
    formatar1: TAction;
    totalizar1: TAction;
    estoque: TAction;
    ScrollBox1: TScrollBox;
    Panel1: TPanel;
    Panel3: TPanel;
    ToolBar1: TToolBar;
    btnPrimeiro: TSpeedButton;
    btnVoltar: TSpeedButton;
    btnAvancar: TSpeedButton;
    btnUltimo: TSpeedButton;
    Panel10: TPanel;
    Panel7: TPanel;
    btnnovo: TSpeedButton;
    Panel12: TPanel;
    btngravar: TSpeedButton;
    Panel13: TPanel;
    btncancelar: TSpeedButton;
    Panel8: TPanel;
    Panel17: TPanel;
    Panel11: TPanel;
    SpeedButton8: TSpeedButton;
    Panel14: TPanel;
    btndelete: TSpeedButton;
    GroupBox3: TGroupBox;
    Label6: TLabel;
    Label7: TLabel;
    Label29: TLabel;
    Label30: TLabel;
    Label31: TLabel;
    Label38: TLabel;
    VencA: TDBEdit;
    ValorA: TDBEdit;
    VencB: TDBEdit;
    ValorB: TDBEdit;
    VencC: TDBEdit;
    ValorC: TDBEdit;
    Panel2: TPanel;
    Panel5: TPanel;
    GroupBox2: TGroupBox;
    Label39: TLabel;
    Label10: TLabel;
    Label11: TLabel;
    Label12: TLabel;
    Label13: TLabel;
    Label14: TLabel;
    Label15: TLabel;
    Label16: TLabel;
    Label17: TLabel;
    Label2: TLabel;
    Label36: TLabel;
    DBEdit9: TDBEdit;
    DBEdit10: TDBEdit;
    DBEdit11: TDBEdit;
    DBEdit12: TDBEdit;
    DBEdit13: TDBEdit;
    DBEdit14: TDBEdit;
    DBEdit15: TDBEdit;
    DBEdit16: TDBEdit;
    DBEdit1: TDBEdit;
    EditCodigo: TDBEdit;
    GroupBox1: TGroupBox;
    Label3: TLabel;
    Label5: TLabel;
    Label18: TLabel;
    Label19: TLabel;
    Label20: TLabel;
    Label21: TLabel;
    Label35: TLabel;
    Label41: TLabel;
    DBEdit17: TDBEdit;
    DBEdit18: TDBEdit;
    DBEdit19: TDBEdit;
    DBEdit20: TDBEdit;
    DBCheckBox1: TDBCheckBox;
    DBCheckBox2: TDBCheckBox;
    EditNNota: TDBEdit;
    DBEdit2: TDBEdit;
    DBLookupComboBox2: TDBLookupComboBox;
    DBGrid1: TDBGrid;
    GroupBox12: TGroupBox;
    Label23: TLabel;
    Label25: TLabel;
    Label26: TLabel;
    Label27: TLabel;
    Label28: TLabel;
    Label24: TLabel;
    Label32: TLabel;
    Label33: TLabel;
    Label42: TLabel;
    Edit5: TDBEdit;
    Edit6: TDBEdit;
    Edit7: TDBEdit;
    Edit8: TDBEdit;
    Edit9: TDBEdit;
    Edit10: TDBEdit;
    DBEdit21: TDBEdit;
    DBEdit22: TDBEdit;
    DBEdit7: TDBEdit;
    DBEdit3: TDBEdit;
    StatusBar1: TStatusBar;
    GroupBox11: TGroupBox;
    Label37: TLabel;
    Label34: TLabel;
    Label1: TLabel;
    Label22: TLabel;
    Label8: TLabel;
    Label9: TLabel;
    EditObs: TDBEdit;
    Edit4: TDBEdit;
    Edit1: TDBEdit;
    Edit2: TDBEdit;
    Edit3: TDBEdit;
    DBEdit23: TDBEdit;
    ajuda: TAction;
    procedure DBEdit1KeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure DBGrid2KeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure DBGrid2Enter(Sender: TObject);
    procedure FormatarExecute(Sender: TObject);
    procedure btnPrimeiroClick(Sender: TObject);
    procedure btnVoltarClick(Sender: TObject);
    procedure btnAvancarClick(Sender: TObject);
    procedure btnUltimoClick(Sender: TObject);
    procedure btnnovoClick(Sender: TObject);
    procedure btngravarClick(Sender: TObject);
    procedure btncancelarClick(Sender: TObject);
    procedure Label35Click(Sender: TObject);
    procedure TotalizarExecute(Sender: TObject);
    procedure PProdutoExecute(Sender: TObject);
    procedure FormProdutoExecute(Sender: TObject);
    procedure PClienteExecute(Sender: TObject);
    procedure DBGrid1ColExit(Sender: TObject);
    procedure DBGrid1Enter(Sender: TObject);
    procedure DBGrid1Exit(Sender: TObject);
    procedure DBGrid1KeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure NovoExecute(Sender: TObject);
    procedure EditCodigoKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure Label36Click(Sender: TObject);
    procedure DBCheckBox1Click(Sender: TObject);
    procedure DBCheckBox2Click(Sender: TObject);
    procedure FormKeyPress(Sender: TObject; var Key: Char);
    procedure avancarExecute(Sender: TObject);
    procedure voltarExecute(Sender: TObject);
    procedure EditNNotaKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure SpeedButton8Click(Sender: TObject);
    procedure focoExecute(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure Edit1Exit(Sender: TObject);
    procedure estoqueExecute(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure btndeleteClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
    procedure ajudaExecute(Sender: TObject);
  private
  procedure AppHint(Sender : TObject);
    { Private declarations }
  public
  St, st1, foc:String;
  BOK : Boolean;
  it : integer;
    { Public declarations }
  end;

var
  fnota: Tfnota;

implementation

uses ulistacliente, ulistaproduto, UnitMenu, UnitRelatorioNota, upedido,
  UnitCliente, Extens, udm;



procedure tfnota.AppHint(Sender: TObject);
begin
  StatusBar1.Panels[0].Text := Application.Hint;
end;


{$R *.DFM}

procedure Tfnota.DBEdit1KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
        if key = vk_F12 then begin
         Application.CreateForm (Tflistacliente, flistacliente);
          fdm.tbcliente.open;
           flistacliente.show;
            end;
end;

procedure Tfnota.DBGrid2KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
                if key = vk_F12 then begin
         Application.CreateForm (Tflistaproduto, flistaproduto);
          flistaproduto.table1.open;
           flistaproduto.show;
            end;
end;

procedure Tfnota.DBGrid2Enter(Sender: TObject);
begin
        fdm.tbnota.edit;
         fdm.tbnota.post;
end;

procedure Tfnota.FormatarExecute(Sender: TObject);
begin
 (fdm.tbnota.fieldbyname ('nota') as tfloatfield).displayformat := '000000';
 (fdm.tbnota.fieldbyname ('emissao') as tdatetimefield).editmask := '99/99/9999';
 (fdm.tbnota.fieldbyname ('VencimentoB') as tdatetimefield).editmask := '99/99/9999';
 (fdm.tbnota.fieldbyname ('Vencimentoc') as tdatetimefield).editmask := '99/99/9999';
 (fdm.tbnota.fieldbyname ('datasaida') as tdatetimefield).editmask := '99/99/9999';
 (fdm.tbnota.fieldbyname ('horasaida') as tdatetimefield).editmask := '99:99';
 (fdm.tbnota.fieldbyname ('codigo') as tfloatfield).displayformat := '000000';
 (fdm.tbnota.fieldbyname ('pesob') as tfloatfield).displayformat := '#0.00';
 (fdm.tbnota.fieldbyname ('pesol') as tfloatfield).displayformat := '#0.00';
 (fdm.tbnota.fieldbyname ('vrproduto') as tfloatfield).displayformat := '###,##0.00';
 (fdm.tbnota.fieldbyname ('valorA') as tfloatfield).displayformat := '###,##0.00';
 (fdm.tbnota.fieldbyname ('valorB') as tfloatfield).displayformat := '###,##0.00';
 (fdm.tbnota.fieldbyname ('valorC') as tfloatfield).displayformat := '###,##0.00';
 (fdm.tbnota.fieldbyname ('vrpedido') as tfloatfield).displayformat := '###,##0.00';
 (fdm.tbnota.fieldbyname ('vrfrete') as tfloatfield).displayformat := '###,##0.00';
 (fdm.tbnota.fieldbyname ('vrnota') as tfloatfield).displayformat := '###,##0.00';
 (fdm.tbnota.fieldbyname ('cep') as tstringfield).editmask := '99.999-999' ;
 (fdm.tbnota.fieldbyname ('fone/fax') as tstringfield).editmask := '(99)9999-9999';
 (fdm.tbnota.fieldbyname ('uf') as tstringfield).editmask := 'aa';
 (fdm.tbnotaitem.fieldbyname ('codigo') as tfloatfield).displayformat := '000000';
 (fdm.tbnotaitem.fieldbyname ('vrunit') as tfloatfield).displayformat := '###,##0.00';
 (fdm.tbnotaitem.fieldbyname ('total') as tfloatfield).displayformat := '###,##0.00';
 (fdm.tbnotaitem.fieldbyname ('qtd') as tfloatfield).displayformat := '00';

end;

procedure Tfnota.btnPrimeiroClick(Sender: TObject);
begin
        fdm.TbNota.first;
end;

procedure Tfnota.btnVoltarClick(Sender: TObject);
begin
        fdm.TbNota.prior;
end;

procedure Tfnota.btnAvancarClick(Sender: TObject);
begin
        fdm.TbNota.Next;
end;

procedure Tfnota.btnUltimoClick(Sender: TObject);
begin
        fdm.TbNota.last;
end;

procedure Tfnota.btnnovoClick(Sender: TObject);
begin
        novoexecute(self);
         dbedit19.setfocus;
end;

procedure Tfnota.btngravarClick(Sender: TObject);
begin
        fdm.tbnota.edit;
         fdm.tbnota.post;
          btnGravar.Enabled:=false;
           btncancelar.enabled := false;

end;

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

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

procedure Tfnota.TotalizarExecute(Sender: TObject);
var
tot : real;
bookmark : tbookmarkstr;
begin


     bookmark := fdm.tbnotaitem.Bookmark;

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

    try
    fdm.tbnotaitem.First;

    while not fdm.tbnotaitem.Eof do begin
    fdm.tbnotaitem.edit;
    fdm.tbnotaitem['total'] := (fdm.tbnotaitem.fieldbyname ('qtd') as tfloatfield).Value *
    (fdm.tbnotaitem.fieldbyname ('vrunit') as tfloatfield).Value;
    tot := tot + (fdm.tbnotaitem.fieldbyname ('total') as tfloatfield).Value;
    fdm.tbnotaitem.next;
    end;
    finally

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

    fdm.tbnota.edit;
    fdm.tbnota['vrproduto'] := tot;
    fdm.tbnota['vrnota'] :=  (fdm.tbnota.fieldbyname ('vrfrete') as tfloatfield).Value + tot;   // produto + frete
    fdm.tbnota.post;


end;

procedure Tfnota.PProdutoExecute(Sender: TObject);
   var
   prod:string;
begin
     
     fdm.tbproduto.open;
      fdm.tbproduto.Refresh;

       if fdm.tbproduto.Locate('codigo',fdm.tbnotaitem['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.tbnotaitem.edit;

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

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



end;

procedure Tfnota.FormProdutoExecute(Sender: TObject);
begin
         Application.CreateForm (Tflistaproduto, flistaproduto);
          flistaproduto.st :='nota';
           flistaproduto.table1.open;
            flistaproduto.show;
end;

procedure Tfnota.PClienteExecute(Sender: TObject);
begin

          fdm.tbcliente.open;

               if fdm.tbcliente.Locate ('codigo',EditCodigo.text,[]) then begin
               fdm.tbnota.edit;
               fdm.tbnota['nome'] := fdm.tbcliente['nome'];
               fdm.tbnota['endereco'] := fdm.tbcliente['endereco'];
               fdm.tbnota['bairro'] := fdm.tbcliente['bairro'];
               fdm.tbnota['municipio'] := fdm.tbcliente['cidade'];
               fdm.tbnota['cep'] := fdm.tbcliente['cep'];
               fdm.tbnota['uf'] := fdm.tbcliente['uf'];
               fdm.tbnota['fone/fax'] := fdm.tbcliente['fone'];
               fdm.tbnota['cgc'] := fdm.tbcliente['cgc'];
               fdm.tbnota['ie'] := fdm.tbcliente['ie'];
               fdm.tbnota['vendedor'] := fdm.tbcliente['vendedor'];
               fdm.tbnota['Fretoconta'] := '2';
               fdm.tbnota['transportadora'] := fdm.tbcliente['transportadora'];
               fdm.tbnota['especia'] :='CAIXAS';
               fdm.tbcliente.close;

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

end;

procedure Tfnota.DBGrid1ColExit(Sender: TObject);
begin
        if dbgrid1.selectedindex = 0 then
         pprodutoExecute (self);

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

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

procedure Tfnota.DBGrid1Enter(Sender: TObject);
 begin
        keypreview := false;
        btngravarclick(self);
        foc:='1';

end;

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

procedure Tfnota.DBGrid1KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
        if key = vk_F12 then
         formprodutoexecute (self);

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

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

procedure Tfnota.NovoExecute(Sender: TObject);
begin


        if foc = '1' then begin
         fdm.tbnotaitem.Insert;
          dbgrid1.SelectedIndex := 0;

       end else begin

       fdm.TbNota.Refresh;

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

        fdm.TbNota.insert;
        if fdm.query1['codigo'] <> null then
         fdm.TbNota['nota'] := fdm.query1['codigo'] + 1
        else
        fdm.TbNota['nota']:='1';
        fdm.TbNota['S']:='X';
        fdm.TbNota['emissao']:=DateTostr(now);
        fdm.TbNota['Natureza']:='VENDAS';
        fdm.TbNota['CFOP']:='5.12';


        st := '';

          fdm.query1.close;
        btnGravar.Enabled:=true;
        btncancelar.Enabled := true;

     end;

end;

procedure Tfnota.EditCodigoKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
        if key = vk_F12 then begin
         Application.CreateForm (Tflistacliente, flistacliente);
          flistacliente.st := 'nota';
           fdm.tbcliente.open;
            flistacliente.show;
             end;

         if key = 13 then begin
          pclienteexecute(self);
           dbgrid1.SetFocus;
            end;
end;

procedure Tfnota.Label36Click(Sender: TObject);
begin
        BOK := inputquery('Localizar Cliente','Entre com o código do cliente:',ST);
         if BOK then
          if not fdm.tbnota.Locate ('codigo',ST,[]) then
           ShowMessage ('Cliente não localizad0!!!');
            ST := '';
end;

procedure Tfnota.DBCheckBox1Click(Sender: TObject);
begin
       fdm.tbnota.edit;
        fdm.tbnota['S'] := ' ';
end;

procedure Tfnota.DBCheckBox2Click(Sender: TObject);
begin
       fdm.tbnota.edit;
        fdm.tbnota['E'] := ' ';
end;

procedure Tfnota.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 Tfnota.avancarExecute(Sender: TObject);
begin
        fdm.tbnota.Next;
end;

procedure Tfnota.voltarExecute(Sender: TObject);
begin
        fdm.tbnota.prior;
end;

procedure Tfnota.EditNNotaKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
        if key = VK_F3 then
         Label35Click(Self);
end;

procedure Tfnota.SpeedButton8Click(Sender: TObject);
Var
 NotaIni, NotaFin:String;
 bookmark : tbookmarkstr;
begin

        bookmark := fdm.tbnota.Bookmark;

     NotaIni := fdm.TBNOTA['NOTA'];

    if application.MessageBox('Imprimir apenas esta nota?','Imprimir',4)= mryes then begin

       fdm.tbnota.filtered := false;
        fdm.tbnota.filter := 'Nota = ''' + NotaIni + '''' ;
         fdm.tbnota.filtered := true;

     end else begin

     if InputQuery ('localizar...', 'Entre com o número inicial da Nota',NotaIni ) then
      if InputQuery ('localizar...', 'Entre com o número final da Nota',NotaFin ) then begin
       fdm.tbnota.filtered := false;
        fdm.tbnota.filter := 'Nota >= ''' + notaini + ''' and nota<= ''' + notafin +'''' ;
         fdm.tbnota.filtered := true;
   end;
   end;

        Application.CreateForm(tfrnota, frnota);

            frnota.QuickRep1.Previewmodal;
             fdm.tbnota.filtered := false;
              frnota.Release;
               fdm.tbnota.Bookmark := bookmark;


end;

procedure Tfnota.focoExecute(Sender: TObject);

begin

        it := it + 1;

        if it = 7 then it:=1;

        case it of

        1: dbedit2.setfocus;
        2: editcodigo.setfocus;
        3: venca.setfocus;
        4: dbgrid1.setfocus;
        5: edit5.setfocus;
        6: editobs.setfocus;
        end;
end;

procedure Tfnota.FormClose(Sender: TObject; var Action: TCloseAction);
begin
	        Application.OnHint := nil;
end;

procedure Tfnota.Edit1Exit(Sender: TObject);
begin
        totalizarexecute(self);
end;

procedure Tfnota.estoqueExecute(Sender: TObject);
var
tot: 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;

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

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

procedure Tfnota.FormShow(Sender: TObject);
begin
        fdm.tbnota.Last;
         btngravar.Enabled := false;
          btncancelar.Enabled := false;
end;

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

        fdm.tbnotaitem.Last;

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

         if fdm.tbnotaitem['cidogo'] <> null then
          fdm.tbnotaitem.delete;

         fdm.tbnota.delete;

         end;
end;

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

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

         idyes : begin
         fdm.tbnota.edit;
          fdm.tbnota.post;
           fdm.tbnotaitem.edit;
            fdm.tbnotaitem.post;
             fdm.tbvendedor.close;
              canclose:=true;
               end;

         idno : begin
          fdm.tbnota.cancel;
           fdm.tbnotaitem.cancel;
            canclose:=true;
             fdm.tbvendedor.close;
               end;

         idcancel :
           canclose:=false;
end;
end;

end;

procedure Tfnota.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\ajudanota.txt') then
   comp.lines.loadfromfile (extractfilepath(paramstr(0)) + '\ajuda\ajudanota.txt');

  texto := comp.Text;
  comp.Destroy;

  Showmessage (texto);


end;

end.


