unit consulta;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogos,
  Grids, StdCtrls, ExtCtrls, ComCtrls, Tabnotbk, Db, DBTables, Buttons,
  DBCtrls,Conver,checa, Dialogs, Gauges;

type
  TFormaConsulta = class(TForm)
    TablaConsulta: TTable;
    RutaCampos: TEdit;
    numcampo: TLabel;
    Destino: TEdit;
    Fuente1: TDataSource;
    TipoVista: TEdit;
    AbreArchivo: TOpenDialog;
    AreaClaves: TListBox;
    ListaCondiciones: TStringGrid;
    ListaCampos: TStringGrid;
    ReporteDe: TGroupBox;
    Archi: TLabel;
    Descripcion: TMemo;
    Archivo: TComboBox;
    Bevel1: TBevel;
    De: TEdit;
    Label1: TLabel;
    Label2: TLabel;
    Hasta: TEdit;
    Concentrar: TRadioButton;
    Detallar: TRadioButton;
    Bevel2: TBevel;
    Condiciones: TStringGrid;
    Label5: TLabel;
    Bevel3: TBevel;
    ListaOpcion: TListBox;
    Ejecutar: TSpeedButton;
    SpeedButton2: TSpeedButton;
    Shape1: TShape;
    Panel3: TPanel;
    Bevel20: TBevel;
    Bevel21: TBevel;
    Bevel22: TBevel;
    Panel4: TPanel;
    Label3: TLabel;
    Label4: TLabel;
    Avance: TGauge;
    procedure CondicionesClick(Sender: TObject);
    procedure ListaOpcionDblClick(Sender: TObject);
    procedure EjecutarClick(Sender: TObject);
    procedure FormActivate(Sender: TObject);
    procedure SpeedButton2Click(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure CondicionesKeyUp(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure FormCreate(Sender: TObject);
    procedure SpeedButton7Click(Sender: TObject);
    procedure ConcentrarClick(Sender: TObject);
    procedure ArchivoChange(Sender: TObject);
    procedure Panel4Click(Sender: TObject);
    procedure Panel3MouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure Label4MouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
  private
    { Private declarations }
  public
    { Public declarations }
  end;


type
 ArchivoLineas=Record
 linea:string[125];
 end;


var
  FormaConsulta: TFormaConsulta;
  n,ncond:integer;


procedure leearchivocampos(inicio,fin:integer);
implementation

uses graficas, antgra;

{$R *.DFM}

procedure filtrabase;
begin
{Accept:=((DataSet['TIMOV_CC']='1')or(DataSet['TIMOV_CC']='2'));}

end;

procedure actualizaarchivo;
type
datos=record
archivo:String[60];
descrip:String[125];
end;
var
dat,dat2:datos;
arch,arch2:file of datos;
i:integer;
begin
with FormaConsulta do
begin
{MuestraMensaje(RutaCampos.Text);}
if FileExists(RutaCampos.Text) then
begin
AssignFile (arch,RutaCampos.Text);
AssignFile(arch2,RutaCampos.Text+'2');
Rewrite(arch2);
Reset(arch);
ListaCampos.RowCount:=1;
for i:=0 to FileSize(arch)-1 do
begin
read(arch,dat);
{if FileExists(dat.}
end;
 closeFile(arch);
end;

end;
end;


procedure LimpiaListaCampos;
var
i,j:integer;
begin
With FormaConsulta do
begin

for j:=1 to ListaCampos.RowCount do
for i:=0 to ListaCampos.ColCount do
begin
ListaCampos.Cells[i,j]:='';

end;
end;

end;


procedure limpiacondiciones;
var
i,j:integer;
begin
With FormaConsulta do
begin
for j:=1 to ListaCondiciones.RowCount do
for i:=1 to ListaCondiciones.ColCount do
begin
ListaCondiciones.Cells[j,i]:='';

end;
for j:=1 to Condiciones.RowCount do
for i:=1 to Condiciones.ColCount do
begin
Condiciones.Cells[j,i]:='';

end;

end;
end;


procedure leearchivovista;
type
datos=record
archivo:String[60];
descrip:String[125];
end;
var
dat:datos;
arch:file of datos;
i:integer;
begin
with FormaConsulta do
begin
{MuestraMensaje('archivo '+leeruta+'\report\'+Archi.Caption);
AssignFile(arch,leeruta+'\report\'+Archi.Caption);}

if FileExists(Archivo.Text) then
begin
{AssignFile(arch,leeruta+'\report\'+Archi.Caption);}
{Archi.Caption:=Archivo.Text;}
{AssignFile(arch,Archi.Caption);}
{AssignFile(arch,Archivo.Text);}
{Reset(arch);
Seek(arch,Archivo.Items.IndexOf(Archivo.Text));
Read(arch,dat);
TipoVista.Text:=Dat.archivo;}
TipoVista.Text:=Archivo.Text;
Descripcion.Clear;

{Descripcion.lines.Add(Dat.Descrip);}
{ReporteDe.Caption:='Reporte de Clientes';}
{CloseFile(arch);}

end
else
begin
MuestraMensaje('El Archivo No Existe');

{actualizaarchivo;}
end;
end;
end;


Procedure concentra;
var
i,j,codigo,numcampo:integer;
valor:string[125];
arch,arch2:TextFile;
num:Real;
evaluar:Boolean;
begin
With FormaConsulta do
begin

{AssignFile(arch,Destino.Text);
Reset(arch);
AssignFile(arch2,'tempo.dat');
ReWrite(arch2);
numcampo:=1;

Readln(arch,valor);
valor:=valordecampo(numcampo,valor);
checarepeticion(numcampo,valor);}

end;
end;

function compara(valor:string;tipodato:string):Boolean;
var
tip,codigo,numi:integer;
numF:Real;
cadaux:String[1];
ultimo:char;
begin
if tipodato= 'ftSmallint' then tip:=1;
if tipodato= 'ftFloat' then tip:=2;
if tipodato= 'ftDate' then tip:=3;
if tipodato= 'ftString' then tip:=4;
case tip of
1:begin
  val(valor,numi,codigo);
  if codigo<>0 then compara:=False
  else compara:=True;
  end;
2:begin
  val(valor,numF,codigo);
  if codigo<>0 then compara:=False
  else compara:=True;

  end;
3:begin
   ultimo:=valor[Length(valor)];

  if  (ord(Char(ultimo))>47) and (ord(Char(ultimo))<58) then
  compara:=True
  else
  compara:=False;
  if ultimo='/' then compara:=True;

  end;
4:begin
  compara:=True;
  end;
end;
end;

procedure leearchivocampos(inicio,fin:integer);
{type
datoscampo=record
campo:String[12];
descripcion:String[40];
tipo:String[12];
longitud:Integer;
end;}

var
{dat:datoscampo;
arch:file of datoscampo;}
contador,i:integer;

begin
With FormaConsulta do
begin
LimpiaListaCampos;
ListaCampos.RowCount:=1;
contador:=0;
for i:=inicio to fin do
begin

ListaCampos.Cells[1,contador]:=leecampos(i,1);
ListaCampos.Cells[2,contador]:=leecampos(i,2);
ListaCampos.Cells[3,contador]:=leecampos(i,3);
ListaCampos.Cells[4,contador]:=leecampos(i,4);
ListaCampos.RowCount:=ListaCampos.RowCount+1;
if (leecampos(i,2)<>'')and (leecampos(i,2)<>'No Disponible') then
contador:=contador+1;
end;

end;

end;

procedure iniciabase;
begin
With FormaConsulta do
begin
TablaConsulta.Open;

end;
end;

procedure calculaparametros;
begin
With FormaConsulta do
begin
AreaClaves.Clear;
AreaClaves.Items.LoadFromFile(TipoVista.Text);
n:=AreaClaves.Items.Count;
end;
end;

function tipo(valor:string):integer;
var numi,codigo:integer;
    numf:Real;
    cadaux:String;
begin
if valor= 'ftSmallint' then tipo:=1;
if valor= 'ftFloat' then tipo:=2;
if valor= 'ftDate' then tipo:=3;
if valor= 'ftString' then tipo:=4;

end;



function restriccion(valor:string;ncond:integer):Boolean;
var
    tip,num,codigo,cam:Integer;
    condicion:Boolean;
    campo:String[1];
    cadaux:String[2];
    caso:char;
begin
with FormaConsulta do
begin
if ListaCondiciones.Cells[1,ncond]<>'' then
begin
valor:=TablaConsulta.FieldByName(ListaCondiciones.Cells[1,ncond]).AsString;

cadaux:=Condiciones.Cells[2,ncond];
caso:=cadaux[1];
if cadaux='>=' then caso:='Y';
if cadaux='<=' then caso:='Z';

if ListaCondiciones.Cells[5,ncond]='1' then
campo:=ListaCondiciones.Cells[3,ncond]
else
campo:=Condiciones.Cells[3,ncond];

case caso of

{***************}
'Y':begin
    if ListaCondiciones.Cells[5,ncond]='1' then cam:=1
    else
    cam:=0;
    tip:=tipo(ListaCondiciones.Cells[2,ncond]);
     condicion:=False;
     case tip of
     1:begin
       if cam=1 then
       if StrToInt(valor)>=TablaConsulta.FieldByName(ListaCondiciones.Cells[3,ncond]).AsInteger then condicion:=True;
       if cam<>1 then
       if StrToInt(valor)>=StrToInt(Condiciones.Cells[3,ncond]) then condicion:=True;
       end;

     2:begin
       if valor='' then valor:='0';
       if cam=1 then
       if StrToFloat(valor)>=TablaConsulta.FieldByName(ListaCondiciones.Cells[3,ncond]).AsFloat then condicion:=True;
       if cam<>1 then
       if StrToFloat(valor)>=StrToFloat(Condiciones.Cells[3,ncond]) then condicion:=True;
       end;

     3:begin
       if valor<>'' then
       begin
       if cam=1 then
       if StrToDateTime(valor)>=TablaConsulta.FieldByName(ListaCondiciones.Cells[3,ncond]).AsDateTime then condicion:=True;
       if cam<>1 then
       if StrToDateTime(valor)>=StrToDateTime(Condiciones.Cells[3,ncond]) then condicion:=True;
       end;
       end;


     4:if valor>=Condiciones.Cells[3,ncond] then condicion:=True;

     end;
    end;


{****************}

{***************}

'Z':begin

    if ListaCondiciones.Cells[5,ncond]='1' then cam:=1
    else
    cam:=0;
    tip:=tipo(ListaCondiciones.Cells[2,ncond]);
     condicion:=False;
     case tip of

     1:begin
       if cam=1 then
       if StrToInt(valor)<=TablaConsulta.FieldByName(ListaCondiciones.Cells[3,ncond]).AsInteger then condicion:=True;
       if cam<>1 then
       if StrToInt(valor)<=StrToInt(Condiciones.Cells[3,ncond]) then condicion:=True;
       end;

     2:begin
       if valor='' then valor:='0';
       if cam=1 then
       if StrToFloat(valor)<=TablaConsulta.FieldByName(ListaCondiciones.Cells[3,ncond]).AsFloat then condicion:=True;
       if cam<>1 then
       if StrToFloat(valor)<=StrToFloat(Condiciones.Cells[3,ncond]) then condicion:=True;
       end;

     3:begin
       if valor<>'' then
       begin
       if cam=1 then
       if StrToDateTime(valor)<=TablaConsulta.FieldByName(ListaCondiciones.Cells[3,ncond]).AsDateTime then condicion:=True;
       if cam<>1 then
       if StrToDateTime(valor)<=StrToDateTime(Condiciones.Cells[3,ncond]) then condicion:=True;
       end;
       end;


     4:if valor<=Condiciones.Cells[3,ncond] then condicion:=True;

     end;
    end;


{**************}



'=':begin
    if ListaCondiciones.Cells[5,ncond]='1' then cam:=1
    else
    cam:=0;
    tip:=tipo(ListaCondiciones.Cells[2,ncond]);
     condicion:=False;
     case tip of
     1:begin
       if cam=1 then
       if StrToInt(valor)=TablaConsulta.FieldByName(ListaCondiciones.Cells[3,ncond]).AsInteger then condicion:=True;
       if cam<>1 then
       if StrToInt(valor)=StrToInt(Condiciones.Cells[3,ncond]) then condicion:=True;
       end;

     2:begin
       if valor='' then valor:='0';
       if cam=1 then
       if StrToFloat(valor)=TablaConsulta.FieldByName(ListaCondiciones.Cells[3,ncond]).AsFloat then condicion:=True;
       if cam<>1 then
       if StrToFloat(valor)=StrToFloat(Condiciones.Cells[3,ncond]) then condicion:=True;
       end;

     3:begin
       if valor<>'' then
       begin
       if cam=1 then
       if StrToDateTime(valor)=TablaConsulta.FieldByName(ListaCondiciones.Cells[3,ncond]).AsDateTime then condicion:=True;
       if cam<>1 then
       if StrToDateTime(valor)=StrToDateTime(Condiciones.Cells[3,ncond]) then condicion:=True;
       end;
       end;


     4:if valor=Condiciones.Cells[3,ncond] then condicion:=True;

     end;
    end;

'<': begin
    if ListaCondiciones.Cells[5,ncond]='1' then cam:=1
    else
    cam:=0;
   tip:=tipo(ListaCondiciones.Cells[2,ncond]);
     condicion:=False;
     case tip of
     1:begin
       if valor='' then valor:='0';
       if cam=1 then
       if StrToInt(valor)<TablaConsulta.FieldByName(ListaCondiciones.Cells[3,ncond]).AsInteger then condicion:=True;
       if cam<>1 then
       if StrToInt(valor)<StrToInt(Condiciones.Cells[3,ncond]) then condicion:=True;
       end;
     2:begin
       if valor='' then valor:='0';
       if cam=1 then
       if StrToFloat(valor)<TablaConsulta.FieldByName(ListaCondiciones.Cells[3,ncond]).AsFloat then condicion:=True;
       if cam<>1 then
       if StrToFloat(valor)<StrToFloat(Condiciones.Cells[3,ncond]) then condicion:=True;
       end;
     3:begin
       if valor<>'' then
       begin
        if cam=1 then
       if StrToDateTime(valor)<TablaConsulta.FieldByName(ListaCondiciones.Cells[3,ncond]).AsDateTime then condicion:=True;
       if cam<>1 then
       if StrToDateTime(valor)<StrToDateTime(Condiciones.Cells[3,ncond]) then condicion:=True;
       end;
       end;
     4:if valor<Condiciones.Cells[3,ncond] then condicion:=True;

     end;
    end;

'>': begin
    if ListaCondiciones.Cells[5,ncond]='1' then cam:=1
    else
    cam:=0;
   tip:=tipo(ListaCondiciones.Cells[2,ncond]);
     condicion:=False;
     case tip of
     1:begin
     if valor='' then valor:='0';
      if cam=1 then
       if StrToInt(valor)>TablaConsulta.FieldByName(ListaCondiciones.Cells[3,ncond]).AsInteger then condicion:=True
       else
     if StrToInt(valor)>StrToInt(Condiciones.Cells[3,ncond]) then condicion:=True;
     end;
     2:begin
       if valor='' then valor:='0';
       if cam=1 then
       if StrToFloat(valor)>TablaConsulta.FieldByName(ListaCondiciones.Cells[3,ncond]).AsFloat then condicion:=True;
       if cam<>1 then
       if StrToFloat(valor)>StrToFloat(Condiciones.Cells[3,ncond]) then condicion:=True;
       end;
     3:begin
       if valor<>'' then
       begin
       if cam=1 then
       if StrToDateTime(valor)>TablaConsulta.FieldByName(ListaCondiciones.Cells[3,ncond]).AsDateTime then condicion:=True;
       if cam<>1 then
       if StrToDateTime(valor)>StrToDateTime(Condiciones.Cells[3,ncond]) then condicion:=True;
       end;
       end;
     4:if valor>Condiciones.Cells[3,ncond] then condicion:=True;

     end;
    end;

end;
restriccion:=Condicion;
end;
end;
end;



procedure generareporte;
var

i,j,codigo,tamodatos,cuenta:longint;
valor:string[125];
arch:TextFile;
num:Real;
evaluar:Boolean;
begin
With FormaConsulta do
begin
AssignFile(arch,Destino.Text);
ReWrite(arch);
{*****escribe encabezados******}
i:=3;
while i<n do
begin
Write(arch,AreaClaves.Items[i]+char(9));
i:=i+4;
end;
writeln(arch,'');
i:=0;
while i<n-1 do
begin
Write(arch,AreaClaves.Items[i+2]+char(9));
i:=i+4;
end;
writeln(arch,'');
{********************}
TablaConsulta.FindNearest([De.Text]);
De.Text:=TablaConsulta.Fields[StrToInt(numcampo.Caption)].AsString;
TablaConsulta.FindNearest([Hasta.Text]);
Hasta.Text:=TablaConsulta.Fields[StrToInt(numcampo.Caption)].AsString;
TablaConsulta.SetRange([De.Text],[Hasta.Text]);
TablaConsulta.First;
tamodatos:=TablaConsulta.RecordCount;
Avance.Progress:=0;
cuenta:=0;
while not TablaConsulta.Eof do
begin
evaluar:=True;
for i:=1 to ncond do
begin
if ListaCondiciones.Cells[1,i]<>'' then
evaluar:=evaluar and restriccion(TablaConsulta.FieldByName(ListaCondiciones.Cells[1,i]).AsString,i);
end;

if evaluar then
begin
{***************************************************}
i:=0;
while i<n-1 do
begin
valor:=TablaConsulta.FieldByName(AreaClaves.Items[i]).AsString;

if StrToInt(AreaClaves.Items[i+2])=0 then
begin
if valor='' then valor:='0';
 Val(valor,num,codigo);
  if codigo=0 then
   valor:=convierte('###,###,##0.00',valor,'');
  { Str(StrToFloat(valor):12:2,valor);}
end;
i:=i+4;
write(arch,valor+char(9));
end;
writeln(arch,'');
{*********************************************}
end;
TablaConsulta.Next;
Avance.Progress:=Trunc((cuenta/tamodatos)*100);
cuenta:=cuenta+1;
end;
Avance.Progress:=100;
CloseFile(arch);
TablaConsulta.CancelRange;

end;

end;


procedure campos;
var
i:integer;
begin

{***********************}

with FormaConsulta do
begin
ListaOpcion.Clear;
For i:=0 to ListaCampos.RowCount do
ListaOpcion.Items.Insert(i,ListaCampos.Cells[2,i]);
end;

{************************}

end;

procedure operadores;
begin
with FormaConsulta do
begin

ListaOpcion.Clear;
ListaOpcion.ItemHeight:=15;
ListaOpcion.Items.Insert(0,'=');
ListaOpcion.Items.Insert(1,'<');
ListaOpcion.Items.Insert(2,'>');
ListaOpcion.Items.Insert(3,'<=');
ListaOpcion.Items.Insert(4,'>=');
ListaOpcion.Items.Insert(5,'<>');

end;

end;

{procedure dato;
begin



end;}




procedure TFormaConsulta.CondicionesClick(Sender: TObject);
begin
case Condiciones.col of
1:campos;
2:operadores;
3:campos;
end;
ncond:=Condiciones.Row;
end;

procedure TFormaConsulta.ListaOpcionDblClick(Sender: TObject);
begin

Condiciones.Cells[Condiciones.Col,Condiciones.Row]:=ListaOpcion.Items[ListaOpcion.ItemIndex];
case Condiciones.Col of
1:begin
  ListaCondiciones.Cells[Condiciones.Col,Condiciones.Row]:=ListaCampos.Cells[1,ListaOpcion.ItemIndex];
  ListaCondiciones.Cells[Condiciones.Col+1,Condiciones.Row]:=ListaCampos.Cells[3,ListaOpcion.ItemIndex];
  end;

2:ListaCondiciones.Cells[Condiciones.Col+1,Condiciones.Row]:=ListaOpcion.Items[ListaOpcion.ItemIndex];

3:begin
if ListaCondiciones.Cells[Condiciones.Col-1,Condiciones.Row]= ListaCampos.Cells[3,ListaOpcion.ItemIndex] then
  begin
  ListaCondiciones.Cells[Condiciones.Col,Condiciones.Row]:=ListaCampos.Cells[1,ListaOpcion.ItemIndex];
  ListaCondiciones.Cells[Condiciones.Col+1,Condiciones.Row]:=ListaCampos.Cells[3,ListaOpcion.ItemIndex];
  ListaCondiciones.Cells[Condiciones.Col+2,Condiciones.Row]:='1';
  end
  else
  MuestraMensaje('No son compatibles los tipos');
  end;

end;
end;

procedure TFormaConsulta.EjecutarClick(Sender: TObject);
begin
{filtrabase;}
if FileExists(Archivo.Text) then
begin
calculaparametros;
generareporte;

if Concentrar.enabled=True then
concentra;

FormaGraficas.Reporte.Visible:=True;
FormaGraficas.Tag:=1;
ejecuta;
FormaAnteriorGrafica.ShowModal;
{FormaGraficas.ShowModal;}
end
else
MuestraMensaje('El Archivo De consulta No Existe...');
end;


procedure TFormaConsulta.FormActivate(Sender: TObject);
var i,j:integer;
begin
Detallar.Enabled:=True;
iniciabase;
{Leearchivocampos;}

for j:=1 to 10 do
begin
for i:=1 to 3 do
Condiciones.Cells[i,j]:='';
end;
ListaOpcion.Clear;

end;

procedure TFormaConsulta.SpeedButton2Click(Sender: TObject);
begin
FormaConsulta.Close;
end;


procedure TFormaConsulta.FormClose(Sender: TObject;
  var Action: TCloseAction);
begin
TablaConsulta.Close;
end;







procedure TFormaConsulta.CondicionesKeyUp(Sender: TObject; var Key: Word;
  Shift: TShiftState);
  var letra:string[1];
begin
if Condiciones.Col=3 then
begin
letra:=Condiciones.Cells[3,Condiciones.Row];
if letra<>'*' then
if not Compara(Condiciones.Cells[3,Condiciones.Row],ListaCondiciones.Cells[2,Condiciones.Row]) then
MuestraMensaje('Valor Erroneo');
end;
end;

procedure TFormaConsulta.FormCreate(Sender: TObject);
begin
Condiciones.ColWidths[0]:=10;
Condiciones.ColWidths[1]:=80;
Condiciones.ColWidths[2]:=80;
Condiciones.ColWidths[3]:=80;
Condiciones.Cells[1,0]:='Campos';
Condiciones.Cells[2,0]:='Operador';
Condiciones.Cells[3,0]:='Valor';
end;


procedure TFormaConsulta.SpeedButton7Click(Sender: TObject);
Type
datoscampo=record
campo:String[12];
descripcion:String[40];
tipo:String[12];
longitud:Integer;
end;
var

dat:datoscampo;
arch:file of datoscampo;
i,j:integer;
begin

if AbreArchivo.Execute then
begin
FormaConsulta.TablaConsulta.DataBaseName:='c:\proyecto';
FormaConsulta.TablaConsulta.First;
{FormaConsulta.RutaCampos.Text:=AbreArchivo.FileName;}
FormaConsulta.Destino.Text:='c:\proyecto\tempo\repcli.rep';
TipoVista.Text:=AbreArchivo.FileName;

end;

Concentrar.Enabled:=True;
iniciabase;
TablaConsulta.First;
{Leearchivocampos;}


for j:=1 to 10 do
begin
for i:=1 to 3 do
Condiciones.Cells[i,j]:='';
end;
ListaOpcion.Clear;

end;


procedure TFormaConsulta.ConcentrarClick(Sender: TObject);
begin
{FormaAcumulados.Show;}
end;



procedure TFormaConsulta.ArchivoChange(Sender: TObject);
begin
leearchivovista;
limpiacondiciones;
Avance.Progress:=0;
end;







procedure TFormaConsulta.Panel4Click(Sender: TObject);
begin
Close;
end;

procedure TFormaConsulta.Panel3MouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
ReleaseCapture;
SendMessage(FormaConsulta.Handle, WM_SYSCOMMAND, $F012, 0);
end;

procedure TFormaConsulta.Label4MouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
ReleaseCapture;
SendMessage(FormaConsulta.Handle, WM_SYSCOMMAND, $F012, 0);
end;

end.
