unit festadisticas;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.ComCtrls, Vcl.StdCtrls,
  Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, ZAbstractRODataset, ZDataset,
  frxExportXLS, frxClass, frxExportBaseDialog, frxExportPDF, frxDBSet,
  Vcl.DBCtrls,comobj;

type
  TEstadisticas = class(TForm)
    qestadisticasgrupo: TZReadOnlyQuery;
    qestadisticas: TZReadOnlyQuery;
    dsqestadisticasgrupo: TDataSource;
    Panel1: TPanel;
    Label1: TLabel;
    fdesde: TDateTimePicker;
    Label2: TLabel;
    fhasta: TDateTimePicker;
    qestadisticasgrupoconcepto: TWideStringField;
    qestadisticasgrupodescripcion: TWideStringField;
    qestadisticasgrupototal: TFloatField;
    qestadisticasgrupodescpagado: TStringField;
    qestadisticasgrupopagado: TIntegerField;
    DBGrid2: TDBGrid;
    chkpagado: TCheckBox;
    dsqestadisticas: TDataSource;
    qestadisticasid: TIntegerField;
    qestadisticasidc: TIntegerField;
    qestadisticasfecharecibo: TDateField;
    qestadisticasfechacobro: TDateField;
    qestadisticasconcepto: TWideStringField;
    qestadisticasimporte: TFloatField;
    qestadisticasdescuento: TIntegerField;
    qestadisticasimportefinal: TFloatField;
    qestadisticasdescripcion: TWideStringField;
    qestadisticasnombre: TWideStringField;
    qestadisticasapellidos: TWideStringField;
    qestadisticasesmaterial: TStringField;
    qestadisticasdespagado: TStringField;
    qestadisticasmaterial: TIntegerField;
    qestadisticasforma_pago: TIntegerField;
    qestadisticaspagado: TIntegerField;
    chkmaterial: TCheckBox;
    chkcursos: TCheckBox;
    infestadisticas: TfrxReport;
    infqestadisticas: TfrxDBDataset;
    frxPDFExport1: TfrxPDFExport;
    frxXLSExport1: TfrxXLSExport;
    Button1: TButton;
    Label3: TLabel;
    qformaspago: TZReadOnlyQuery;
    dsqformaspago: TDataSource;
    qformaspagoid: TIntegerField;
    qformaspagoide: TIntegerField;
    qformaspagoids: TWideStringField;
    qformaspagodescripcion: TWideStringField;
    qformaspagoactivo: TIntegerField;
    qformaspagodomiciliado: TIntegerField;
    comboformapago: TDBLookupComboBox;
    Panel2: TPanel;
    DBGrid1: TDBGrid;
    DBGrid3: TDBGrid;
    qestadisticasgrupofp: TZReadOnlyQuery;
    dsqestadisticasgrupofp: TDataSource;
    qestadisticasgrupofpdescripcion: TWideStringField;
    qestadisticasgrupofptotal: TFloatField;
    qestadisticasgrupofppagado: TIntegerField;
    qestadisticasgrupofpdescpagado: TStringField;
    Button2: TButton;
    Label4: TLabel;
    Label5: TLabel;
    infqestadisticasgrupo: TfrxDBDataset;
    qnumalumnos: TZReadOnlyQuery;
    qnumclientes: TZReadOnlyQuery;
    qnumalumnosnum_alumnos: TLargeintField;
    qnumclientesnumclientes: TLargeintField;
    Label6: TLabel;
    DBText1: TDBText;
    Label7: TLabel;
    DBText2: TDBText;
    dsnumalumnos: TDataSource;
    dsnumclientes: TDataSource;
    qtotales: TZReadOnlyQuery;
    Button3: TButton;
    SaveDialog1: TSaveDialog;
    chkcobros: TCheckBox;
    qestadisticasalumno: TWideStringField;
    procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure FormKeyPress(Sender: TObject; var Key: Char);
    procedure qestadisticasgrupoCalcFields(DataSet: TDataSet);
    procedure qestadisticasCalcFields(DataSet: TDataSet);
    procedure FormShow(Sender: TObject);
    procedure fdesdeChange(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure qestadisticasgrupofpCalcFields(DataSet: TDataSet);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure DBGrid2TitleClick(Column: TColumn);
  private
    { Private declarations }
  public
    { Public declarations }
     procedure ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar = nil);

  end;

var
  Estadisticas: TEstadisticas;

implementation

{$R *.dfm}

uses ESTGRUPOS;
procedure Testadisticas.ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar);

  procedure ProgressBarInit;
  begin
    ProgressBarXls.Max := DBGrid.DataSource.DataSet.RecordCount;
    ProgressBarXls.Position := 0;
    ProgressBarXls.Visible := True;
  end;

const
  xlWBATworksheet = -4167;
var
  Excel, WorkBook, WorkSheet: OleVariant;
  I, J: Integer;
  PBookmark: TBookmark;
begin
  // Guardar la posición en la DB y desactivar que se mueva el registro
  PBookmark := DBGrid.DataSource.DataSet.GetBookmark;
  DBGrid.DataSource.DataSet.DisableControls;
  DBGrid.DataSource.DataSet.First;

  // Comprobar si existe el component TProgressBar
  if (ProgressBarXls <> nil) then
    ProgressBarInit;

  // Crear instancia de la aplicación Excel
  Excel := CreateOleObject('Excel.Application');

  // Evitar que nos pregunte si deseamos sobreescribir el archivo
  Excel.DisplayAlerts := False;

  // Agregar libro de trabajo
  WorkBook := Excel.Workbooks.Add(xlWBATWorksheet);

  // Tomar una referencia a la hoja creada
  WorkSheet := WorkBook.WorkSheets[1];

  // Se  describe el nombre de la hoja
  WorkSheet.Name := SheetName;

  // Llenamos las celdas
  //    Toma en cuenta que las columnas y filas empiezan en 1, y que en el
  // WorkSheet.Cells[I, J], I es la fila y J es la columna.

  //   Extrae los nombres de los campos del DBGrid y los coloca en el primer registro,
  // excluyendo los campos que están ocultos
  for J := 0 to DBGrid.FieldCount -1 do
    if DBGrid.Fields[J].Visible then
    begin
      // Poner la fuente de letra en Negrita
      WorkSheet.Cells[1, J +1].Font.Bold := True;
      // Centrar la celda
//      WorkSheet.Cells[1, J +1].HorizontalAlignment := xlCenter;
      // Asignamos Valor del titulo del DBrid
      WorkSheet.Cells[1, J +1] := DBGrid.Columns[J].Title.Caption;
    end;

  // Guardar los registros
  for I := 0 to DBGrid.DataSource.DataSet.RecordCount -1 do
  begin
    // Identificamos los campos y lo grabamos según su tipo
    for J := 0 to DBGrid.FieldCount -1 do
      case DBGrid.Fields[J].DataType of
        ftAutoInc, ftBytes, ftInteger, ftSmallint, ftWord: // Auto o Numérico
          WorkSheet.Cells[I +2, J +1] := DBGrid.Fields[J].AsInteger;
        ftBCD, ftFloat, ftCurrency: // Numérico con decimales
          WorkSheet.Cells[I +2, J +1] := DBGrid.Fields[J].AsFloat;
        ftDateTime, ftDate, ftTime: // Fecha y Hora
          WorkSheet.Cells[I +2, J +1] := DBGrid.Fields[J].AsDateTime;
        else // Todo lo demas caracteres
          WorkSheet.Cells[I +2, J +1] := DBGrid.Fields[J].AsString;
      end;

    // Saltamos de registro
    DBGrid.DataSource.DataSet.Next;

    // Comprobar si existe el component TProgressBar
    if (ProgressBarXls <> nil) then
      ProgressBarXls.Position := ProgressBarXls.Position +1;
  end;

  // Comprobar si existe el component TProgressBar
  if (ProgressBarXls <> nil) then
    ProgressBarXls.Visible := False;

  // Redimensionar todas las celdas para que esten según su tamaño
  WorkSheet.Cells.Columns.AutoFit;

  // Guardar el archivo
  WorkBook.SaveAs(FileNameXLS);

  // Cierra el archivo
  WorkBook.Close(FileNameXLS);

  // Salir de Excel
  Excel.Quit;

  // posicionar el registro donde estaba
  DBGrid.DataSource.DataSet.GotoBookmark(PBookmark);
  DBGrid.DataSource.DataSet.FreeBookmark(PBookmark);
  DBGrid.DataSource.DataSet.EnableControls;
end;

procedure TEstadisticas.Button1Click(Sender: TObject);
var pfdesde,pfhasta:tdate;
    ppagado,pmaterial,pformapago:string;
begin
    pfdesde:=fdesde.Date;
    pfhasta:=fhasta.Date;
    if chkpagado.Checked then ppagado:='0' else ppagado:='%';
    if (chkmaterial.Checked=true) and (chkcursos.Checked=true) then pmaterial:='%';
    if (chkmaterial.Checked=true) and (chkcursos.Checked=false) then pmaterial:='1';
    if (chkmaterial.Checked=false) and (chkcursos.Checked=true) then pmaterial:='0';
    if qformaspagoid.AsInteger=-1 then pformapago:='%' else pformapago:=qformaspagoid.AsString;
    if chkcobros.Checked then
    begin
        qestadisticas.sql.Clear;
        qestadisticas.SQL.Add('SELECT c.id,c.idc,c.fecharecibo,c.fechacobro,c.concepto,c.importe,c.material,c.forma_pago,c.descuento,c.importefinal,c.pagado,fp.descripcion,cl.nombre,cl.apellidos,');
        qestadisticas.SQL.Add('(select concat(apellidos,'+''''+' '+''''+',nombre) from alumnos where id=c.ida) as alumno FROM formagest.cobros c, formagest.formas_pago fp, clientes cl where  ');
        qestadisticas.SQL.Add(' cl.ide=c.ide and cl.id=c.idc and fechacobro>=:PDESDE and fechacobro<=:PHASTA and pagado like(:PPAGADO) and ');
        qestadisticas.SQL.Add(' material like (:PMATERIAL) and  c.forma_pago like (:PFORMAPAGO) and  c.forma_pago=fp.id  order by concepto,descripcion,idc,id');
        qestadisticas.Prepare;
        qestadisticas.ParamByName('PDESDE').Asdate:=pfdesde;
        qestadisticas.ParamByName('PHASTA').Asdate:=pfhasta;
        qestadisticas.ParamByName('PPAGADO').Asstring:='1';//ppagado;
        qestadisticas.ParamByName('PMATERIAL').Asstring:=pmaterial;
        qestadisticas.ParamByName('PFORMAPAGO').AsString:=pformapago;
        qestadisticas.open;
    end else
    begin
        qestadisticas.close;
        qestadisticas.SQL.Clear;
        qestadisticas.SQL.Add('SELECT c.id,c.idc,c.fecharecibo,c.fechacobro,c.concepto,c.importe,c.material,c.forma_pago,c.descuento,c.importefinal,c.pagado,fp.descripcion,cl.nombre,cl.apellidos,');
        qestadisticas.SQL.Add('(select concat(apellidos,'+''''+' '+''''+',nombre) from alumnos where id=c.ida) as alumno FROM formagest.cobros c, formagest.formas_pago fp, clientes cl ');
        qestadisticas.SQL.Add(' where cl.ide=c.ide and cl.id=c.idc and fecharecibo>=:PDESDE and fecharecibo<=:PHASTA and pagado like(:PPAGADO) and material like (:PMATERIAL) and  c.forma_pago like (:PFORMAPAGO) and  c.forma_pago=fp.id order by pagado,descripcion,concepto,apellidos');
        qestadisticas.Prepare;
        qestadisticas.ParamByName('PDESDE').AsDate:=pfdesde;
        qestadisticas.ParamByName('PHASTA').AsDate:=pfhasta;
        qestadisticas.ParamByName('PPAGADO').Asstring:=ppagado;
        qestadisticas.ParamByName('PMATERIAL').Asstring:=pmaterial;
        qestadisticas.ParamByName('PFORMAPAGO').AsString:=pformapago;
        qestadisticas.open;
    end;
    infqestadisticasgrupo.Datasource:=dsqestadisticasgrupo;
    infqestadisticas.Datasource:=dsqestadisticas;
    infestadisticas.Report.Clear;
    infestadisticas.LoadFromFile('c:\formagest\informes\infestadisticas2.fr3');
    infestadisticas.ShowReport();
end;

procedure TEstadisticas.Button2Click(Sender: TObject);
var pfdesde,pfhasta:tdate;
    ppagado,pmaterial,pformapago:string;
begin
    pfdesde:=fdesde.Date;
    pfhasta:=fhasta.Date;
    if chkpagado.Checked then ppagado:='0' else ppagado:='%';
    if (chkmaterial.Checked=true) and (chkcursos.Checked=true) then pmaterial:='%';
    if (chkmaterial.Checked=true) and (chkcursos.Checked=false) then pmaterial:='1';
    if (chkmaterial.Checked=false) and (chkcursos.Checked=true) then pmaterial:='0';
    if qformaspagoid.AsInteger=-1 then pformapago:='%' else pformapago:=qformaspagoid.AsString;
    qestadisticas.close;
    qestadisticas.SQL.Clear;
    qestadisticas.SQL.Add('SELECT c.id,c.idc,c.fecharecibo,c.fechacobro,c.concepto,c.importe,c.material,c.forma_pago,c.descuento,c.importefinal,c.pagado,fp.descripcion,cl.nombre,cl.apellidos,');
    qestadisticas.SQL.Add('(select concat(apellidos,'+''''+' '+''''+',nombre) from alumnos where id=c.ida) as alumno FROM formagest.cobros c, formagest.formas_pago fp, clientes cl ');
    qestadisticas.SQL.Add(' where cl.ide=c.ide and cl.id=c.idc and fecharecibo>=:PDESDE and fecharecibo<=:PHASTA and pagado like(:PPAGADO) and material like (:PMATERIAL) and  c.forma_pago like (:PFORMAPAGO) and  c.forma_pago=fp.id  order by descripcion,idc,id');
    qestadisticas.Prepare;
    qestadisticas.ParamByName('PDESDE').AsDate:=pfdesde;
    qestadisticas.ParamByName('PHASTA').AsDate:=pfhasta;
    qestadisticas.ParamByName('PPAGADO').Asstring:=ppagado;
    qestadisticas.ParamByName('PMATERIAL').Asstring:=pmaterial;
    qestadisticas.ParamByName('PFORMAPAGO').AsString:=pformapago;
    qestadisticas.open;

    infqestadisticas.Datasource:=dsqestadisticas;
    infestadisticas.Report.Clear;
    infestadisticas.LoadFromFile('c:\formagest\informes\infestadisticasfp.fr3');
    infestadisticas.ShowReport();
end;

procedure TEstadisticas.Button3Click(Sender: TObject);
var  archivo:string;
begin
    savedialog1.FileName:='COBROSDETALLE.xlsx';
    savedialog1.Execute();
    archivo:=savedialog1.FileName;
    try
    Exportaraexcel(archivo,'DETALLE DE COBROS',DBGRID2);
    finally
      showmessage('Los datos han sido exportados correctamente a '+archivo);
    end;
end;

procedure TEstadisticas.DBGrid2TitleClick(Column: TColumn);
var
  st,ST2:ZAbstractRODataset.TSortType;
begin
      st:=qestadisticas.SortType;
      If st = stAscending then
      begin
       qestadisticas.sorttype:=stDescending;
      end else
      begin
        qestadisticas.sorttype:=stAscending;
      end;
      qestadisticas.SortedFields:=Column.FieldName +';apellidos';
//      qestadisticas.refresh;
      dsqestadisticas.DataSet.First;

end;

procedure TEstadisticas.fdesdeChange(Sender: TObject);
var pfdesde,pfhasta:tdate;
    ppagado,pmaterial,pformapago:string;
    wanyo,wmes,wdia:word;
begin
    pfdesde:=fdesde.Date;
    pfhasta:=fhasta.Date;
    if chkpagado.Checked then ppagado:='0' else ppagado:='%';
    if (chkmaterial.Checked=true) and (chkcursos.Checked=true) then pmaterial:='%';
    if (chkmaterial.Checked=true) and (chkcursos.Checked=false) then pmaterial:='1';
    if (chkmaterial.Checked=false) and (chkcursos.Checked=true) then pmaterial:='0';
    if qformaspagoid.AsInteger=-1 then pformapago:='%' else pformapago:=qformaspagoid.AsString;
    if chkcobros.Checked then
    begin
        qestadisticasgrupo.SQL.Clear;
        qestadisticasgrupo.SQL.Add('SELECT concepto,fp.descripcion,sum(importefinal) as total,pagado FROM cobros c, formas_pago fp where fechacobro>=:PDESDE and fechacobro<=:PHASTA and pagado like(:PPAGADO) and material like (:PMATERIAL) ');
        qestadisticasgrupo.sql.Add(' and  c.forma_pago like (:PFORMAPAGO) and c.forma_pago=fp.id group by concepto,forma_pago,pagado order by pagado,forma_pago,concepto');
        qestadisticasgrupo.Prepare;
        qestadisticasgrupo.ParamByName('PDESDE').Asdate:=pfdesde;
        qestadisticasgrupo.ParamByName('PHASTA').AsDate:=pfhasta;
        qestadisticasgrupo.ParamByName('PPAGADO').Asstring:='1';//ppagado;
        qestadisticasgrupo.ParamByName('PMATERIAL').Asstring:=pmaterial;
        qestadisticasgrupo.ParamByName('PFORMAPAGO').AsString:=pformapago;
        qestadisticasgrupo.open;
        qestadisticasgrupofp.SQL.Clear;
        qestadisticasgrupofp.SQL.Add('SELECT fp.descripcion,sum(importefinal) as total,pagado FROM cobros c, formas_pago fp where  fechacobro>=:PDESDE and fechacobro<=:PHASTA and pagado like(:PPAGADO) ');
        qestadisticasgrupofp.sql.add(' and material like (:PMATERIAL) and  c.forma_pago like (:PFORMAPAGO) and c.forma_pago=fp.id group by forma_pago,pagado order by fp.descripcion');
        qestadisticasgrupofp.Prepare;
        qestadisticasgrupofp.ParamByName('PDESDE').AsDate:=pfdesde;
        qestadisticasgrupofp.ParamByName('PHASTA').AsDate:=pfhasta;
        qestadisticasgrupofp.ParamByName('PPAGADO').Asstring:='1';//ppagado;
        qestadisticasgrupofp.ParamByName('PMATERIAL').Asstring:=pmaterial;
        qestadisticasgrupofp.ParamByName('PFORMAPAGO').AsString:=pformapago;
        qestadisticasgrupofp.open;
        qestadisticas.sql.Clear;
        qestadisticas.SQL.Add('SELECT c.id,c.idc,c.fecharecibo,c.fechacobro,c.concepto,c.importe,c.material,c.forma_pago,c.descuento,c.importefinal,c.pagado,fp.descripcion,cl.nombre,cl.apellidos, ');
        qestadisticas.SQL.Add('(select concat(apellidos,'+''''+' '+''''+',nombre) from alumnos where id=c.ida) as alumno FROM formagest.cobros c, formagest.formas_pago fp, clientes cl where  ');
        qestadisticas.SQL.Add(' cl.ide=c.ide and cl.id=c.idc and fechacobro>=:PDESDE and fechacobro<=:PHASTA and pagado like(:PPAGADO) and ');
        qestadisticas.SQL.Add(' material like (:PMATERIAL) and  c.forma_pago like (:PFORMAPAGO) and  c.forma_pago=fp.id  order by concepto,descripcion,idc,id');
        qestadisticas.Prepare;
        qestadisticas.ParamByName('PDESDE').Asdate:=pfdesde;
        qestadisticas.ParamByName('PHASTA').Asdate:=pfhasta;
        qestadisticas.ParamByName('PPAGADO').Asstring:='1';//ppagado;
        qestadisticas.ParamByName('PMATERIAL').Asstring:=pmaterial;
        qestadisticas.ParamByName('PFORMAPAGO').AsString:=pformapago;
        qestadisticas.open;
    end else
    begin
        qestadisticasgrupo.SQL.Clear;
        qestadisticasgrupo.SQL.Add('SELECT concepto,fp.descripcion,sum(importefinal) as total,pagado FROM cobros c, formas_pago fp where fecharecibo>=:PDESDE and fecharecibo<=:PHASTA and pagado like(:PPAGADO) and material like (:PMATERIAL) ');
        qestadisticasgrupo.sql.Add(' and  c.forma_pago like (:PFORMAPAGO) and c.forma_pago=fp.id group by concepto,forma_pago,pagado order by pagado,forma_pago,concepto');
        qestadisticasgrupo.Prepare;
        qestadisticasgrupo.ParamByName('PDESDE').Asdate:=pfdesde;
        qestadisticasgrupo.ParamByName('PHASTA').Asdate:=pfhasta;
        qestadisticasgrupo.ParamByName('PPAGADO').Asstring:=ppagado;
        qestadisticasgrupo.ParamByName('PMATERIAL').Asstring:=pmaterial;
        qestadisticasgrupo.ParamByName('PFORMAPAGO').AsString:=pformapago;
        qestadisticasgrupo.open;
        qestadisticasgrupofp.SQL.Clear;
        qestadisticasgrupofp.SQL.Add('SELECT fp.descripcion,sum(importefinal) as total,pagado FROM cobros c, formas_pago fp where  fecharecibo>=:PDESDE and fecharecibo<=:PHASTA and pagado like(:PPAGADO) ');
        qestadisticasgrupofp.sql.add(' and material like (:PMATERIAL) and  c.forma_pago like (:PFORMAPAGO) and c.forma_pago=fp.id group by forma_pago,pagado order by fp.descripcion');
        qestadisticasgrupofp.Prepare;
        qestadisticasgrupofp.ParamByName('PDESDE').Asdate:=pfdesde;
        qestadisticasgrupofp.ParamByName('PHASTA').Asdate:=pfhasta;
        qestadisticasgrupofp.ParamByName('PPAGADO').Asstring:=ppagado;
        qestadisticasgrupofp.ParamByName('PMATERIAL').Asstring:=pmaterial;
        qestadisticasgrupofp.ParamByName('PFORMAPAGO').AsString:=pformapago;
        qestadisticasgrupofp.open;
        qestadisticas.sql.Clear;
        qestadisticas.SQL.Add('SELECT c.id,c.idc,c.fecharecibo,c.fechacobro,c.concepto,c.importe,c.material,c.forma_pago,c.descuento,c.importefinal,c.pagado,fp.descripcion,cl.nombre,cl.apellidos, ');
        qestadisticas.SQL.Add('(select concat(apellidos,'+''''+' '+''''+',nombre) from alumnos where id=c.ida) as alumno FROM formagest.cobros c, formagest.formas_pago fp, clientes cl where  ');
        qestadisticas.SQL.Add(' cl.ide=c.ide and cl.id=c.idc and fecharecibo>=:PDESDE and fecharecibo<=:PHASTA and pagado like(:PPAGADO) and ');
        qestadisticas.SQL.Add(' material like (:PMATERIAL) and  c.forma_pago like (:PFORMAPAGO) and  c.forma_pago=fp.id  order by concepto,descripcion,idc,id');
        qestadisticas.Prepare;
        qestadisticas.ParamByName('PDESDE').Asdate:=pfdesde;
        qestadisticas.ParamByName('PHASTA').Asdate:=pfhasta;
        qestadisticas.ParamByName('PPAGADO').Asstring:=ppagado;
        qestadisticas.ParamByName('PMATERIAL').Asstring:=pmaterial;
        qestadisticas.ParamByName('PFORMAPAGO').AsString:=pformapago;
        qestadisticas.open;
    end;
end;

procedure TEstadisticas.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
    if (activecontrol is tdbgrid) then
    begin
        if Key = 13 then Key :=9;
    end;
end;

procedure TEstadisticas.FormKeyPress(Sender: TObject; var Key: Char);
var formatos:tformatsettings;
punto:string;
begin
    GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos);
    punto:=formatos.DecimalSeparator;
    if punto=',' then
    begin
        key:=upcase(key);
        {if (key='.') and (activecontrol is tdbedit) then
        begin
           if  (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=','
        end;}
        if (key='.') and (activecontrol is tdbgrid) then
        begin
            key:=',';
        end;
    end;
    if (activecontrol is tdbgrid) then
    begin
        if Key = #13 then Key :=#9;
    end;

    if (key=#13) then
    begin
        Perform(WM_NextDLGCtl,0,0);
        key:=#0;
    end;
end;

procedure TEstadisticas.FormShow(Sender: TObject);
var pfdesde,pfhasta:tdate;
    ppagado,pmaterial,pformapago:string;
begin
    qformaspago.Open;
    comboformapago.KeyValue:=qformaspagoid.AsInteger;
    fdesde.Date:=date();
    fhasta.Date:=date();
    pfdesde:=fdesde.Date;
    pfhasta:=fhasta.Date;
    if chkpagado.Checked then ppagado:='0' else ppagado:='%';
    if (chkmaterial.Checked=true) and (chkcursos.Checked=true) then pmaterial:='%';
    if (chkmaterial.Checked=true) and (chkcursos.Checked=false) then pmaterial:='1';
    if (chkmaterial.Checked=false) and (chkcursos.Checked=true) then pmaterial:='0';
    if qformaspagoid.AsInteger=-1 then pformapago:='%' else pformapago:=qformaspagoid.AsString;
    qestadisticasgrupo.SQL.Clear;
    qestadisticasgrupo.SQL.Add('SELECT concepto,fp.descripcion,sum(importefinal) as total,pagado FROM cobros c, formas_pago fp where fecharecibo>=:PDESDE and fecharecibo<=:PHASTA and pagado like(:PPAGADO) and material like (:PMATERIAL) ');
    qestadisticasgrupo.sql.Add(' and  c.forma_pago like (:PFORMAPAGO) and c.forma_pago=fp.id group by concepto,forma_pago,pagado order by pagado,forma_pago,concepto');
    qestadisticasgrupo.Prepare;
    qestadisticasgrupo.ParamByName('PDESDE').AsDate:=pfdesde;
    qestadisticasgrupo.ParamByName('PHASTA').AsDate:=pfhasta;
    qestadisticasgrupo.ParamByName('PPAGADO').Asstring:=ppagado;
    qestadisticasgrupo.ParamByName('PMATERIAL').Asstring:=pmaterial;
    qestadisticasgrupo.ParamByName('PFORMAPAGO').AsString:=pformapago;
    qestadisticasgrupo.open;
    qestadisticasgrupofp.SQL.Clear;
    qestadisticasgrupofp.SQL.Add('SELECT fp.descripcion,sum(importefinal) as total,pagado FROM cobros c, formas_pago fp where  fecharecibo>=:PDESDE and fecharecibo<=:PHASTA and pagado like(:PPAGADO) ');
    qestadisticasgrupofp.sql.add(' and material like (:PMATERIAL) and  c.forma_pago like (:PFORMAPAGO) and c.forma_pago=fp.id group by forma_pago,pagado order by fp.descripcion');
    qestadisticasgrupofp.Prepare;
    qestadisticasgrupofp.ParamByName('PDESDE').AsDate:=pfdesde;
    qestadisticasgrupofp.ParamByName('PHASTA').AsDate:=pfhasta;
    qestadisticasgrupofp.ParamByName('PPAGADO').Asstring:=ppagado;
    qestadisticasgrupofp.ParamByName('PMATERIAL').Asstring:=pmaterial;
    qestadisticasgrupofp.ParamByName('PFORMAPAGO').AsString:=pformapago;
    qestadisticasgrupofp.open;
    qestadisticas.sql.Clear;
    qestadisticas.SQL.Add('SELECT c.id,c.idc,c.fecharecibo,c.fechacobro,c.concepto,c.importe,c.material,c.forma_pago,c.descuento,c.importefinal,c.pagado,fp.descripcion,cl.nombre,cl.apellidos, ');
    qestadisticas.SQL.Add('(select concat(apellidos,'+''''+' '+''''+',nombre) from alumnos where id=c.ida) as alumno FROM formagest.cobros c, formagest.formas_pago fp, clientes cl where  ');
    qestadisticas.SQL.Add(' cl.ide=c.ide and cl.id=c.idc and fecharecibo>=:PDESDE and fecharecibo<=:PHASTA and pagado like(:PPAGADO) and ');
    qestadisticas.SQL.Add(' material like (:PMATERIAL) and  c.forma_pago like (:PFORMAPAGO) and  c.forma_pago=fp.id  order by concepto,descripcion,idc,id');
    qestadisticas.Prepare;
    qestadisticas.ParamByName('PDESDE').AsDate:=pfdesde;
    qestadisticas.ParamByName('PHASTA').AsDate:=pfhasta;
    qestadisticas.ParamByName('PPAGADO').Asstring:=ppagado;
    qestadisticas.ParamByName('PMATERIAL').Asstring:=pmaterial;
    qestadisticas.ParamByName('PFORMAPAGO').AsString:=pformapago;
    qestadisticas.open;
    qnumclientes.open;
    qnumalumnos.open;
end;

procedure TEstadisticas.qestadisticasCalcFields(DataSet: TDataSet);
begin
    if qestadisticaspagado.asinteger=0 then qestadisticasdespagado.Value:='PENDIENTE';
    if qestadisticaspagado.asinteger=1 then qestadisticasdespagado.Value:='COBRADO';
    if qestadisticasmaterial.asinteger=0 then qestadisticasesmaterial.value:='NO';
    if qestadisticasmaterial.asinteger=1 then qestadisticasesmaterial.value:='SI';
end;

procedure TEstadisticas.qestadisticasgrupoCalcFields(DataSet: TDataSet);
begin
    if qestadisticasgrupopagado.asinteger=0 then qestadisticasgrupodescpagado.Value:='PENDIENTES';
    if qestadisticasgrupopagado.asinteger=1 then qestadisticasgrupodescpagado.Value:='COBRADOS';
end;

procedure TEstadisticas.qestadisticasgrupofpCalcFields(DataSet: TDataSet);
begin
    if qestadisticasgrupofppagado.asinteger=0 then qestadisticasgrupofpdescpagado.Value:='PENDIENTES';
    if qestadisticasgrupofppagado.asinteger=1 then qestadisticasgrupofpdescpagado.Value:='COBRADOS';
end;

end.
