unit fticados;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, frxClass, Data.DB, ZDataset,
  ZAbstractRODataset, ZAbstractDataset, Vcl.ComCtrls, Vcl.Mask, Vcl.StdCtrls,
  Vcl.DBCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.ImgList, frxExportPDF,
  frxExportBaseDialog, frxExportCSV, frxDBSet,excel2000,comobj;

type
  Tticados = class(TForm)
    btJexcel: TButton;
    dbticadosdetalle: TfrxDBDataset;
    frxCSVExport1: TfrxCSVExport;
    frxPDFExport1: TfrxPDFExport;
    gcrpagado: TDBCheckBox;
    ImageList1: TImageList;
    Panel1: TPanel;
    Panel2: TPanel;
    Label2: TLabel;
    buscarempleado: TEdit;
    chktodos: TCheckBox;
    DBGrid1: TDBGrid;
    Panel3: TPanel;
    gridnormal: TDBGrid;
    Panel4: TPanel;
    Label3: TLabel;
    Label4: TLabel;
    Label5: TLabel;
    DBText1: TDBText;
    Label8: TLabel;
    lnumtrabajadores: TLabel;
    Panel5: TPanel;
    pmodificaciones: TPanel;
    Label7: TLabel;
    Label9: TLabel;
    Label10: TLabel;
    Label11: TLabel;
    lentsal: TComboBox;
    Button3: TButton;
    Edit2: TEdit;
    v_descuento: TEdit;
    Button4: TButton;
    v_hora: TMaskEdit;
    fdesde: TDateTimePicker;
    fhasta: TDateTimePicker;
    Button2: TButton;
    CheckBox1: TCheckBox;
    checkacumulados: TCheckBox;
    btactualizar: TButton;
    Button9: TButton;
    Button10: TButton;
    Panel6: TPanel;
    Button1: TButton;
    Button7: TButton;
    gridtotales: TDBGrid;
    gridampliado: TDBGrid;
    gridasistencia: TDBGrid;
    qasistir: TZQuery;
    qasistiride: TIntegerField;
    qasistiridt: TIntegerField;
    qasistiranyo: TIntegerField;
    qasistirmes: TWideStringField;
    qasistirnif: TWideStringField;
    qasistirnombre: TWideStringField;
    qasistird1: TWideStringField;
    qasistird2: TWideStringField;
    qasistird3: TWideStringField;
    qasistird4: TWideStringField;
    qasistird5: TWideStringField;
    qasistird6: TWideStringField;
    qasistird7: TWideStringField;
    qasistird8: TWideStringField;
    qasistird9: TWideStringField;
    qasistird10: TWideStringField;
    qasistird11: TWideStringField;
    qasistird12: TWideStringField;
    qasistird13: TWideStringField;
    qasistird14: TWideStringField;
    qasistird15: TWideStringField;
    qasistird16: TWideStringField;
    qasistird17: TWideStringField;
    qasistird18: TWideStringField;
    qasistird19: TWideStringField;
    qasistird20: TWideStringField;
    qasistird21: TWideStringField;
    qasistird22: TWideStringField;
    qasistird23: TWideStringField;
    qasistird24: TWideStringField;
    qasistird25: TWideStringField;
    qasistird26: TWideStringField;
    qasistird27: TWideStringField;
    qasistird28: TWideStringField;
    qasistird29: TWideStringField;
    qasistird30: TWideStringField;
    qasistird31: TWideStringField;
    qasistirfechaalta: TDateField;
    qasistirfechabaja: TDateField;
    qasistirnombre2: TWideStringField;
    qaux: TZReadOnlyQuery;
    qempleados: TZReadOnlyQuery;
    qempleadoside: TIntegerField;
    qempleadosid: TSmallintField;
    qempleadosnombre: TWideStringField;
    qempleadoscodart: TWideStringField;
    qempleadosnif: TWideStringField;
    qempleadoshorascontrato: TFloatField;
    qjornales: TZQuery;
    qjornalesid: TIntegerField;
    qjornalesempresa: TIntegerField;
    qjornalesfecha: TDateField;
    qjornalesparcela: TWideStringField;
    qjornalesidt: TIntegerField;
    qjornalestrabajador: TWideStringField;
    qjornalestypework: TWideStringField;
    qjornalesarticulo: TWideStringField;
    qjornalesqhoras: TFloatField;
    qjornalesprecio: TFloatField;
    qjornalestotal: TFloatField;
    qjornalesestado: TWideStringField;
    qjornalesorigen: TWideStringField;
    qjornalesobservaciones: TWideStringField;
    qticados: TZQuery;
    qticadosid: TLargeintField;
    qticadoside: TSmallintField;
    qticadosfecha: TDateField;
    qticadosidt: TIntegerField;
    qticadosTRABAJADOR: TWideStringField;
    qticadoshorasm: TFloatField;
    qticadoshorasm_m: TFloatField;
    qticadoshorast: TFloatField;
    qticadoshorast_m: TFloatField;
    qticadosnum_horas: TFloatField;
    qticadosnum_horas_m: TFloatField;
    qticadosimprimir: TIntegerField;
    qticadosobservaciones: TWideStringField;
    qticadosfestivo: TIntegerField;
    qticadosdescuentohoras: TFloatField;
    qticadoshorascobrar: TFloatField;
    qticadosentradam: TTimeField;
    qticadossalidam: TTimeField;
    qticadossalidam_m: TTimeField;
    qticadosentradat: TTimeField;
    qticadossalidat: TTimeField;
    qticadossalidat_m: TTimeField;
    qticadoshorafinmostrar: TTimeField;
    qticadoshoras_reales: TFloatField;
    qticadosmostrar: TIntegerField;
    qticadosmodificando: TIntegerField;
    qticadostiempoalmuerzo: TFloatField;
    qticadossalidam_mm: TTimeField;
    qticadoshorasm_mm: TFloatField;
    qticadosentradat_mm: TTimeField;
    qticadossalidat_mm: TTimeField;
    qticadoshorast_mm: TFloatField;
    qticadosdetalle: TZQuery;
    qticadosdetalleid: TLargeintField;
    qticadosdetalleide: TSmallintField;
    qticadosdetallefecha: TDateField;
    qticadosdetalleidt: TIntegerField;
    qticadosdetalleTRABAJADOR: TWideStringField;
    qticadosdetalleENTRADA_REAL: TTimeField;
    qticadosdetalleSALIDA_REAL: TTimeField;
    qticadosdetalletiempo: TFloatField;
    qticadosdetallecentro: TWideStringField;
    qtotales: TZQuery;
    qtotalesidt: TIntegerField;
    qtotalestrabajador: TWideStringField;
    qtotalestotalhoras: TFloatField;
    qtotalestotalhorascompu: TFloatField;
    qtotalhoras: TZQuery;
    qtotalhorastotalhoras: TFloatField;
    qtotalhorasidt: TIntegerField;
    rTicados: TfrxReport;
    SaveDialog1: TSaveDialog;
    ticadosdb: TfrxDBDataset;
    dsqasistencia: TDataSource;
    dsqempleados: TDataSource;
    dsqticados: TDataSource;
    dsqticadosdetalle: TDataSource;
    dsqtotales: TDataSource;
    dstotalhoras: TDataSource;
    Button5: TButton;
    Button6: TButton;
    qinftrabajadores: TZReadOnlyQuery;
    qinftrabajadoresid: TIntegerField;
    qinftrabajadoreside: TIntegerField;
    qinftrabajadoresnif: TWideStringField;
    qinftrabajadoresnombre: TWideStringField;
    qinftrabajadoresapellidos: TWideStringField;
    qinftrabajadoresnombre_completo: TWideStringField;
    qinftrabajadoresdireccion: TWideStringField;
    qinftrabajadorespoblacion: TWideStringField;
    qinftrabajadorescp: TWideStringField;
    qinftrabajadoresprovincia: TWideStringField;
    qinftrabajadorestelefono1: TWideStringField;
    qinftrabajadorestelefono2: TWideStringField;
    qinftrabajadoresemail: TWideStringField;
    qinftrabajadoresentidad: TWideStringField;
    qinftrabajadorescc: TWideStringField;
    qinftrabajadoressalario: TFloatField;
    qinftrabajadoresprecio_km: TFloatField;
    qinftrabajadoresprecio_hx: TFloatField;
    qinftrabajadoresactivo: TIntegerField;
    qinftrabajadoresusuario: TWideStringField;
    qinftrabajadorespassword: TWideStringField;
    qinftrabajadorestipo_acceso: TIntegerField;
    qinftrabajadoresseleccionado: TIntegerField;
    qinftrabajadorescolor: TWideStringField;
    qinftrabajadoreshorasdia: TFloatField;
    qinftrabajadoresimagen: TBlobField;
    informes: TfrxReport;
    informedb: TfrxDBDataset;
    dsqinftrabajadores: TDataSource;
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FormKeyPress(Sender: TObject; var Key: Char);
    procedure FormShow(Sender: TObject);
    procedure buscarempleadoChange(Sender: TObject);
    procedure CheckBox1Click(Sender: TObject);
    procedure btactualizarClick(Sender: TObject);
    procedure gridampliadoCellClick(Column: TColumn);
    procedure gridampliadoDblClick(Sender: TObject);
    procedure gridampliadoDrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumn; State: TGridDrawState);
    procedure gridampliadoTitleClick(Column: TColumn);
    procedure chktodosClick(Sender: TObject);
    procedure checkacumuladosClick(Sender: TObject);
    procedure Panel5Click(Sender: TObject);
    procedure fdesdeChange(Sender: TObject);
    procedure Button9Click(Sender: TObject);
    procedure Button5Click(Sender: TObject);
    procedure Button10Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button6Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
   procedure ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar = nil);

  end;

var
  ticados: Tticados;
  filtrotrabajadores,tlimitado,p_mostrar:string;
  grupo:integer;
  desdeactualizar:integer;
  oldhoras:real;
  vidticados:integer;
const
  rojo=$00AAAAFF;
  amarillo=$00B9FFFF;
  verde=$00C7FBAA;
  azul=$00FFFFBB;


implementation

{$R *.dfm}

uses DATOS, fdlgticados;
procedure Tticados.btactualizarClick(Sender: TObject);
var i,p_empresa:integer;
    p_activo,p_grupo,p_empleados:string;
begin
   if dm.empresa.Active then p_empresa:=dm.empresaid.AsInteger
      else
        begin
          dm.empresa.Open;
          p_empresa:=dm.empresaid.AsInteger;
        end;
    qaux.close;
    qaux.SQL.Clear;
    qaux.SQL.Add('update trabajadores set seleccionado=0 where seleccionado=1');
    qaux.Execsql;


    p_empleados:='%'+buscarempleado.Text+'%';
    if chktodos.Checked then
    begin
    p_mostrar:='%';
    qempleados.close;
    qempleados.ParamByname('EMPRESA').AsInteger:=p_empresa;
    qempleados.ParamByname('MOSTRAR').AsSTRING:=p_mostrar;
    qempleados.ParamByname('EMPLEADO').Asstring:=p_empleados;
    qempleados.Open;
    qaux.close;
    qaux.SQL.Clear;
    qaux.SQL.Add('update trabajadores set seleccionado=1 where ide=:EMPRESA and mostrar like(:MOSTRAR) and id like (:ID)' );
    qaux.Prepare;
    end else
    begin
     p_mostrar:='1';
     qaux.close;
     qaux.SQL.Clear;
     qaux.SQL.Add('update trabajadores set seleccionado=1 where ide=:EMPRESA and mostrar like(:MOSTRAR) and id like (:ID)' );
     qaux.Prepare;
    end;
    if dbgrid1.SelectedRows.Count>0 then
      for i := 0 to dbgrid1.Selectedrows.Count - 1 do
      begin
        qempleados.GotoBookmark ((dbgrid1.selectedrows[i]));
        qaux.ParamByName('ID').AsInteger:=qempleadosid.asinteger;
        qaux.ParamByName('EMPRESA').AsInteger:=qempleadoside.asinteger;
        qaux.ParamByName('MOSTRAR').AsString:=p_mostrar;
        qaux.Execsql;
      end
    else
    begin
       qaux.close;
       qaux.SQL.Clear;
       qaux.SQL.Add('update trabajadores set seleccionado=1 where ide=:EMPRESA and nombre like(:EMPLEADO) and mostrar like (:MOSTRAR)');
       qaux.Prepare;
       qaux.parambyname('EMPRESA').AsInteger:=p_empresa;
       qaux.parambyname('EMPLEADO').Asstring:=p_empleados;
       qaux.parambyname('MOSTRAR').Asstring:=p_mostrar;
       qaux.Execsql;
    end;
    if gridampliado.Visible then p_mostrar:='%' else p_mostrar:='1';
    qempleados.Refresh;
    if checkbox1.Checked then
    begin
      qticados.Close;
//      qticados.SQL.Clear;
//      qticados.SQL.Add('select * from ticadoscompleto where mostrar like(:MOSTRAR) and fecha>=:FECHAINICIO and fecha<=:FECHAFIN and idt in (select id from trabajadores where seleccionado=1)  order by trabajador,fecha desc,entradam,entradat');
      qticados.Prepare;
      qticados.ParamByName('FECHAINICIO').AsDate:=fdesde.Date;
      qticados.ParamByName('FECHAFIN').AsDate:=fhasta.Date;
      qticados.ParamByName('MOSTRAR').Asstring:=p_mostrar;
      qticados.MasterSource:=nil;
      qticados.Open;
      qtotalhoras.Close;
      qtotalhoras.MasterSource:=nil;
      qtotalhoras.SQL.Clear;
      qtotalhoras.SQL.Add('select idt,sum(num_horas_m) as totalhoras from ticadoscompleto where mostrar=1 and fecha>=:FECHAINICIO and fecha<=:FECHAFIN and idt in (select id from trabajadores where seleccionado=1) ');
      qtotalhoras.Prepare;
      qtotalhoras.ParamByName('FECHAINICIO').AsDate:=fdesde.Date;
      qtotalhoras.ParamByName('FECHAFIN').AsDate:=fhasta.Date;
      qtotalhoras.Open;
    end else
    begin
      qticados.Close;
//      qticados.SQL.Clear;
//      qticados.SQL.Add('select * from ticadoscompleto where mostrar like(:MOSTRAR) and fecha>=:FECHAINICIO and fecha<=:FECHAFIN and idt in (select id from trabajadores where seleccionado=1)  order by trabajador,fecha desc,entradam,entradat');
      qticados.Prepare;
      qticados.ParamByName('FECHAINICIO').AsDate:=fdesde.Date;
      qticados.ParamByName('FECHAFIN').AsDate:=fhasta.Date;
      qticados.ParamByName('MOSTRAR').Asstring:=p_mostrar;
      qticados.MasterSource:=dsqempleados;
      qticados.Open;
      qtotalhoras.Close;
      qtotalhoras.MasterSource:=dsqempleados;
      qtotalhoras.SQL.Clear;
      qtotalhoras.SQL.Add('select idt,sum(num_horas_m) as totalhoras from ticadoscompleto where mostrar=1 and fecha>=:FECHAINICIO and fecha<=:FECHAFIN and idt in (select id from trabajadores where seleccionado=1) group by idt order by idt');
      qtotalhoras.Prepare;
      qtotalhoras.ParamByName('FECHAINICIO').AsDate:=fdesde.Date;
      qtotalhoras.ParamByName('FECHAFIN').AsDate:=fhasta.Date;
      qtotalhoras.Open;
    end;


end;

procedure Tticados.buscarempleadoChange(Sender: TObject);
var pmostrar:string;
begin
    if chktodos.Checked then pmostrar:='%' else pmostrar:='1';
    qempleados.Close;
    qempleados.Prepare;
    qempleados.ParamByName('EMPLEADO').AsString:='%'+buscarempleado.Text+'%';
    qempleados.ParamByName('EMPRESA').AsInteger:=DM.empresaID.AsInteger;
    qempleados.ParamByName('MOSTRAR').AsString:=pmostrar;
    qempleados.open;

end;

procedure Tticados.Button10Click(Sender: TObject);
begin
     qticadosdetalle.close;
     qticadosdetalle.Prepare;
     qticadosdetalle.ParamByName('FECHAINICIO').AsDate:=fdesde.Date;
     qticadosdetalle.ParamByName('FECHAFIN').AsDate:=fhasta.Date;
     qticadosdetalle.ParamByName('IDE').Asinteger:=dm.empresaid.AsInteger;
     qticadosdetalle.Open;
        if checkbox1.Checked then
        begin
            ticadosdb.Datasource:=dsqticados;
            qticados.SortedFields:='fecha,trabajador';
            qticados.SortType:=stascending;
            rTicados.Report.Clear;
            rTicados.LoadFromFile('c:\formagest\informes\controlhorariogrupo.fr3');
        //    rTicados.Variables.Variables['tdesde']:=QUOTEDSTR('Desde: '+datetostr(fdesde.Date));
          //  rTicados.Variables.Variables['thasta']:=QUOTEDSTR('Hasta: '+DATETOSTR(fhasta.DATE));
            rticados.Report.FileName:='Control horario ';
            rticados.ShowReport();
            rTicados.Clear;
            ticadosdb.Datasource:=dsqticados;
            qticados.SortedFields:='trabajador,fecha';
            qticados.SortType:=stascending;
            rTicados.Report.Clear;
            rTicados.LoadFromFile('c:\formagest\informes\controlhorariodetalle.fr3');
            rTicados.Variables.Variables['tdesde']:=QUOTEDSTR('Desde: '+datetostr(fdesde.Date));
            rTicados.Variables.Variables['thasta']:=QUOTEDSTR('Hasta: '+DATETOSTR(fhasta.DATE));
            rticados.Report.FileName:='Control horario ' + qticadostrabajador.asstring;
            rticados.ShowReport();
            rTicados.Clear;
        end else
        begin
            ticadosdb.Datasource:=dsqticados;
            qticados.SortedFields:='trabajador,fecha';
            qticados.SortType:=stascending;
            rTicados.Report.Clear;
            rTicados.LoadFromFile('c:\formagest\informes\controlhorariodetalle.fr3');
            rTicados.Variables.Variables['tdesde']:=QUOTEDSTR('Desde: '+datetostr(fdesde.Date));
            rTicados.Variables.Variables['thasta']:=QUOTEDSTR('Hasta: '+DATETOSTR(fhasta.DATE));
            rticados.Report.FileName:='Control horario ' + qticadostrabajador.asstring;
            rticados.ShowReport();
            rTicados.Clear;
        end;
end;

procedure Tticados.Button2Click(Sender: TObject);
begin
   if checkacumulados.Checked then
    begin
        ticadosdb.Datasource:=dsqtotales;
        rTicados.Report.Clear;
        rTicados.LoadFromFile('c:\formagest\informes\controlhorariototales.fr3');
        rTicados.Variables.Variables['tdesde']:=QUOTEDSTR('Desde: '+datetostr(fdesde.Date));
        rTicados.Variables.Variables['thasta']:=QUOTEDSTR('Hasta: '+DATETOSTR(fhasta.DATE));
        rticados.Report.FileName:='Control horario ' + qticadostrabajador.asstring;
        rticados.ShowReport();
        rTicados.Clear
    end else
    begin
        if checkbox1.Checked then
        begin
            ticadosdb.Datasource:=dsqticados;
            qticados.SortedFields:='fecha,trabajador';
            qticados.SortType:=stascending;
            rTicados.Report.Clear;
            rTicados.LoadFromFile('c:\formagest\informes\controlhorariogrupo.fr3');
        //    rTicados.Variables.Variables['tdesde']:=QUOTEDSTR('Desde: '+datetostr(fdesde.Date));
          //  rTicados.Variables.Variables['thasta']:=QUOTEDSTR('Hasta: '+DATETOSTR(fhasta.DATE));
            rticados.Report.FileName:='Control horario ';
            rticados.ShowReport();
            rTicados.Clear;
            ticadosdb.Datasource:=dsqticados;
            qticados.SortedFields:='trabajador,fecha';
            qticados.SortType:=stascending;
            rTicados.Report.Clear;
            rTicados.LoadFromFile('c:\formagest\informes\controlhorario.fr3');
            rTicados.Variables.Variables['tdesde']:=QUOTEDSTR('Desde: '+datetostr(fdesde.Date));
            rTicados.Variables.Variables['thasta']:=QUOTEDSTR('Hasta: '+DATETOSTR(fhasta.DATE));
            rticados.Report.FileName:='Control horario ' + qticadostrabajador.asstring;
            rticados.ShowReport();
            rTicados.Clear;
        end else
        begin
            ticadosdb.Datasource:=dsqticados;
            qticados.SortedFields:='trabajador,fecha';
            qticados.SortType:=stascending;
            rTicados.Report.Clear;
            rTicados.LoadFromFile('c:\formagest\informes\controlhorario.fr3');
            rTicados.Variables.Variables['tdesde']:=QUOTEDSTR('Desde: '+datetostr(fdesde.Date));
            rTicados.Variables.Variables['thasta']:=QUOTEDSTR('Hasta: '+DATETOSTR(fhasta.DATE));
            rticados.Report.FileName:='Control horario ' + qticadostrabajador.asstring;
            rticados.ShowReport();
            rTicados.Clear;
        end;
    end;
end;

procedure Tticados.Button5Click(Sender: TObject);
var  archivo:string;
begin
    if gridampliado.Visible then
    begin
        archivo:='c:\formagest\TICADOS.xlsx';
        try
        Exportaraexcel(archivo,'TICADOS',GRIDampliado);
        finally
          showmessage('Los datos han sido exportados correctamente a C:\formagest');
        end;
    end;
    if gridnormal.Visible then
    begin
        archivo:='c:\formagest\TICADOS.xlsx';
        try
        Exportaraexcel(archivo,'TICADOS',GRIDnormal);
        finally
          showmessage('Los datos han sido exportados correctamente a C:\formagest');
        end;
    end;
    if gridtotales.Visible then
    begin
        archivo:='c:\formagest\TICADOS.xlsx';
        try
        Exportaraexcel(archivo,'TICADOS',GRIDtotales);
        finally
          showmessage('Los datos han sido exportados correctamente a C:\agrigest');
        end;
    end;

end;

procedure Tticados.Button6Click(Sender: TObject);
begin
  qinftrabajadores.Close;
  qinftrabajadores.Prepare;
  qinftrabajadores.ParamByName('EMPRESA').AsInteger:=qempleadoside.AsInteger;
  qinftrabajadores.ParamByName('ID').AsInteger:=qempleadosid.AsInteger;
  qinftrabajadores.Open;
  informedb.Datasource:=dsqinftrabajadores;
  informes.Report.Clear;
  informes.LoadFromFile('c:\formagest\informes\tarjeta2.fr3');
  informes.ShowReport();
end;

procedure Tticados.Button9Click(Sender: TObject);
var  archivo,vmes,vnombre,vnif,vhoras:string;
     tdia,tmes,tanyo:word;
     vdia,vanyo,vide,vidt:integer;
begin
  qaux.Close;
  qaux.SQL.Clear;
  qaux.SQL.Add('delete from emp_asistencia');
  qaux.execsql;

  qticados.First;
  while not qticados.Eof do
  begin
    decodedate(qticadosfecha.AsDateTime,tanyo,tmes,tdia);
    vdia:=tdia;
    vanyo:=tanyo;
    vhoras:=floattostr(qticadosnum_horas_m.AsFloat);
    case tmes of
       1:vmes:='ENERO';
       2:vmes:='FEBRERO';
       3:vmes:='MARZO';
       4:vmes:='ABRIL';
       5:vmes:='MAYO';
       6:vmes:='JUNIO';
       7:vmes:='JULIO';
       8:vmes:='AGOSTO';
       9:vmes:='SEPTIEMBRE';
      10:vmes:='OCTUBRE';
      11:vmes:='NOVIEMBRE';
      12:vmes:='DICIEMBRE';
    end;
    vide:=qticadoside.AsInteger;
    vidt:=qticadosidt.AsInteger;
    qempleados.Locate('ide,id',vararrayof([vide,vidt]),[locaseinsensitive]);
    vnif:=qempleadosnif.asstring;
    vnombre:=qempleadosnombre.AsString;
    qaux.Close;
    qaux.SQL.Clear;
    qaux.SQL.Add('select * from emp_asistencia where ide=:EMPRESA and idt=:TRABAJADOR and anyo=:ANYO and mes=:MES');
    qaux.Prepare;
    qaux.ParamByName('EMPRESA').AsInteger:=vide;
    qaux.ParamByName('TRABAJADOR').AsInteger:=vidt;
    qaux.ParamByName('ANYO').AsInteger:=vanyo;
    qaux.ParamByName('MES').Asstring:=vmes;
    qaux.Open;
    if qaux.RecordCount=0 then
    begin
      qaux.Close;
      qaux.SQL.Clear;
      qaux.SQL.Add('insert into emp_asistencia (ide,idt,nif,nombre,anyo,mes) values (:EMPRESA,:TRABAJADOR,:NIF,:NOMBRE,:ANYO,:MES)');
      qaux.Prepare;
      qaux.ParamByName('EMPRESA').AsInteger:=vide;
      qaux.ParamByName('TRABAJADOR').AsInteger:=vidt;
      qaux.ParamByName('NIF').Asstring:=vnif;
      qaux.ParamByName('NOMBRE').Asstring:=vnombre;
      qaux.ParamByName('ANYO').AsInteger:=vanyo;
      qaux.ParamByName('MES').Asstring:=vmes;
      qaux.execsql;
      qasistir.close;
      qasistir.Open;
      qasistir.Locate('ide,idt,anyo,mes',vararrayof([vide,vidt,vanyo,vmes]),[locaseinsensitive]);
    end;
       qasistir.Edit;
       case vdia of
       1:qasistird1.value:='X';
       2:qasistird2.value:='X';
       3:qasistird3.value:='X';
       4:qasistird4.value:='X';
       5:qasistird5.value:='X';
       6:qasistird6.value:='X';
       7:qasistird7.value:='X';
       8:qasistird8.value:='X';
       9:qasistird9.value:='X';
      10:qasistird10.value:='X';
      11:qasistird11.value:='X';
      12:qasistird12.value:='X';
      13:qasistird13.value:='X';
      14:qasistird14.value:='X';
      15:qasistird15.value:='X';
      16:qasistird16.value:='X';
      17:qasistird17.value:='X';
      18:qasistird18.value:='X';
      19:qasistird19.value:='X';
      20:qasistird20.value:='X';
      21:qasistird21.value:='X';
      22:qasistird22.value:='X';
      23:qasistird23.value:='X';
      24:qasistird24.value:='X';
      25:qasistird25.value:='X';
      26:qasistird26.value:='X';
      27:qasistird27.value:='X';
      28:qasistird28.value:='X';
      29:qasistird29.value:='X';
      30:qasistird30.value:='X';
      31:qasistird31.value:='X';
    end;
    qasistir.Post;
    qticados.Next;
  end;
    decodedate(fdesde.date,tanyo,tmes,tdia);
    case tmes of
       1:vmes:='ENERO';
       2:vmes:='FEBRERO';
       3:vmes:='MARZO';
       4:vmes:='ABRIL';
       5:vmes:='MAYO';
       6:vmes:='JUNIO';
       7:vmes:='JULIO';
       8:vmes:='AGOSTO';
       9:vmes:='SEPTIEMBRE';
      10:vmes:='OCTUBRE';
      11:vmes:='NOVIEMBRE';
      12:vmes:='DICIEMBRE';
    end;
    qasistir.Close;
    qasistir.SQL.Clear;
    qasistir.SQL.Add('select * from v_emp_asistencia where ide=:EMPRESA and anyo=:ANYO and mes=:MES order by anyo,nombre2');
    qasistir.Prepare;
    qasistir.ParamByName('EMPRESA').AsInteger:=vide;
    qasistir.ParamByName('MES').Asstring:=vmes;
    qasistir.ParamByName('ANYO').Asinteger:=vanyo;

    qasistir.Open;

    savedialog1.FileName:='PARTE COMUNICACION.xlsx';
    savedialog1.Execute();
    archivo:=savedialog1.FileName;
    try
    Exportaraexcel(archivo,'PARTE',GRIDASISTENCIA);
    finally
      showmessage('Los datos han sido exportados correctamente a '+archivo);
    end;
{    qasistencia.Close;
    qasistencia.SQL.Clear;
    qasistencia.SQL.Add('select * from v_emp_asistencia order by ide,idt,anyo,mes');
    qasistencia.Open;}


end;

procedure Tticados.checkacumuladosClick(Sender: TObject);
begin
   if checkacumulados.Checked then
    begin
       if checkbox1.Checked then
       begin
          qticados.Close;
          qtotalhoras.Close;
          qticados.MasterSource:=nil;
          qticados.Open;
          qtotalhoras.MasterSource:=nil;
          qtotalhoras.Open;
          qtotales.MasterSource:=nil;
          qtotales.Open;
       end else
       begin
         qticados.Close;
         qtotalhoras.Close;
         qticados.MasterSource:=dsqempleados;
         qticados.Open;
         qtotalhoras.MasterSource:=dsqempleados;
         qtotalhoras.Open;
         qtotales.MasterSource:=dsqempleados;
         qtotales.Open;
       end;

        gridtotales.Visible:=true;
        gridnormal.Visible:=false;
        gridampliado.Visible:=false;
        gridtotales.Columns[2].Title.caption:='Horas desde el '+datetostr(fdesde.Date)+' hasta el '+datetostr(fhasta.Date);
    end else
    begin
       if checkbox1.Checked then
       begin
          qticados.Close;
          qtotalhoras.Close;
          qticados.MasterSource:=nil;
          qticados.Open;
          qtotalhoras.MasterSource:=nil;
          qtotalhoras.Open;
          qtotales.MasterSource:=nil;
          qtotales.Open;
       end else
       begin
         qticados.Close;
         qtotalhoras.Close;
         qticados.MasterSource:=dsqempleados;
         qticados.Open;
         qtotalhoras.MasterSource:=dsqempleados;
         qtotalhoras.Open;
         qtotales.MasterSource:=dsqempleados;
         qtotales.Open;
       end;
        gridtotales.Visible:=false;
        gridnormal.Visible:=true;
        gridampliado.Visible:=false;
    end;

end;

procedure Tticados.CheckBox1Click(Sender: TObject);
begin
    btactualizar.Click;

end;

procedure Tticados.chktodosClick(Sender: TObject);
begin
  if chktodos.Checked then
  begin
    qempleados.Close;
    qempleados.ParamByName('EMPLEADO').AsString:='%';
    qempleados.ParamByName('EMPRESA').AsInteger:=DM.empresaID.AsInteger;
    qempleados.ParamByName('MOSTRAR').Asstring:='%';
    qempleados.open;
  end else
  begin
    qempleados.Close;
    qempleados.ParamByName('EMPLEADO').AsString:='%';
    qempleados.ParamByName('EMPRESA').AsInteger:=DM.empresaID.AsInteger;
    qempleados.ParamByName('MOSTRAR').Asstring:='1';
    qempleados.open;

  end;
  btactualizar.Click;
end;

procedure tticados.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 Tticados.fdesdeChange(Sender: TObject);
begin
  btactualizar.Click;
  btactualizar.Click;
end;

procedure Tticados.FormClose(Sender: TObject; var Action: TCloseAction);
begin
    qaux.close;
    qaux.SQL.Clear;
    qaux.SQL.Add('update trabajadores set seleccionado=0 where seleccionado=1');
    qaux.Execsql;
   qticados.Close;
   qtotalhoras.Close;
   qempleados.Close;
end;

procedure Tticados.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 Tticados.FormShow(Sender: TObject);
begin
   p_mostrar:='1';
   DM.empresa.Open;
   fdesde.Date:=date()-1;
   fhasta.Date:=date()-1;
   gridampliado.Visible:=false;
   panel6.Visible:=false;
   pmodificaciones.Visible:=false;
   gridnormal.Visible:=true;
   desdeactualizar:=0;
    qaux.close;
    qaux.SQL.Clear;
    qaux.SQL.Add('update trabajadores set seleccionado=0 where seleccionado=1');
    qaux.Execsql;
    qaux.close;
    qaux.SQL.Clear;
    qaux.SQL.Add('update trabajadores set seleccionado=1 where mostrar=1');
    qaux.Execsql;
   dm.qempleados.Close;
   dm.qempleados.Prepare;
    qempleados.ParamByName('EMPLEADO').AsString:='%';
    qempleados.ParamByName('EMPRESA').AsInteger:=DM.empresaID.AsInteger;
    qempleados.ParamByName('MOSTRAR').AsInteger:=1;
    qempleados.open;

end;

procedure Tticados.gridampliadoCellClick(Column: TColumn);
begin
    if column.Field.FieldName ='mostrar' then
    begin
        if qticadosmostrar.asinteger=1 then
         begin
           qticados.Edit;
           qticadosmostrar.value:=0;
           qticados.Post;
//           qticados.Refresh;
           gridampliado.selectedIndex:=18;
         end else
               begin
                 qticados.edit;
                 qticadosmostrar.Value:=1;
                 qticados.Post;
//                 qticados.Refresh;
                 gridampliado.SelectedIndex:=18;
               end;
    end;
    qtotalhoras.close;
    qtotalhoras.Open;
end;

procedure Tticados.gridampliadoDblClick(Sender: TObject);
var vidticados:integer;
begin
    vidticados:=qticadosid.AsInteger;
    dlgticados := Tdlgticados.Create(nil);
    try
      dlgticados.qticados.ParamByName('IDE').AsInteger:=qticadoside.AsInteger;
      dlgticados.qticados.ParamByName('IDT').AsInteger:=qticadosidt.AsInteger;
      dlgticados.qticados.ParamByName('FECHA').Asdatetime:=qticadosfecha.Asdatetime;
      dlgticados.qticados.prepare;
      dlgticados.qticados.Open;
      dlgticados.idticado:=vidticados;
      dlgticados.showmodal();
    finally
      dlgticados.Free;
      qticados.Refresh;
      qticados.Locate('id',vidticados,[locaseinsensitive]);
    end;
end;

procedure Tticados.gridampliadoDrawColumnCell(Sender: TObject;
  const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
const IsChecked : array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED);
var
    DrawState: Integer;
    DrawRect: TRect;
begin
if (gdFocused in State) then
begin
    if qticadosfestivo.Asinteger=1 then
    begin
        Gridampliado.Canvas.brush.Color := rojo;
    end;
    gridampliado.DefaultDrawColumnCell(Rect, DataCol, Column, State);

    if (Column.Field.FieldName = 'mostrar') then
     begin
       gcrpagado.Left := Rect.Left + gridampliado.Left + 2;
       gcrpagado.Top := Rect.Top + gridampliado.top + 2;
       gcrpagado.Width := Rect.Right - Rect.Left;
       gcrpagado.Height := Rect.Bottom - Rect.Top;
       gcrpagado.Visible := True;
     end;
end else
     begin
        if qticadosfestivo.Asinteger=1 then
        begin
            Gridampliado.Canvas.brush.Color := rojo;
        end;
        gridampliado.DefaultDrawColumnCell(Rect, DataCol, Column, State);

       if (Column.Field.FieldName = 'mostrar') then
       begin
         DrawRect:=Rect;
         InflateRect(DrawRect,-1,-1);
         if column.Field.Asinteger=0  then DrawState := ischecked[false];
         if column.Field.Asinteger=1  then DrawState := ischecked[true];
         //DrawState := ISChecked[Column.Field.Asboolean];
         gridampliado.Canvas.FillRect(Rect);
         DrawFrameControl(gridampliado.Canvas.Handle, DrawRect,
         DFC_BUTTON, DrawState);
       end;
    end;



end;

procedure Tticados.gridampliadoTitleClick(Column: TColumn);
var
  st:ZAbstractRODataset.TSortType;
begin
  st:=qticados.SortType;
  qticados.SortedFields:=Column.FieldName;
  If st = stAscending then qticados.SortType:=stDescending else qticados.SortType:=stAscending;
  dsqticados.DataSet.First;
end;



procedure Tticados.Panel5Click(Sender: TObject);
var idt:integer;
begin
   idt:=qempleadosid.AsInteger;


   if gridnormal.visible then
   begin
      gridampliado.Visible:=true;
      panel6.Visible:=true;
      gridnormal.Visible:=false;
      pmodificaciones.visible:=true;
      button10.Visible:=true;

   end else
   begin
      gridampliado.Visible:=false;
      panel6.Visible:=false;
      gridnormal.Visible:=true;
      pmodificaciones.visible:=false;
      button10.Visible:=false;
   end;
   btactualizar.Click;
   qempleados.Locate('id',idt,[locaseinsensitive]);
end;

end.
