unit uservico;

interface

uses
  Windows, variants, Messages, Classes, SysUtils, Graphics, Controls, StdCtrls, Forms,
  Dialogs, DBCtrls, DB, Grids, DBGrids, Mask, DBTables, ExtCtrls, Buttons,
  ToolWin, ComCtrls, ActnList, QuickRpt, QRCtrls, Menus;

type
  TFservico = class(TForm)
    DSServico: TDataSource;
    ActionList1: TActionList;
    totalizar: TAction;
    PageControl1: TPageControl;
    TabSheet1: TTabSheet;
    Panel1: TPanel;
    Label12: TLabel;
    Edit1: TEdit;
    ToolBar2: TToolBar;
    btnPrimeiro: TSpeedButton;
    btnVoltar: TSpeedButton;
    btnAvancar: TSpeedButton;
    btnUltimo: TSpeedButton;
    Panel6: TPanel;
    Panel7: TPanel;
    btnnovo: TSpeedButton;
    Panel5: TPanel;
    btngravar: TSpeedButton;
    Panel8: TPanel;
    btncancelar: TSpeedButton;
    Panel12: TPanel;
    BtnFechar: TSpeedButton;
    Panel4: TPanel;
    btnimprimir: TSpeedButton;
    Panel9: TPanel;
    BtnDeleta: TSpeedButton;
    Panel14: TPanel;
    BtnCadastro: TSpeedButton;
    Panel2: TPanel;
    ScrollBox: TScrollBox;
    Bevel6: TBevel;
    Bevel4: TBevel;
    Bevel1: TBevel;
    Bevel5: TBevel;
    Bevel7: TBevel;
    Label2: TLabel;
    Label3: TLabel;
    Label4: TLabel;
    Label7: TLabel;
    Label9: TLabel;
    Label10: TLabel;
    Label11: TLabel;
    Label17: TLabel;
    Label8: TLabel;
    Label14: TLabel;
    Label15: TLabel;
    Label16: TLabel;
    Label18: TLabel;
    Label20: TLabel;
    Label21: TLabel;
    Label22: TLabel;
    Label23: TLabel;
    EditEntradaN: TDBEdit;
    EditData: TDBEdit;
    EditVeiculo: TDBEdit;
    EditPlaca: TDBEdit;
    EditQtdDias: TDBEdit;
    EditHora: TDBEdit;
    EditQtdHora: TDBEdit;
    EditDataSaida: TDBEdit;
    DBRadioGroup2: TDBRadioGroup;
    DBGrid1: TDBGrid;
    EditHoraSaida: TDBEdit;
    DBRadioGroup3: TDBRadioGroup;
    EditVrDiarias: TDBEdit;
    EditVrHoras: TDBEdit;
    EditVrItens: TDBEdit;
    EditVrMotor: TDBEdit;
    EditVrCera: TDBEdit;
    EditSubTotal: TDBEdit;
    EditDescontos: TDBEdit;
    EditVrServTerc: TDBEdit;
    TabSheet2: TTabSheet;
    DBGrid2: TDBGrid;
    Panel13: TPanel;
    GroupBox2: TGroupBox;
    Label34: TLabel;
    Label35: TLabel;
    GroupBox3: TGroupBox;
    Data1: TDateTimePicker;
    Data2: TDateTimePicker;
    DSCliente: TDataSource;
    ComboConvenio: TDBComboBox;
    Panel3: TPanel;
    Bevel2: TBevel;
    Label19: TLabel;
    EditTotal: TDBEdit;
    FechaHora: TAction;
    FechaDia: TAction;
    FechaConvenio: TAction;
    EntraPago: TAction;
    DBRadioGroup1: TDBRadioGroup;
    FechaParticular: TAction;
    ErroCampo: TAction;
    BtCaixa: TSpeedButton;
    BTExcluidos: TSpeedButton;
    Panel15: TPanel;
    Label25: TLabel;
    Label26: TLabel;
    LbEstacionamento: TLabel;
    LbLavador: TLabel;
    LbTotal: TLabel;
    Label30: TLabel;
    Label27: TLabel;
    LbDesconto: TLabel;
    SpeedButton6: TSpeedButton;
    BtCarroEst: TSpeedButton;
    SpeedButton3: TSpeedButton;
    BtCancelaFiltro: TSpeedButton;
    SpeedButton7: TSpeedButton;
    SpeedButton8: TSpeedButton;
    Lavacao: TAction;
    CkCera: TCheckBox;
    CkMotor: TCheckBox;
    CkServico: TCheckBox;
    Gerapago: TAction;
    FechaPago: TAction;
    BtGrava: TSpeedButton;
    BtCancela: TSpeedButton;
    BtImprime: TSpeedButton;
    Panel11: TPanel;
    Label13: TLabel;
    Bevel8: TBevel;
    EditDinheiro: TEdit;
    Bevel3: TBevel;
    Label1: TLabel;
    DBText1: TDBText;
    Label5: TLabel;
    Label6: TLabel;
    Label28: TLabel;
    Label24: TLabel;
    LBTroco: TLabel;
    Panel10: TPanel;
    Panel16: TPanel;
    SpeedButton1: TSpeedButton;
    Panel17: TPanel;
    procedure btnnovoClick(Sender: TObject);
    procedure btngravarClick(Sender: TObject);
    procedure btncancelarClick(Sender: TObject);
    procedure BtnDeletaClick(Sender: TObject);
    procedure btnimprimirClick(Sender: TObject);
    procedure FormKeyPress(Sender: TObject; var Key: Char);
    procedure Edit1Change(Sender: TObject);
    procedure Edit1Exit(Sender: TObject);
    procedure btnPrimeiroClick(Sender: TObject);
    procedure btnVoltarClick(Sender: TObject);
    procedure btnAvancarClick(Sender: TObject);
    procedure btnUltimoClick(Sender: TObject);
    procedure BtnFecharClick(Sender: TObject);
    procedure BtnCadastroClick(Sender: TObject);
    procedure RadioButton1Click(Sender: TObject);
    procedure totalizarExecute(Sender: TObject);
    procedure BtCancelaFiltroClick(Sender: TObject);
    procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
    procedure BtCarroEstClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure DBRadioGroup2Click(Sender: TObject);
    procedure ComboConvenioDropDown(Sender: TObject);
    procedure FechaHoraExecute(Sender: TObject);
    procedure FechaDiaExecute(Sender: TObject);
    procedure FechaConvenioExecute(Sender: TObject);
    procedure BTExcluidosClick(Sender: TObject);
    procedure Edit1Enter(Sender: TObject);
    procedure EntraPagoExecute(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FechaParticularExecute(Sender: TObject);
    procedure ComboConvenioChange(Sender: TObject);
    procedure CkCeraClick(Sender: TObject);
    procedure ErroCampoExecute(Sender: TObject);
    procedure DBGrid1Enter(Sender: TObject);
    procedure BtCaixaClick(Sender: TObject);
    procedure DBRadioGroup3Click(Sender: TObject);
    procedure TabSheet2Exit(Sender: TObject);
    procedure SpeedButton3Click(Sender: TObject);
    procedure SpeedButton6Click(Sender: TObject);
    procedure SpeedButton7Click(Sender: TObject);
    procedure SpeedButton8Click(Sender: TObject);
    procedure LavacaoExecute(Sender: TObject);
    procedure CkMotorClick(Sender: TObject);
    procedure CkServicoClick(Sender: TObject);
    procedure GerapagoExecute(Sender: TObject);
    procedure PageControl1Change(Sender: TObject);
    procedure FechaPagoExecute(Sender: TObject);
    procedure EditPlacaExit(Sender: TObject);
    procedure TabSheet1Enter(Sender: TObject);
    procedure FormKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure LbEntradaClick(Sender: TObject);
    procedure ComboConvenioEnter(Sender: TObject);
    procedure ComboConvenioExit(Sender: TObject);
    procedure EditDinheiroKeyPress(Sender: TObject; var Key: Char);
    procedure EditDinheiroExit(Sender: TObject);
    procedure EditDinheiroKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure EditDinheiroEnter(Sender: TObject);
    procedure SpeedButton1Click(Sender: TObject);
  private
    { private declarations }
  public
    { public declarations }
  end;

var
  Fservico: TFservico;

implementation

uses uvalor, UImpEntrada, UImpSaida, UJustificativa, UDataModulo,
  UDialogoImp,UCaixa,UReceber,UBackup;

{$R *.DFM}

function VerCampo:Boolean;
begin
  if (Modulo.TBServico['Veículo']=null) or (Modulo.TBServico['Placa']=null) then
    result:=True
  else
    result:=False;
end;
procedure TFservico.btnnovoClick(Sender: TObject);
begin
  if (modulo.TBServico['EntradaN']=null) or ((Modulo.TBServico['Placa'] <> null) and
               (Modulo.TBServico['Veículo'] <> null)) then
  begin
    btnGravar.Enabled:=true;
    btncancelar.Enabled := true;

    with modulo.query1 do
    begin
      close;
      sql.clear;
      sql.add('select max(EntradaN) as codigo from tbservico');
      open;
    end;
    modulo.TBServico.insert;
    if modulo.query1['codigo'] <> null then
    modulo.TBServico['EntradaN'] := modulo.query1['codigo'] + 1
    else
      modulo.TBServico['EntradaN']:='1';

    modulo.TBServico['dataentrada']:=DateTostr (now);
    Modulo.TBServico['horaentrada']:=timetostr(now);
    Modulo.TBServico['Especie']:='H';
    Modulo.TBServico['Tipo']:='P';
    Modulo.TBServico['Convenio']:='Particular';
    Modulo.query1.close;

    EditPlaca.setfocus;
  end
  else
    ErroCampoExecute(Self);

  ComboConvenio.Enabled:=False;
end;

procedure TFservico.btngravarClick(Sender: TObject);
begin
  if (EditPlaca.Text <> '') and (EditVeiculo.Text <> '') then
  begin
    Modulo.TBServico.Edit;
    Modulo.TBServico.Post;
    btngravar.Enabled:=false;
    btncancelar.Enabled:=false;
    btgrava.Enabled:=false;
    btcancela.Enabled:=false;

  end
  else
    ErroCampoexecute(self);
  ComboConvenio.Enabled:=False;
end;

procedure TFservico.btncancelarClick(Sender: TObject);
begin
  Modulo.TBServico.cancel;
  btnGravar.Enabled:=false;
  btncancelar.enabled := false;
  btgrava.Enabled:=false;
  btcancela.Enabled:=false;
  ComboConvenio.Enabled:=False;
end;

procedure TFservico.BtnDeletaClick(Sender: TObject);
begin
  if Modulo.TBServico['EntradaN']=null then
  begin
    ShowMessage('Nenhum Registro a ser excluído.');
    Abort;
  end;
  if Application.MessageBox('Deseja excluir esta entrada? ',
                             'Confirme', 4)= idYes then
  Modulo.TBServico.delete;
  BtnCancelar.Enabled:=False;
  BtnGravar.Enabled:=False;
end;

procedure TFservico.btnimprimirClick(Sender: TObject);
begin

  if Modulo.TbServico['DataSaida']=null then
  begin
    if BtnCancelar.Enabled=True then
      BtnGravarClick(Self);

    if Modulo.TBServico['Tipo']='G' then
      EntraPagoExecute(self)
    else
      Try
        if Application.MessageBox('Deseja mesmo imprimir esta entrada?',
                                  'Imprimir?',0+4+32)= 6 then
        begin
          Modulo.TBServico.Filter := 'EntradaN ='''+EditEntradaN.text+'''';
          Modulo.TBServico.Filtered := True;
          Application.CreateForm (TFImpEntrada, FImpEntrada);
          FImpEntrada.quickrep1.Print;
        end
        else
          Abort;

      finally
        Modulo.TBServico.Filtered :=False;
        FImpEntrada.Free
      end;

  end
  else  
  begin
    Application.MessageBox('Esta conta já foi fechada.'+#13+
                           'Abra uma nova conta para efetuar a transação.',
                           'Conta já fechada.',0+48);
    Abort;
  end;
  Modulo.TBServico.Last;
end;
procedure TFservico.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 TFservico.Edit1Change(Sender: TObject);
begin
  if not VerCampo then
    Modulo.TBServico.Locate('Placa',Edit1.Text,[]);
end;
procedure TFservico.Edit1Exit(Sender: TObject);
begin
  Edit1.Clear;
  Modulo.TBServico.Filtered:=False;
end;

procedure TFservico.btnPrimeiroClick(Sender: TObject);
begin
  if VerCampo then
    ErroCampoExecute(self)
  else
    Modulo.TBServico.First;
end;

procedure TFservico.btnVoltarClick(Sender: TObject);
begin
  if VerCampo then
    ErroCampoExecute(self)
  else
    Modulo.TBServico.Prior;
end;

procedure TFservico.btnAvancarClick(Sender: TObject);
begin
  if VerCampo then
   ErroCampoExecute(self)
  else
   Modulo.TBServico.next; 
end;

procedure TFservico.btnUltimoClick(Sender: TObject);
begin
  if VerCampo then
    ErroCampoExecute(self)
  else
    Modulo.TBServico.last;
end;

procedure TFservico.BtnFecharClick(Sender: TObject);
begin
  if btncancelar.Enabled then
     BtnGravarClick(self);

  if Modulo.TBServico['Tipo']='G' then
  begin
    FechaPagoExecute(Self);
    Abort;//Pára aqui se for pré-pago
  end;

  if Application.MessageBox('Deseja registrar Fechamento?','Fechamento',0+4+32)=6 then
  begin
    Modulo.TBServico.Edit;
    if (Modulo.TBServico['Tipo']='P') or (Modulo.TBServico['Tipo']='C')then
    begin
      Modulo.TBServico['horasaida']:= timetostr(now);
      Modulo.TBServico['datasaida']:= datetostr(now);
      Modulo.TBServicoqtddias.Clear;
      Modulo.TBServicoqtdhora.Clear;
    end;

    if Modulo.TBServico['Especie'] = 'H' then
      FechaHoraexecute(Self);
    if Modulo.TBServico['Especie'] = 'D' then
      FechaDiaExecute(Self);
    //  Se o campo estiver preenchido não pega da TbValores

    Modulo.TBServicoSubTotal.Value:=Modulo.TBServicoVrDiaria.Value +
             Modulo.TBServicoVrHora.Value + Modulo.TBServicoVrItens.Value +
             Modulo.TBServicoVrCera.Value + Modulo.TBServicoVrMotor.Value +
             Modulo.TBServicoVrTerceiro.Value ;

    Modulo.TBServicoTotal.Value:= Modulo.TBServicoSubTotal.Value -
                                  Modulo.TBServicoDesconto.Value;
    Modulo.TBServico.Post;

    if Modulo.TBServico['Tipo']= 'P' then
      FechaParticularExecute(self);
    if Modulo.TBServico['Tipo']= 'C' then
      FechaConvenioExecute(self);

    try
      Modulo.TBServico.Filter :='EntradaN='''+EditEntradaN.text+'''';
      Modulo.TBServico.Filtered := True;
      Application.CreateForm(TFDialogoImp,FDialogoImp);
      FDialogoImp.ShowModal;
      FDialogoImp.Release;
    finally
      FDialogoImp.Free;
      Modulo.TBServico.Filtered := false;
    end;

    BtnCancelar.Enabled:=False;
    BtnGravar.Enabled:=False;
  end
  else
    Abort;
  EditDinheiro.SetFocus;
end;
procedure TFservico.BtnCadastroClick(Sender: TObject);
begin
  try
    application.CreateForm( TFCadastro, FCadastro);
    FCadastro.showmodal;
    FCadastro.release;
  finally
    FCadastro.Free;
  end;

end;

procedure TFservico.RadioButton1Click(Sender: TObject);

begin
        Modulo.TBServico.Filtered := false;
        Modulo.TBServico.Filter :='Datasaida <''01/01/1900''';
        Modulo.TBServico.Filtered := true;
end;

procedure TFservico.totalizarExecute(Sender: TObject);
var
tot : real;
bookmark : tbookmarkstr;
begin
  bookmark := Modulo.TBServico.Bookmark;
  try
    Modulo.TBServico.DisableControls;
    tot := 0;
    try
    Modulo.TBServico.First;

    while not Modulo.TBServico.Eof do
    begin
      tot := tot + Modulo.TBServicototal.asfloat;
      Modulo.TBServico.next;
    end;
    finally
      Modulo.TBServico.EnableControls;
    end;
  finally
    Modulo.TBServico.Bookmark := bookmark;
  end;

end;

procedure TFservico.BtCancelaFiltroClick(Sender: TObject);
begin
  Modulo.TBServico.Filtered := false;
end;

procedure TFservico.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
  if btngravar.Enabled = true then
  begin
    Showmessage('Você deverá gravar ou cancelar, para sair');
    canclose := false;
  end;
end;

procedure TFservico.BtCarroEstClick(Sender: TObject);
begin
  Modulo.TBServico.Filtered := false;
  Modulo.TBServico.Filter :='Datasaida <''01/01/1900''';
  Modulo.TBServico.Filtered := true;
end;

procedure TFservico.FormCreate(Sender: TObject);
begin
  Data1.Date:=Date;
  Data2.Date:=Date;
  Modulo.TBServico.Open;
  Modulo.TBValores.Open;
end;

procedure TFservico.DBRadioGroup2Click(Sender: TObject);
begin
  if DBRadioGroup2.ItemIndex=0 then
    Modulo.TBServico['Convenio']:='Particular';
  if DBRadioGroup2.ItemIndex=1 then
    ComboConvenio.Enabled:=True
  else
    ComboConvenio.Enabled:=False;
end;                             
procedure TFservico.ComboConvenioDropDown(Sender: TObject);
begin
  ComboConvenio.Items.Clear;
  with Modulo.Query1 do
  begin
    Close;
    SQL.Clear;
    SQL.Add('Select NomeFantasia from TbCliente order by NomeFantasia');
    Open;
  end;

  if Modulo.Query1['NomeFantasia'] <> null then
  begin
    Modulo.Query1.First;
    ComboConvenio.Items.Add('Particular');
    while not Modulo.Query1.Eof do
    begin
      ComboConvenio.Items.Add(Modulo.Query1['NomeFantasia']);
      Modulo.Query1.Next;
    end;
    Modulo.Query1.Close;
  end
  else
  begin
    ShowMessage('Não existe nenhum Cliente cadastrado.'+#13+
                'Cadastre-o em "Cadastros".');
    ComboConvenio.Items.Add('Particular');
  end;
end;

procedure TFservico.FechaHoraExecute(Sender: TObject);
var
HoraEnt,HoraSaida:TDateTime;
Horas:Integer;
FracaoHora,FracaoDia:Double;
begin
  FracaoHora:=0;
  FracaoDia:=0;
  Horas:=0;

  if (Modulo.TBServico['Tipo']='P') or (Modulo.TBServico['Tipo']='C')then
  begin
    HoraEnt:=StrToDateTime(DatetoStr(Modulo.TBServico['DataEntrada'])+' '+
                           TimeToStr(Modulo.TBServico['HoraEntrada']));
    HoraSaida:=StrToDateTime(DateToStr(Modulo.TBServico['DataSaida'])+' '+
                             TimeToStr(Modulo.TBServico['HoraSaida']));
    FracaoDia:=HoraSaida-HoraEnt;
    FracaoHora:=FracaoDia*24;
    while FracaoHora>Horas do
      Inc(Horas);
    FracaoHora:=FracaoHora-Horas;
    if FracaoHora<0 then
    begin
      FracaoHora:=FracaoHora+Horas;
      Dec(Horas);
      FracaoHora:=FracaoHora-Horas;
    end;

    if FracaoHora>1/6 then
      Inc(Horas);

    if Horas<1 then
      Inc(Horas);

    Modulo.TBServico['QtdHora']:=Horas;
  end;

  if Modulo.TbServico['VrHora']=null then
    Modulo.TbServico['VrHora']:=(Modulo.TBServico['QtdHora'])*
                                (Modulo.TbValores['VrHora'])
  else
    Modulo.TbServico['VrHora']:=(Modulo.TBServico['QtdHora'])*
                                (Modulo.TbServico['VrHora']);

  if Modulo.TBServico['Itens']<>null then
    LavacaoExecute(Self);

end;
procedure TFservico.FechaDiaExecute(Sender: TObject);
var
HoraEnt,HoraSaida:TDateTime;

FracaoHora,FracaoDia:Double;
Horas,Dias:Integer;

begin
  Fracaodia:=0;
  FracaoHora:=0;
  Horas:=0;
  Dias:=0;
  HoraEnt:=StrToDateTime(DatetoStr(Modulo.TBServico['DataEntrada'])+' '+
                         TimeToStr(Modulo.TBServico['HoraEntrada']));
  HoraSaida:=StrToDateTime(DateToStr(Modulo.TBServico['DataSaida'])+' '+
                           TimeToStr(Modulo.TBServico['HoraSaida']));

  FracaoDia:=HoraSaida-HoraEnt;

  while FracaoDia>Dias do
    Inc(Dias);

  FracaoDia:=FracaoDia-Dias;

  if FracaoDia<0 then
    begin
      FracaoDia:=Dias+FracaoDia;
      Dec(Dias);
      FracaoDia:=FracaoDia-Dias;
    end;

  if FracaoDia > 1/144 then
  begin
    FracaoHora:=FracaoDia*24;
    while FracaoHora>Horas do
      Inc(Horas);

    FracaoHora:=FracaoHora-Horas;
    if FracaoHora<0 then
    begin
      FracaoHora:=FracaoHora+Horas;
      Dec(Horas);
    end;
    FracaoHora:=FracaoHora-Horas;

    if FracaoHora > 1/6 then
      Inc(Horas);

    Modulo.TBServico['QtdHora']:=Horas;

    if Modulo.TbServico['VrHora']=null then
      Modulo.TBServico['VrHora']:=(Modulo.TBServico['QtdHora'])*
                                  (Modulo.TbValores['VrHora'])
    else
      Modulo.TbServico['VrHora']:=(Modulo.TBServico['QtdHora'])*
                                  (Modulo.TbServico['VrHora']);

  end;

  Modulo.TbServico['QtdDias']:=Dias;

  if Modulo.TBServico['VrDiaria']=null then
    Modulo.TBServico['VrDiaria']:=(Modulo.TBServico['qtddias'])*
                                  (Modulo.TBValores['VrDiaria'])
  else
    Modulo.TBServico['VrDiaria']:=(Modulo.TBServico['qtddias'])*
                                  (Modulo.TBServico['VrDiaria']);
end;
procedure TFservico.FechaConvenioExecute(Sender: TObject);
begin
  if ComboConvenio.Text='Particular' then
  begin
    ShowMessage('Selecione o Cliente, antes de Fechar.');
    Abort;
  end;
  Modulo.TbReceber.Open;
  Modulo.TbReceber.Refresh;

  with Modulo.Query1 do
  begin
    Close;
    Sql.Clear;
    Sql.Add('Select max(Codigo) as codigo from TbReceber');
    Open;
  end;

  Modulo.TbReceber.Insert;
  if Modulo.Query1['codigo']<>null then
    Modulo.TbReceber['Codigo']:=Modulo.Query1['codigo']+1
  else
     Modulo.TbReceber['Codigo']:='1';

  Modulo.TbReceber['Data']:=DateToStr(Now);
  Modulo.TbReceber['Situacao']:='';
  Modulo.TbReceber['CodCliente']:=Modulo.TBServico['CodCliente'];
  Modulo.TbReceber['Fantasia']:=Modulo.TBServico['Convenio'];
  Modulo.TbReceber['EntradaN']:=Modulo.TBServico['EntradaN'];
  Modulo.TbReceber['Veículo']:=Modulo.TBServico['Veículo'];
  Modulo.TbReceber['Placa']:=Modulo.TBServico['Placa'];
  Modulo.TbReceber['Itens']:=Modulo.TBServico['Itens'];
  Modulo.TbReceber['Complemento']:=Modulo.TBServico['Complemento'];
  Modulo.TbReceber['HoraEntrada']:=Modulo.TBServico['HoraEntrada'];
  Modulo.TbReceber['DataEntrada']:=Modulo.TBServico['DataEntrada'];
  Modulo.TbReceber['DataSaida']:=Modulo.TBServico['DataSaida'];
  Modulo.TbReceber['HoraSaida']:=Modulo.TBServico['HoraSaida'];
  Modulo.TbReceber['VrDiaria']:=Modulo.TBServico['VrDiaria'];
  Modulo.TbReceber['VrHora']:=Modulo.TBServico['VrHora'];
  Modulo.TbReceber['VrItens']:=Modulo.TBServico['VrItens'];
  Modulo.TbReceber['VrCera']:=Modulo.TBServico['VrCera'];
  Modulo.TbReceber['VrMotor']:=Modulo.TBServico['VrMotor'];
  Modulo.TbReceber['VrTerceiro']:=Modulo.TBServico['VrTerceiro'];
  Modulo.TbReceber['QtdDias']:=Modulo.TBServico['QtdDias'];
  Modulo.TbReceber['QtdHora']:=Modulo.TBServico['QtdHora'];
  Modulo.TbReceber['SubTotal']:=Modulo.TBServico['SubTotal'];
  Modulo.TbReceber['Desconto']:=Modulo.TBServico['Desconto'];
  Modulo.TbReceber['Total']:=Modulo.TBServico['Total'];
  Modulo.TbReceber.Edit;
  Modulo.TbReceber.Post;
  Modulo.TbReceber.Close;

end;

procedure TFservico.BTExcluidosClick(Sender: TObject);
begin
  Try
    Application.CreateForm(TFJustificativa, FJustificativa);
    FJustificativa.ShowModal;
    FJustificativa.Release;
  finally
    FJustificativa.Free;
  end;
end;

procedure TFservico.Edit1Enter(Sender: TObject);
begin
 if ((Modulo.TbServico.State=dsInsert) or (Modulo.TbServico.State=dsEdit)) then
 begin
    ErroCampoExecute(Self);
    Abort;
 end
 else
   BtCarroEstClick(Self);
end;
procedure TFservico.EntraPagoExecute(Sender: TObject);
var
HoraEnt,HoraSaida:TDateTime;
begin
  if (Modulo.TbServico['Especie']='H') and  (Modulo.TBServico['QtdHora']<>null) then
  begin
    HoraEnt:=StrToDateTime(DatetoStr(Modulo.TBServico['DataEntrada'])+' '+
                         TimeToStr(Modulo.TBServico['HoraEntrada']));

    HoraSaida:=(HoraEnt)+(Modulo.TBServicoQtdHora.value/24);
    Modulo.TBServico.Edit;
    Modulo.TBServico['VencPago']:=HoraSaida;

    if Modulo.TBServico['VrHora']=null then
      Modulo.TBServico['VrHora']:=(Modulo.TBValores['VrHora'])*
                                  (Modulo.TBServico['QtdHora'])
    else
      Modulo.TBServico['VrHora']:=(Modulo.TBServico['VrHora'])*
                                  (Modulo.TBServico['QtdHora']);
    Modulo.TBServico.Post;
    GeraPagoExecute(self);
  end
  else
    if (Modulo.TbServico['Especie']='H') then
    begin
      Application.MessageBox('Você precisa especificar a quantidade de horas.',
                           'Atenção',0+48);
      EditQtdHora.SetFocus;
      Abort;
    end;

  ///*******Fim de Hora*********///

  if (Modulo.TbServico['Especie']='D') and (Modulo.TbServico['QtdDias']<>null) then
  begin
    HoraEnt:=StrToDateTime(DatetoStr(Modulo.TBServico['DataEntrada'])+' '+
                         TimeToStr(Modulo.TBServico['HoraEntrada']));
    HoraSaida:=(HoraEnt)+(Modulo.TbServicoQtdDias.value);
    Modulo.TBServico.Edit;
    Modulo.TBServico['VencPago']:=HoraSaida;

    if Modulo.TBServico['VrDiaria']=null then
        Modulo.TBServico['VrDiaria']:=(Modulo.TBValores['VrDiaria'])*
                                      (Modulo.TBServico['QtdDias'])
    else
      Modulo.TBServico['VrDiaria']:=(Modulo.TBServico['QtdDias'])*
                                    (Modulo.TBServico['VrDiaria']);

    GeraPagoExecute(self);
  end
  else
    if Modulo.TbServico['Especie']='D' then
    begin
      Application.MessageBox('Você precisa especificar a quantidade de dias.',
                           'Atenção',0+48);
      EditQtddias.SetFocus;
      Abort;
    end;
end;
procedure TFservico.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  Modulo.TbServico.Close;
  Modulo.TbValores.Close;
  Modulo.Free;
end;

procedure TFservico.FechaParticularExecute(Sender: TObject);
begin

  with Modulo.query1 do
  begin
    Close;
    Sql.Clear;
    Sql.Add('Select max(Codigo) as Codigo from TbRecebimentos');
    Open;
  end;
  Modulo.TbRecebimentos.Open;
  Modulo.TbRecebimentos.Refresh;
  Modulo.TbRecebimentos.Insert;

  if Modulo.Query1['Codigo']<>null then
    Modulo.TbRecebimentos['Codigo']:=Modulo.Query1['Codigo']+1

  else
    Modulo.TbRecebimentos['Codigo']:='1';

  Modulo.TbRecebimentos['EntradaN']:=Modulo.TBServico['EntradaN'];
  Modulo.TbRecebimentos['Data']:=DateToStr(now);
  Modulo.TbRecebimentos['Cliente']:='Particular';
  Modulo.TbRecebimentos['Natureza']:='Particular';
  Modulo.TbRecebimentos['Valor']:=Modulo.TBServico['Total'];
  Modulo.TbRecebimentos.Post;
  Modulo.TbRecebimentos.Close;
  Modulo.Query1.Close;
end;

procedure TFservico.ComboConvenioChange(Sender: TObject);
begin

   if ComboConvenio.Text<>'Particular' then
     try
       Modulo.TBCliente.Open;
       Modulo.TBCliente.Filtered:=False;
       Modulo.TBCliente.Filter:='NomeFantasia='''+ComboConvenio.Text+'''';
       Modulo.TBCliente.Filtered:=True;
       Modulo.TbServico['CodCliente']:=Modulo.TBCliente['CodCliente'];
     finally
       Modulo.TBCliente.Filtered:=False;
        Modulo.TBCliente.Refresh;
       Modulo.TBCliente.Close;
     end;
end;

procedure TFservico.CkCeraClick(Sender: TObject);
begin
  if CkCera.Checked then
    Modulo.TBServico['VrCera']:=Modulo.TBServico['VrCera']
  else
    Modulo.TBServico['VrCera']:=null;
end;

procedure TFservico.ErroCampoExecute(Sender: TObject);
begin
  if ((Modulo.TBServico['Veículo']=null) or (Modulo.TBServico['Placa']=null))
  and ((Modulo.TbServico.State=dsInsert) or (Modulo.TbServico.State=dsEdit))then
  begin
    Application.MessageBox('O(s) campo(s) Placa ou Veículo não foram'+
                           ' preenchidos.'+#13+'Preecha-o(s) ou Cancele o '+
                           'registro atual antes de realizar esta operação.',
                           'Placa ou Veículo não preenchidos.',0+16+256);
    if EditPlaca.Text = '' then
      EditPlaca.SetFocus;
    if (EditVeiculo.Text = '') and (EditPlaca.Text <> '') then
      EditVeiculo.SetFocus;
    Abort;
  end
  else
  //if(Modulo.TbServico.State=dsInsert) or (Modulo.TbServico.State=dsEdit) then
  begin
    Application.MessageBox('Você precisa Gravar ou Cancelar o registro atual,'
                          +#13+'antes de realizar esta operação.','Atenção',
                          0+16+256);
    EditVeiculo.SetFocus;
    Abort;
  end;    

end;
procedure TFservico.DBGrid1Enter(Sender: TObject);
begin
  if (Modulo.TbServico.State=dsInsert) or (Modulo.TbServico.State=dsEdit) then
    ErroCampoExecute(self);
end;
procedure TFservico.BtCaixaClick(Sender: TObject);
begin
  Try
    Application.CreateForm(TFCaixa, Fcaixa);
    FCaixa.ShowModal;
    FCaixa.Release;
  finally
    FCaixa.Free;
  end;
end;

procedure TFservico.DBRadioGroup3Click(Sender: TObject);
begin
  Case DBRadioGroup3.ItemIndex of
    0:Modulo.TbServico['VrItens']:=Modulo.TbValores['VrInterna'];
    1:Modulo.TbServico['VrItens']:=Modulo.TBValores['VrExterna'];
    2:Modulo.TBServico['VrItens']:=Modulo.TBValores['VrCompleta'];
  end;
  if DBRadioGroup3.ItemIndex>=1 then
  begin
    CkCera.Enabled:=True;
    CkMotor.Enabled:=True;
    CkServico.Enabled:=True;
  end
  else
  begin
    CkCera.Enabled:=False;
    CkMotor.Enabled:=False;
    CkServico.Enabled:=False;
  end;
end;

procedure TFservico.TabSheet2Exit(Sender: TObject);
begin
  Modulo.TbServico.Filtered:=False;
end;

procedure TFservico.SpeedButton3Click(Sender: TObject);
begin
  Modulo.TBServico.Filtered:=False;
  Modulo.TBServico.Filter:='Tipo=''C''and DataEntrada>='''+DateToStr(Data1.Date)+
                           '''and DataEntrada<='''+DateToStr(Data2.Date)+'''' ;
  Modulo.TBServico.Filtered:=True;
end;

procedure TFservico.SpeedButton6Click(Sender: TObject);
begin
  Modulo.TbServico.Filtered:=False;
  Modulo.TbServico.Filter:='Itens<>''''and DataEntrada>='''+DateToStr(Data1.Date)+
                           '''and DataEntrada<='''+DateToStr(Data2.Date)+'''' ;
  Modulo.TbServico.Filtered:=True;
end;

procedure TFservico.SpeedButton7Click(Sender: TObject);
var
Total,Lavador,Estacionamento,Desconto:Currency;
begin
  Modulo.TBServico.Filtered := false;
  Modulo.TBServico.Filter:='DataEntrada>='''+DateToStr(Data1.Date)+
                           '''and DataEntrada<='''+DateToStr(Data2.Date)+'''' ;
  Modulo.TBServico.Filtered:=True;
  Total:=0;
  Lavador:=0;
  Estacionamento:=0;
  Desconto:=0;
  Modulo.TBServico.DisableControls;
  Modulo.TBServico.First;
  try
    while not Modulo.TBServico.eof do
    begin
      if Modulo.TBServico['VrItens']<>null then
        Lavador:=Lavador+Modulo.TBServicoVrItens.Value;
      if Modulo.TBServico['VrCera']<>null then
        Lavador:=Lavador+Modulo.TBServicoVrCera.Value;
      if Modulo.TBServico['VrTerceiro']<>null then
        Lavador:=Lavador+Modulo.TBServicoVrTerceiro.Value;
        
      Modulo.TBServico.Next;
    end;

    Modulo.TBServico.First;
    while not Modulo.TBServico.eof do
    begin
      if Modulo.TBServico['Especie']='H' then
        Estacionamento:=Estacionamento+Modulo.TBServicoVrHora.value;
      if Modulo.TBServico['Especie']='D' then
        Estacionamento:=Estacionamento+Modulo.TBServicoVrDiaria.value;
      Modulo.TBServico.Next;
    end;

    Modulo.TBServico.First;
    while not Modulo.TBServico.eof do
    begin
      if Modulo.TBServico['Desconto']<>null then
        Desconto:=Desconto+Modulo.TBServicoDesconto.Value;
      Modulo.TBServico.Next;
    end;

    Total:=Lavador+Estacionamento-Desconto;
  finally
    LbLavador.Caption:='R$'+Format('%8f',[Lavador]);
    LbEstacionamento.Caption:='R$'+Format('%8f',[Estacionamento]);
    LbDesconto.Caption:='R$'+Format('%8f',[Desconto]);
    LbTotal.Caption:='R$'+Format('%8f',[Total]);
    Modulo.TBServico.EnableControls;
  end;

end;

procedure TFservico.SpeedButton8Click(Sender: TObject);
begin
  try
    Application.CreateForm(TFreceber,FReceber);
    FReceber.ShowModal;
    FReceber.Release;
  finally
    FReceber.Free;
  end;
end;

procedure TFservico.LavacaoExecute(Sender: TObject);
var
HoraEnt,HoraSaida:TDateTime;
FracaoDia:Double;
begin
  Fracaodia:=0;
  HoraEnt:=StrToDateTime(DatetoStr(Modulo.TBServico['DataEntrada'])+' '+
                         TimeToStr(Modulo.TBServico['HoraEntrada']));
  HoraSaida:=StrToDateTime(DateToStr(Modulo.TBServico['DataSaida'])+' '+
                           TimeToStr(Modulo.TBServico['HoraSaida']));
  FracaoDia:=HoraSaida-HoraEnt;
  if Fracaodia>13/144 then
  begin
    Modulo.TBServico['QtdHora']:=(Modulo.TBServico['QtdHora'])-2;
    Modulo.TBServico['VrHora']:=(Modulo.TBServico['QtdHora'])*
                                (Modulo.TbValores['VrHora']);
  end
  else
  begin
    Modulo.TBServico['QtdHora']:=null;
    Modulo.TBServico['VrHora']:=null;
  end;


end;

procedure TFservico.CkMotorClick(Sender: TObject);
begin
 if CkMotor.Checked then
    Modulo.TBServico['VrMotor']:=Modulo.TBServico['VrMotor']
  else
    Modulo.TBServico['VrMotor']:=null;
end;

procedure TFservico.CkServicoClick(Sender: TObject);
begin
  EditVrServTerc.SetFocus;
end;

procedure TFservico.GerapagoExecute(Sender: TObject);
var
marco:TBookmarkStr;
begin
  marco:=Modulo.TBServico.Bookmark;
  Modulo.TBServico.Edit;
  Modulo.TBServicoSubTotal.Value:=Modulo.TBServicoVrDiaria.Value +
           Modulo.TBServicoVrHora.Value + Modulo.TBServicoVrItens.Value +
           Modulo.TBServicoVrCera.Value + Modulo.TBServicoVrMotor.Value +
           Modulo.TBServicoVrTerceiro.Value ;
  if Modulo.TBServico['Desconto']<>null then
    Modulo.TBServico['Total']:=(Modulo.TBServico['SubTotal'])-
                               (Modulo.TBServico['Desconto'])
  else
    Modulo.TBServico['Total']:=Modulo.TBServico['SubTotal'];

  Modulo.TBServico.Post;

  Modulo.TBServico.Filter:='EntradaN='''+IntToStr(Modulo.TBServico['EntradaN'])+'''';
  Modulo.TBServico.Filtered:=True;

  try
    Application.CreateForm(TFDialogoImp,FDialogoImp);
    FDialogoImp.ShowModal;
    FDialogoImp.Release;
  finally
    FDialogoImp.Free;
    Modulo.TBServico.Filtered:=False;
  end;
  Modulo.TBServico.Bookmark:=marco;

  with Modulo.query1 do
  begin
    Close;
    Sql.Clear;
    Sql.Add('Select max(Codigo) as Codigo from TbRecebimentos');
    Open;
  end;
  Modulo.TbRecebimentos.Open;
  Modulo.TbRecebimentos.Insert;

  if Modulo.Query1['Codigo']<>null then
    Modulo.TbRecebimentos['Codigo']:=Modulo.Query1['Codigo']+1

  else
    Modulo.TbRecebimentos['Codigo']:='1';

  Modulo.TbRecebimentos['EntradaN']:=Modulo.TBServico['EntradaN'];
  Modulo.TbRecebimentos['Data']:=DateToStr(now);
  Modulo.TbRecebimentos['Cliente']:='Particular';
  Modulo.TbRecebimentos['Natureza']:='Pré-Pago';
  Modulo.TbRecebimentos['Valor']:=Modulo.TBServico['Total'];
  Modulo.TbRecebimentos.Post;
  Modulo.TbRecebimentos.Close;
  Modulo.Query1.Close;
end;
procedure TFservico.PageControl1Change(Sender: TObject);
begin
   if (Modulo.TBServico.State=dsInsert) or (Modulo.TBServico.State=dsEdit) then
   begin
     PageControl1.ActivePage:=TabSheet1;
     ErroCampoExecute(Self);
   end;
   Modulo.TBServico.Filtered:=False;
end;

procedure TFservico.FechaPagoExecute(Sender: TObject);
var
Entrada,Saida,Venc:TDateTime;
Placa, Veiculo:String;
begin
  if Modulo.TBServico['VencPago']<> null then
  begin
    Modulo.TBServico.Edit;
    Modulo.TBServico['horasaida']:= timetostr(now);
    Modulo.TBServico['datasaida']:= datetostr(now);
    Entrada:=StrToDateTime(DateToStr(Modulo.TBServico['DataEntrada'])+' '+
                           TimeToStr(Modulo.TbServico['HoraEntrada']));
    Saida:=StrToDateTime(DateToStr(Modulo.TBServico['datasaida'])+' '+
                         TimeToStr(Modulo.TBServico['horasaida']));

    Venc:=Modulo.TBServico['VencPago'];
    Modulo.TBServico.Post;

    if Saida>(Venc+1/144) then
    begin
      Placa:=Modulo.TbServico['Placa'];
      Veiculo:=Modulo.TbServico['Veículo'];
      with Modulo.Query1 do
      begin
        Close;
        Sql.Clear;
        Sql.Add('Select max(EntradaN) as EntradaN from TbServico');
        Open;
      end;

      modulo.TBServico.insert;
      if modulo.query1['EntradaN'] <> null then
        modulo.TBServico['EntradaN'] := modulo.query1['EntradaN'] + 1
      else
        modulo.TBServico['EntradaN']:='1';

      modulo.TBServico['dataentrada']:=DateToStr(Venc);
      Modulo.TBServico['horaentrada']:=timetostr(Venc);
      Modulo.TbServico['Placa']:=Placa;
      Modulo.TbServico['Veículo']:=Veiculo;
      Modulo.TBServico['Especie']:='H';
      Modulo.TBServico['Tipo']:='P';
      Modulo.TBServico['Convenio']:='Particular';
      Modulo.query1.close;
      BtnFecharClick(self);
    end
    else
      ShowMessage('Fechamento efetuado com sucesso.');
  end
  else
    Application.MessageBox('Não foi efetuado a rotina de entrada do veículo.'
                           +#13+'Isto é necessário para efetuar o fechamento.',
                           'Atenção',0+48);
  end;
procedure TFservico.EditPlacaExit(Sender: TObject);
begin
  if (Modulo.TBServico.State=DsInsert) or (Modulo.TBServico.State=DsEdit)then
  begin
    if EditPlaca.Text='' then
      ErrocampoExecute(self);
    with Modulo.Query1 do
    begin
      Close;
      SQL.Clear;
      SQL.Add('Select Placa as estacionado from TBServico where Placa="'+EditPlaca.Text+
              '"AND datasaida IS NULL');
      Open;
    end;

    if Modulo.Query1['estacionado']<>null then
    begin
      Application.MessageBox('O veículo com este número de placa já encontra-se '+
                         'estacionado.'+#13+'Verifique se digitação está correta.',
                         'Atenção',0+48);
      EditPlaca.SetFocus;
    end;
    Modulo.Query1.Close;
  end;
end;

procedure TFservico.TabSheet1Enter(Sender: TObject);
begin
  Modulo.TbServico.Refresh;
  Modulo.TbServico.Last;
end;

procedure TFservico.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  case key of
    VK_Insert: BtnNovoClick(self);
    VK_Prior: BtnVoltarClick(self);
    VK_Home:BtnPrimeiroClick(self);
    VK_Next:BtnAvancarClick(self);
    VK_End: BtnUltimoClick(self);
    VK_F2: BtnGravarClick(self);
    VK_F3: LbEntradaClick(self);
    VK_F5: BtnImprimirClick(self);
    VK_F6: BtnFecharClick(self);
  end;
end;
procedure TFservico.LbEntradaClick(Sender: TObject);
var
  St:String;
begin
  if InputQuery('Digite o número da entrada.','Localizar Entrada',St) then
    if not Modulo.TBServico.Locate('EntradaN',St,[])then
      ShowMessage('Esta entrada não existe, ou foi deletada.');
end;

procedure TFservico.ComboConvenioEnter(Sender: TObject);
begin
 Fservico.KeyPreview:=False;
end;

procedure TFservico.ComboConvenioExit(Sender: TObject);
begin
  Fservico.KeyPreview:=True;
end;

procedure TFservico.EditDinheiroKeyPress(Sender: TObject; var Key: Char);
begin
  if not (key in ['0'..'9',','])then
    abort;
end;
procedure TFservico.EditDinheiroExit(Sender: TObject);
begin
  EditDinheiro.Clear;
  LbTroco.Caption:='';
  Fservico.KeyPreview:=True;
end;

procedure TFservico.EditDinheiroKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if key=13 then
    LbTroco.Caption:='R$'+Format('%8f',[(StrToCurr(EditDinheiro.Text))
                   -(Modulo.TBServicoTotal.value)]);
  if key=VK_Insert then
    BtnNovoClick(self);
end;

procedure TFservico.EditDinheiroEnter(Sender: TObject);
begin
  FServico.KeyPreview:=False;
end;
procedure TFservico.SpeedButton1Click(Sender: TObject);
begin
  if not (Modulo.TbServico.State=dsInsert) or (Modulo.TbServico.State=dsEdit) then
  begin
    Application.CreateForm(TFBackup,FBackup);
    FBackup.ShowModal;
    FBackup.Release;
  end
  else
    Errocampoexecute(self);
end;

end.









