unit fticados;

interface

uses
  FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client, uFireDacHelper,
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids,
  Vcl.StdCtrls, Data.DB,   
  Vcl.ComCtrls, Vcl.ImgList, frxExportCSV, frxClass, frxExportPDF, frxDBSet,
  Vcl.DBCtrls,comobj,excel2000, Vcl.Mask,math, frxExportBaseDialog, Bde.DBTables;
type
  Tticados = class(TForm)
    Panel1: TPanel;
    Panel2: TPanel;
    Label1: TLabel;
    Label2: TLabel;
    DBGrid1: TDBGrid;
    qempleados: TFDQuery;
    dsqempleados: TDataSource;
    Panel3: TPanel;
    Panel4: TPanel;
    qticados: TFDQuery;
    dsqticados: TDataSource;
    Panel5: TPanel;
    buscarempleado: TEdit;
    Panel6: TPanel;
    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;
    Button1: TButton;
    ImageList1: TImageList;
    ticadosdb: TfrxDBDataset;
    rTicados: TfrxReport;
    frxPDFExport1: TfrxPDFExport;
    frxCSVExport1: TfrxCSVExport;
    qtotalhoras: TFDQuery;
    qtotalhorastotalhoras: TFloatField;
    dstotalhoras: TDataSource;
    qtotalhorasidt: TIntegerField;
    pmodificaciones: TPanel;
    Label3: TLabel;
    fdesde: TDateTimePicker;
    fhasta: TDateTimePicker;
    Label4: TLabel;
    Label5: TLabel;
    DBText1: TDBText;
    Button2: TButton;
    lentsal: TComboBox;
    Label7: TLabel;
    Button3: TButton;
    CheckBox1: TCheckBox;
    Edit2: TEdit;
    Label9: TLabel;
    btJexcel: TButton;
    checkacumulados: TCheckBox;
    qtotales: TFDQuery;
    dsqtotales: TDataSource;
    qtotalesidt: TIntegerField;
    qtotalestrabajador: TWideStringField;
    qtotalestotalhoras: TFloatField;
    Label10: TLabel;
    v_descuento: TEdit;
    Button4: TButton;
    qticadosdescuentohoras: TFloatField;
    Label11: TLabel;
    v_hora: TMaskEdit;
    qticadoshorascobrar: TFloatField;
    Label6: TLabel;
    v_horas: TEdit;
    Button5: TButton;
    qticadosentradam: TTimeField;
    qticadossalidam: TTimeField;
    qticadossalidam_m: TTimeField;
    qticadosentradat: TTimeField;
    qticadossalidat: TTimeField;
    qticadossalidat_m: TTimeField;
    qticadoshorafinmostrar: TTimeField;
    tgrupo: TDBLookupComboBox;
    qgrupostrabajadores2: TFDQuery;
    dsqgrupostrabajadores2: TDataSource;
    qgrupostrabajadores2ide: TIntegerField;
    qgrupostrabajadores2id: TIntegerField;
    qgrupostrabajadores2descripcion: TWideStringField;
    Label212: TLabel;
    ljcentro: TDBLookupComboBox;
    Label213: TLabel;
    ljtrabajo: TDBLookupComboBox;
    Label214: TLabel;
    ljhora: TDBLookupComboBox;
    qparcelas: TFDQuery;
    dsqparcelas: TDataSource;
    qparcelascodpar: TWideStringField;
    qparcelasempresa: TIntegerField;
    qparcelasnombre: TWideStringField;
    qtipohoras: TFDQuery;
    dsqtipohoras: TDataSource;
    qtrabajos: TFDQuery;
    dsqtrabajos: TDataSource;
    qtipohorascodart: TWideStringField;
    qtipohorasdescrip: TWideStringField;
    qtipohorasprecio: TFloatField;
    qtipohorasempresa: TIntegerField;
    qtrabajosid: TWideStringField;
    qtrabajosnombre: TWideStringField;
    qtrabajosempresa: TIntegerField;
    v_precio: TDBText;
    checkborrar: TCheckBox;
    qaux: TFDQuery;
    qjornales: TFDQuery;
    qjornalesid: TIntegerField;
    qjornalesempresa: TIntegerField;
    qjornalesfecha: TDateField;
    qjornalesparcela: TWideStringField;
    qjornalesidt: TIntegerField;
    qjornalestrabajador: TWideStringField;
    qjornalestypework: TWideStringField;
    qjornalesarticulo: TWideStringField;
    qjornalesqhoras: TFloatField;
    qjornalesprecio: TFloatField;
    qjornalestotal: TFloatField;
    qjornalesestado: TWideStringField;
    Button6: TButton;
    lnumtrabajadores: TLabel;
    Button7: TButton;
    qticadoshoras_reales: TFloatField;
    qticadosmostrar: TIntegerField;
    gcrpagado: TDBCheckBox;
    qticadosmodificando: TIntegerField;
    gridnormal: TDBGrid;
    gridtotales: TDBGrid;
    gridampliado: TDBGrid;
    qempleadosid: TSmallintField;
    qempleadosnombre: TWideStringField;
    qempleadoside: TIntegerField;
    chktodos: TCheckBox;
    qempleadoscodart: TWideStringField;
    btactualizar: TButton;
    Button8: TButton;
    Button9: TButton;
    dsqasistencia: TDataSource;
    gridasistencia: TDBGrid;
    qempleadosnif: TWideStringField;
    SaveDialog1: TSaveDialog;
    qtotalestotalhorascompu: TFloatField;
    qticadostiempoalmuerzo: TFloatField;
    qempleadoshorascontrato: TFloatField;
    qticadossalidam_mm: TTimeField;
    qticadoshorasm_mm: TFloatField;
    qticadosentradat_mm: TTimeField;
    qticadossalidat_mm: TTimeField;
    qticadoshorast_mm: TFloatField;
    Button10: TButton;
    dbticadosdetalle: TfrxDBDataset;
    qticadosdetalle: TFDQuery;
    dsqticadosdetalle: TDataSource;
    qticadosdetalleid: TLargeintField;
    qticadosdetalleide: TSmallintField;
    qticadosdetallefecha: TDateField;
    qticadosdetalleidt: TIntegerField;
    qticadosdetalleTRABAJADOR: TWideStringField;
    qticadosdetalleENTRADA_REAL: TTimeField;
    qticadosdetalleSALIDA_REAL: TTimeField;
    qticadosdetalletiempo: TFloatField;
    qticadosdetallecentro: TWideStringField;
    qjornalesorigen: TWideStringField;
    qjornalesobservaciones: TWideStringField;
    qasistir: TFDQuery;
    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;
    procedure tgrupoChange(Sender: TObject);
    procedure buscarempleadoChange(Sender: TObject);
    procedure fdesdeChange(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure Panel5Click(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure gridampliadoDrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumn; State: TGridDrawState);
    procedure gridnormalDrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumn; State: TGridDrawState);
    procedure Button2Click(Sender: TObject);
    procedure v_horasEnter(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure CheckBox1Click(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure btJexcelClick(Sender: TObject);
    procedure checkacumuladosClick(Sender: TObject);
    procedure FormKeyPress(Sender: TObject; var Key: Char);
    procedure gridampliadoTitleClick(Column: TColumn);
    procedure Button4Click(Sender: TObject);
    procedure Button5Click(Sender: TObject);
    procedure gridnormalTitleClick(Column: TColumn);
    procedure Button6Click(Sender: TObject);
    procedure qticadosAfterOpen(DataSet: TDataSet);
    procedure qticadosBeforePost(DataSet: TDataSet);
    procedure Button7Click(Sender: TObject);
    procedure gridampliadoCellClick(Column: TColumn);
    procedure qticadosBeforeEdit(DataSet: TDataSet);
    procedure qempleadosAfterOpen(DataSet: TDataSet);
    procedure qempleadosBeforeOpen(DataSet: TDataSet);
    procedure btactualizarClick(Sender: TObject);
    procedure gridampliadoDblClick(Sender: TObject);
    procedure Button8Click(Sender: TObject);
    procedure Button9Click(Sender: TObject);
    procedure qticadosAfterPost(DataSet: TDataSet);
    procedure Button10Click(Sender: TObject);
    procedure dsqgrupostrabajadores2DataChange(Sender: TObject; Field: TField);
  private
    { Private declarations }
  public
    { Public declarations }

   procedure ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar = nil);

  end;

var
  ticados: Tticados;
  filtrotrabajadores,tlimitado:string;
  grupo:integer;
  desdeactualizar:integer;
  oldhoras:real;
  vidticados:integer;
const
  rojo=$00AAAAFF;
  amarillo=$00B9FFFF;
  verde=$00C7FBAA;
  azul=$00FFFFBB;

implementation
uses datos, fdlgticados;
{$R *.dfm}

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 posicin 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 aplicacin 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 estn 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 segn su tipo
    for J := 0 to DBGrid.FieldCount -1 do
      case DBGrid.Fields[J].DataType of
        ftAutoInc, ftBytes, ftInteger, ftSmallint, ftWord: // Auto o Numrico
          WorkSheet.Cells[I +2, J +1] := DBGrid.Fields[J].AsInteger;
        ftBCD, ftFloat, ftCurrency: // Numrico 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 segn su tamao
  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.btJexcelClick(Sender: TObject);
var  archivo:string;
begin
    if gridampliado.Visible then
    begin
        archivo:='c:\agrigest\TICADOS.xlsx';
        try
        Exportaraexcel(archivo,'TICADOS',GRIDampliado);
        finally
          showmessage('Los datos han sido exportados correctamente a C:\agrigest');
        end;
    end;
    if gridnormal.Visible then
    begin
        archivo:='c:\agrigest\TICADOS.xlsx';
        try
        Exportaraexcel(archivo,'TICADOS',GRIDnormal);
        finally
          showmessage('Los datos han sido exportados correctamente a C:\agrigest');
        end;
    end;
    if gridtotales.Visible then
    begin
        archivo:='c:\agrigest\TICADOS.xlsx';
        try
        Exportaraexcel(archivo,'TICADOS',GRIDtotales);
        finally
          showmessage('Los datos han sido exportados correctamente a C:\agrigest');
        end;
    end;

end;

procedure Tticados.buscarempleadoChange(Sender: TObject);
begin
    filtrotrabajadores:='%'+buscarempleado.Text+'%';
    qempleados.Close;
    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.tempresaid.AsInteger;
     qticadosdetalle.Open;
        if checkbox1.Checked then
        begin
            ticadosdb.Datasource:=dsqticados;
            qticados.SortedFields:='fecha,trabajador';
            qticados.SortType:=stascending;
            rTicados.Report.Clear;
            rTicados.LoadFromFile('c:\agrigest\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:\agrigest\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:\agrigest\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.Button1Click(Sender: TObject);
begin
   qticados.Delete;
end;

procedure Tticados.Button2Click(Sender: TObject);
begin
    if checkacumulados.Checked then
    begin
        ticadosdb.Datasource:=dsqtotales;
        rTicados.Report.Clear;
        rTicados.LoadFromFile('c:\agrigest\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:\agrigest\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:\agrigest\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:\agrigest\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.Button3Click(Sender: TObject);
var ad,entsal,aleatorio,aleatorio2,positivo:integer;
    dia,mes,anyo:word;
    tfecha:string;
begin
    qticados.First;
    desdeactualizar:=1;
    entsal:=lentsal.ItemIndex;
    if v_hora.Text<>'  :  :  ' then
    begin
        case entsal of
            0:
            begin
              qticados.First;
              while not qticados.Eof do
              begin
                 if v_hora.text<>'00:00:00' then
                 begin
                     randomize;
                     positivo:=random(2);
                     if positivo=0 then positivo:=-1;
                     randomize;
                     aleatorio:=positivo*random(10);
                     randomize;
                     aleatorio2:=random(60);
                 end;
                 qticados.Edit;
                 decodedate(qticadosfecha.AsDateTime,anyo,mes,dia);
                 tfecha:=inttostr(anyo)+'/'+inttostr(mes)+'/'+inttostr(dia);
                 qticadosentradam.Value:=strtotime(v_hora.Text);
                 qticadosentradam.Value:=qticadosentradam.AsdateTime+aleatorio/1440+aleatorio2/86400;
                 if edit2.Text <>'' then qticadosobservaciones.Value:=Edit2.Text;
                 qticados.post;
                 qticados.Next;
              end;
            end;
            1:
            begin
              qticados.First;
              while not qticados.Eof do
              begin
                 if v_hora.text<>'00:00:00' then
                 begin
                     randomize;
                     positivo:=random(2);
                     if positivo=0 then positivo:=-1;
                     randomize;
                     aleatorio:=positivo*random(10);
                     randomize;
                     aleatorio2:=random(60);
                 end;

                 qticados.Edit;
                 decodedate(qticadosfecha.AsDateTime,anyo,mes,dia);
                 tfecha:=inttostr(anyo)+'/'+inttostr(mes)+'/'+inttostr(dia);
                 qticadossalidam.Value:=strtotime(v_hora.Text);
                 qticadossalidam.Value:=qticadossalidam.AsdateTime+aleatorio/1440+aleatorio2/86400;
                 if edit2.Text <>'' then qticadosobservaciones.Value:=Edit2.Text;
                 qticados.post;
                 qticados.Next;
              end;
            end;
            2:
            begin
              qticados.First;
              while not qticados.Eof do
              begin
                 if v_hora.Text<>'00:00:00' then
                 begin
                     randomize;
                     positivo:=random(2);
                     if positivo=0 then positivo:=-1;
                     randomize;
                     aleatorio:=positivo*random(10);
                     randomize;
                     aleatorio2:=random(60);
                 end;
                 qticados.Edit;
                 decodedate(qticadosfecha.AsDateTime,anyo,mes,dia);
                 tfecha:=inttostr(anyo)+'/'+inttostr(mes)+'/'+inttostr(dia);
                 qticadosentradat.Value:=strtotime(v_hora.Text);
                 qticadosentradat.Value:=qticadosentradat.AsdateTime+aleatorio/1440+aleatorio2/86400;
                 if edit2.Text <>'' then qticadosobservaciones.Value:=Edit2.Text;
                 qticados.post;
                 qticados.Next;
              end;
            end;
            3:
            begin
              qticados.First;
              while not qticados.Eof do
              begin
                 if v_hora.Text<>'00:00:00' then
                 begin
                     randomize;
                     positivo:=random(2);
                     if positivo=0 then positivo:=-1;
                     randomize;
                     aleatorio:=positivo*random(10);
                     randomize;
                     aleatorio2:=random(60);
                 end;

                 qticados.Edit;
                 decodedate(qticadosfecha.AsDateTime,anyo,mes,dia);
                 tfecha:=inttostr(anyo)+'/'+inttostr(mes)+'/'+inttostr(dia);
                 qticadossalidat.Value:=strtotime(v_hora.Text);
                 qticadossalidat.Value:=qticadossalidat.AsdateTime+aleatorio/1440+aleatorio2/86400;
                 if edit2.Text <>'' then qticadosobservaciones.Value:=Edit2.Text;
                 qticados.post;
                 qticados.Next;
              end;
            end;
        end;
     end;
    if (v_hora.Text='  :  :  ') and (edit2.text<>'') then
    begin
      qticados.First;
      while not qticados.Eof do
      begin
         qticados.Edit;
         if edit2.Text <>'' then qticadosobservaciones.Value:=Edit2.Text;
         qticados.post;
         qticados.Next;
      end;
    end;
    qticados.Refresh;
    desdeactualizar:=0;
    qticados.First;
end;

procedure Tticados.Button4Click(Sender: TObject);
var punto:string;
formatos:tformatsettings;
begin
    GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos);
    punto:=formatos.DecimalSeparator;
    qticados.First;
    if punto=',' then  v_descuento.text:=stringreplace(v_descuento.Text,'.',',',[rfreplaceall]);
      while not qticados.Eof do
      begin
         qticados.Edit;
         qticadosdescuentohoras.Value:=strtofloat(v_descuento.Text);
         qticados.post;
         qticados.Next;
      end;
      qticados.refresh;
      qticados.First;
end;

procedure Tticados.Button5Click(Sender: TObject);
var contador,vide,vidt:integer;
    dia,mes,anyo:word;
    tfecha:string;
    totaljornal:real;
begin
    qjornales.Open;
    qticados.First;
    qaux.SQL.Clear;
    qaux.SQL.Add('select max(id)+1 from trabajo_diario');
    qaux.Open;
    contador:=qaux.Fields[0].AsInteger;
    if qticados.RecordCount>0 then
       begin
           qticados.First;

           while not qticados.Eof do
           begin
           vide:=qticadoside.Asinteger;
           vidt:=qticadosidt.AsInteger;
           qempleados.Locate('ide,id',vararrayof([vide,vidt]),[locaseinsensitive]);
           decodedate(qticadosfecha.AsDateTime,anyo,mes,dia);
           tfecha:=floattostr(anyo)+'-'+floattostr(mes)+'-'+floattostr(dia);
              if checkborrar.Checked then
              begin
                  qaux.SQL.Clear;
                  qaux.SQL.Add('select * from trabajo_diario where idt='+qticadosidt.AsString+' and fecha='+''''+tfecha+''''+' and empresa='+qticadoside.AsString);
                  qaux.open;
                  if qaux.RecordCount>0 then
                  begin
                      qaux.SQL.Clear;
                      qaux.SQL.Add('delete from trabajo_diario where idt='+qticadosidt.AsString+' and fecha='+''''+tfecha+''''+' and empresa='+qticadoside.AsString);
                      qaux.execsql;
                  end;

              end;
              qjornales.append;
              qjornalesid.Value:=contador;
              qjornalesfecha.Value:=qticadosfecha.AsDateTime;
              qjornalesparcela.value:=ljcentro.KeyValue;
              qjornalesidt.Value:=qticadosidt.asinteger;
              qjornalestrabajador.Value:=qticadostrabajador.asstring;
              qjornalestypework.Value:=ljtrabajo.KeyValue;
              qjornalesarticulo.Value:=ljhora.KeyValue;
              qjornalesqhoras.Value:=qticadoshorascobrar.AsFloat;
              qjornalesprecio.value:=qtipohorasprecio.AsFloat;
              qjornalesobservaciones.value:=qticadosobservaciones.AsString;
              totaljornal:=qticadoshorascobrar.asfloat*qtipohorasprecio.AsFloat;
              qjornalestotal.Value:=strtofloat(FormatFloat('0.00',totaljornal));
              qjornalesestado.Value:='C';
              qjornales.Post;
              contador:=contador+1;
              qticados.Next;
           end;
       end else
           begin
             showmessage('DEBE SELECCIONAR AL MENOS UN TRABAJADOR');
           end;
      qticados.First;
end;

procedure Tticados.Button6Click(Sender: TObject);
begin
      qticados.First;
      v_horas.text:=stringreplace(v_horas.Text,' ','',[rfreplaceall]);
      if v_horas.text<>'' then
      begin
        v_horas.text:=stringreplace(v_horas.Text,'.',',',[rfreplaceall]);
        while not qticados.Eof do
        begin
           qticados.Edit;
           qticadoshorascobrar.Value:=strtofloat(v_horas.Text);
           qticados.post;
           qticados.Next;
        end;
      end;
    qticados.refresh;
    qticados.First;
end;

procedure Tticados.Button7Click(Sender: TObject);
begin
    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.showmodal();
    finally
      dlgticados.Free;
      qticados.Refresh;
    end;
end;

procedure Tticados.Button8Click(Sender: TObject);
var minutosajuste,ajusteentrada,ajustesalida:integer;
    horaentrada,horasalida:ttime;
    hora,minutos,horaaj,minutosaj,anyo,mes,dia:word;
    dhora,dminutos,dsegundos,dmilisegundos:word;
    horasfact:real;
    tid,descuento:integer;
    vmes,vdia,vanyo,vfecha,sdescuento:string;
begin
  qticados.First;
  if dm.tempresaajuste15.AsInteger=1 then minutosajuste:=15;
  if dm.tempresaajuste30.AsInteger=1 then minutosajuste:=30;
  ajusteentrada:=dm.tempresaajusteentrada.AsInteger;
  ajustesalida:=dm.tempresaajustesalida.AsInteger;
  while not qticados.Eof do
  begin
    horasfact:=0;
    if qticadosentradam.Asstring<>'' then
    begin     //1
      horaentrada:=qticadosentradam.AsDateTime;
      if qticadossalidam.Asstring<>'' then
      begin      //2
        horasalida:=qticadossalidam.AsDateTime;
        if minutosajuste=30 then
        begin        //4
           decodetime(horaentrada,dhora,dminutos,dsegundos,dmilisegundos);
           horaaj:=dhora;
           if dminutos<=ajusteentrada then minutosaj:=0;
           if (dminutos>ajusteentrada) and (dminutos<=ajusteentrada+30) then minutosaj:=30;
           if dminutos>30+ajusteentrada then
           begin
                minutosaj:=0;
                horaaj:=horaaj+1;
           end;
           horaentrada:=encodetime(horaaj,minutosaj,0,0);
           decodetime(horasalida,dhora,dminutos,dsegundos,dmilisegundos);
           horaaj:=dhora;
           if dminutos<=ajustesalida then minutosaj:=0;
           if (dminutos>ajustesalida) and (dminutos<=ajustesalida+30) then minutosaj:=30;
           if dminutos>30+ajustesalida then
           begin
                minutosaj:=0;
                horaaj:=horaaj+1;
           end;
           horasalida:=encodetime(horaaj,minutosaj,0,0);
           horasfact:=(horasalida-horaentrada)*24;
        end; //4
        if minutosajuste=15 then
        begin        //4
           decodetime(horaentrada,dhora,dminutos,dsegundos,dmilisegundos);
           horaaj:=dhora;
           if dminutos<=ajusteentrada then minutosaj:=0;
           if (dminutos>ajusteentrada) and (dminutos<=ajusteentrada+15) then minutosaj:=15;
           if (dminutos>15+ajusteentrada) and (dminutos<=ajusteentrada+30) then minutosaj:=30;
           if (dminutos>30+ajusteentrada) and (dminutos<=ajusteentrada+45) then minutosaj:=45;
           if dminutos>45+ajusteentrada then
           begin
                minutosaj:=0;
                horaaj:=horaaj+1;
           end;
           horaentrada:=encodetime(horaaj,minutosaj,0,0);
           decodetime(horasalida,dhora,dminutos,dsegundos,dmilisegundos);
           horaaj:=dhora;
           if dminutos<=ajusteentrada then minutosaj:=0;
           if (dminutos>ajusteentrada) and (dminutos<=ajusteentrada+15) then minutosaj:=15;
           if (dminutos>15+ajusteentrada) and (dminutos<=ajusteentrada+30) then minutosaj:=30;
           if (dminutos>30+ajusteentrada) and (dminutos<=ajusteentrada+45) then minutosaj:=45;
           if dminutos>45+ajusteentrada then
           begin
                minutosaj:=0;
                horaaj:=horaaj+1;
           end;
           horasalida:=encodetime(horaaj,minutosaj,0,0);
           horasfact:=(horasalida-horaentrada)*24;
        end;
      end;     //2
    end;//1
    if qticadosentradat.Asstring<>'' then
    begin   //1
      horaentrada:=qticadosentradat.AsDateTime;
      if qticadossalidat.Asstring<>'' then
      begin    //2
        horasalida:=qticadossalidat.AsDateTime;
        if minutosajuste=30 then
        begin  //4
           decodetime(horaentrada,dhora,dminutos,dsegundos,dmilisegundos);
           horaaj:=dhora;
           if dminutos<=ajusteentrada then minutosaj:=0;
           if (dminutos>ajusteentrada) and (dminutos<=ajusteentrada+30) then minutosaj:=30;
           if dminutos>30+ajusteentrada then
           begin
                minutosaj:=0;
                horaaj:=horaaj+1;
           end;
           horaentrada:=encodetime(horaaj,minutosaj,0,0);

           decodetime(horasalida,dhora,dminutos,dsegundos,dmilisegundos);
           horaaj:=dhora;
           if dminutos<=ajustesalida then minutosaj:=0;
           if (dminutos>ajustesalida) and (dminutos<=ajustesalida+30) then minutosaj:=30;
           if dminutos>30+ajustesalida then
           begin
                minutosaj:=0;
                horaaj:=horaaj+1;
           end;
           horasalida:=encodetime(horaaj,minutosaj,0,0);
           horasfact:=horasfact+((horasalida-horaentrada)*24);
         end;         //4
        if minutosajuste=15 then
        begin  //4
           decodetime(horaentrada,dhora,dminutos,dsegundos,dmilisegundos);
           horaaj:=dhora;
           if dminutos<=ajusteentrada then minutosaj:=0;
           if (dminutos>ajusteentrada) and (dminutos<=ajusteentrada+15) then minutosaj:=15;
           if (dminutos>15+ajusteentrada) and (dminutos<=ajusteentrada+30) then minutosaj:=30;
           if (dminutos>30+ajusteentrada) and (dminutos<=ajusteentrada+45) then minutosaj:=45;
           if dminutos>45+ajusteentrada then
           begin
                minutosaj:=0;
                horaaj:=horaaj+1;
           end;
           horaentrada:=encodetime(horaaj,minutosaj,0,0);

           decodetime(horasalida,dhora,dminutos,dsegundos,dmilisegundos);
           horaaj:=dhora;
           if dminutos<=ajusteentrada then minutosaj:=0;
           if (dminutos>ajusteentrada) and (dminutos<=ajusteentrada+15) then minutosaj:=15;
           if (dminutos>15+ajusteentrada) and (dminutos<=ajusteentrada+30) then minutosaj:=30;
           if (dminutos>30+ajusteentrada) and (dminutos<=ajusteentrada+45) then minutosaj:=45;
           if dminutos>45+ajusteentrada then
           begin
                minutosaj:=0;
                horaaj:=horaaj+1;
           end;
           horasalida:=encodetime(horaaj,minutosaj,0,0);
           horasfact:=horasfact+((horasalida-horaentrada)*24);
         end;         //4

        end;  //2

      end; //1
     qticados.Edit;
     qticadoshorascobrar.asfloat:=0;
     qticadosmodificando.asinteger:=1;
     qticados.Post;
     qticados.Edit;
     qticadoshorascobrar.asfloat:=horasfact-qticadosdescuentohoras.AsFloat;
     qticadosmodificando.asinteger:=0;
     qticados.Post;
     qticados.Next;
  end;


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.btactualizarClick(Sender: TObject);
var i,p_empresa:integer;
    p_activo,p_grupo,p_empleados,p_mostrar:string;
begin
   if dm.tempresa.Active then p_empresa:=dm.tempresaid.AsInteger
      else
        begin
          dm.tempresa.Open;
          p_empresa:=dm.tempresaid.AsInteger;
        end;
    if grupo=0 then p_grupo:='%' else p_grupo:=inttostr(grupo);
    p_empleados:='%'+buscarempleado.Text+'%';
    if chktodos.Checked then p_activo:='%' else p_activo:='1';
    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 ide=:EMPRESA and id=:ID and activo like(:ACTIVO)' );
    qaux.Prepare;
    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('ACTIVO').AsString:=p_activo;
        qaux.Execsql;
      end
    else
    begin
       qaux.close;
       qaux.SQL.Clear;
       qaux.SQL.Add('update trabajadores set seleccionado=1 where ide=:EMPRESA and grupo like(:GRUPO) and nombre like(:EMPLEADO) and activo like (:ACTIVO)');
       qaux.Prepare;
       qaux.parambyname('EMPRESA').AsInteger:=p_empresa;
       qaux.parambyname('GRUPO').Asstring:=p_grupo;
       qaux.parambyname('EMPLEADO').Asstring:=p_empleados;
       qaux.parambyname('ACTIVO').Asstring:=p_activo;
       qaux.Execsql;
    end;
    if gridampliado.Visible then p_mostrar:='%' else p_mostrar:='1';
    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.CheckBox1Click(Sender: TObject);
var p_mostrar:string;
begin
    btactualizar.Click;
end;

procedure Tticados.dsqgrupostrabajadores2DataChange(Sender: TObject;
  Field: TField);
begin
  grupo:=qgrupostrabajadores2id.asinteger;
  qempleados.Close;
  qempleados.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.gridnormalDrawColumnCell(Sender: TObject; const Rect: TRect;
  DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
    if qticadosfestivo.Asinteger=1 then
    begin
        gridnormal.Canvas.brush.Color := rojo;
    end;

    gridnormal.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;

procedure Tticados.gridnormalTitleClick(Column: TColumn);
var
  st:TFDQuerySortType;
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.v_horasEnter(Sender: TObject);
begin
   v_horas.Text:='';
end;

procedure Tticados.fdesdeChange(Sender: TObject);
begin
  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
   DM.tempresa.Open;
   fdesde.Date:=date()-1;
   fhasta.Date:=date()-1;
   gridampliado.Visible:=false;
   panel6.Visible:=false;
   pmodificaciones.Visible:=false;
   gridnormal.Visible:=true;
   desdeactualizar:=0;
   qgrupostrabajadores2.Prepare;
   qgrupostrabajadores2.ParamByName('IDEMPRESA').AsInteger:=dm.tempresaid.AsInteger;
   qgrupostrabajadores2.open;
   tgrupo.KeyValue:=qgrupostrabajadores2id.AsString;
   qparcelas.Open;
   qtipohoras.Open;
   qtrabajos.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:TFDQuerySortType;
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;

procedure Tticados.qempleadosAfterOpen(DataSet: TDataSet);
var i:integer;
    p_empresa:integer;
    p_empleados,p_grupo,p_activo,p_mostrar:string;
begin
      if dm.tempresa.Active then p_empresa:=dm.tempresaid.AsInteger
      else
        begin
          dm.tempresa.Open;
          p_empresa:=dm.tempresaid.AsInteger;
        end;
      if grupo=0 then p_grupo:='%' else p_grupo:=inttostr(grupo);
    p_empleados:='%'+buscarempleado.Text+'%';
    if chktodos.Checked then p_activo:='%' else p_activo:='1';
    qaux.close;
    qaux.SQL.Clear;
    qaux.SQL.Add('select * from trabajadores where seleccionado=1');
    qaux.open;
    if qaux.RecordCount>1 then
    begin
      qaux.close;
      qaux.SQL.Clear;
      qaux.SQL.Add('update trabajadores set seleccionado=0 where seleccionado=1');
      qaux.Execsql;
    end;
    qaux.close;
    qaux.SQL.Clear;
    qaux.SQL.Add('update trabajadores set seleccionado=1 where ide=:EMPRESA and id=:ID and activo like(:ACTIVO)' );
    qaux.Prepare;
    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('ACTIVO').AsString:=p_activo;
        qaux.Execsql;
      end
    else
    begin
       qaux.close;
       qaux.SQL.Clear;
       qaux.SQL.Add('update trabajadores set seleccionado=1 where ide=:EMPRESA and activo like(:GRUPO) and nombre like(:EMPLEADO) and activo like (:ACTIVO)');
       qaux.Prepare;
       qaux.parambyname('EMPRESA').AsInteger:=p_empresa;
       qaux.parambyname('GRUPO').Asstring:=p_grupo;
       qaux.parambyname('EMPLEADO').Asstring:=p_empleados;
       qaux.parambyname('ACTIVO').Asstring:=p_activo;
       qaux.Execsql;
    end;
    if gridampliado.Visible then p_mostrar:='%' else p_mostrar:='1';
    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 like(:MOSTRAR) and fecha>=:FECHAINICIO and fecha<=:FECHAFIN and idt in (select id from trabajadores where seleccionado=1) ');
      qtotalhoras.Prepare;
      qtotalhoras.ParamByName('FECHAINICIO').AsDateTime:=fdesde.DateTime;
      qtotalhoras.ParamByName('FECHAFIN').AsDateTime:=fhasta.DateTime;
      qtotalhoras.ParamByName('MOSTRAR').Asstring:=p_mostrar;
      qtotalhoras.Open;
      qtotales.Close;
      qtotales.SQL.Clear;
      qtotales.SQL.Add('select idt,trabajador,sum(num_horas_m) as totalhoras,sum(horascobrar) as totalhorascompu');
      qtotales.SQL.Add(' from ticadoscompleto where  mostrar like(:MOSTRAR) and fecha>=:FECHAINICIO and fecha<=:FECHAFIN and idt in (select id from trabajadores where seleccionado=1) group by idt order by trabajador');
      qtotales.Prepare;
      qtotales.ParamByName('FECHAINICIO').AsDate:=fdesde.Date;
      qtotales.ParamByName('FECHAFIN').AsDate:=fhasta.Date;
      qtotales.ParamByName('MOSTRAR').Asstring:=p_mostrar;
      qtotales.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 like(:MOSTRAR) and fecha>=:FECHAINICIO and fecha<=:FECHAFIN and idt in (select id from trabajadores where seleccionado=1) group by idt');
      qtotalhoras.Prepare;
      qtotalhoras.ParamByName('FECHAINICIO').AsDate:=fdesde.Date;
      qtotalhoras.ParamByName('FECHAFIN').AsDate:=fhasta.Date;
      qtotalhoras.ParamByName('MOSTRAR').Asstring:=p_mostrar;
      qtotalhoras.Open;
      qtotales.Close;
      qtotales.SQL.Clear;
      qtotales.SQL.Add('select idt,trabajador,sum(num_horas_m) as totalhoras,sum(horascobrar) as totalhorascompu ');
      qtotales.SQL.Add(' from ticadoscompleto where mostrar like(:MOSTRAR) and fecha>=:FECHAINICIO and fecha<=:FECHAFIN and idt in (select id from trabajadores where seleccionado=1) group by trabajador');
      qtotales.Prepare;
      qtotales.ParamByName('FECHAINICIO').AsDate:=fdesde.Date;
      qtotales.ParamByName('FECHAFIN').AsDate:=fhasta.Date;
      qtotales.ParamByName('MOSTRAR').Asstring:=p_mostrar;
      qtotales.Open;
    end;
end;

procedure Tticados.qempleadosBeforeOpen(DataSet: TDataSet);
var p_empresa:integer;
    p_empleados,p_grupo,p_activo:string;
begin
      if dm.tempresa.Active then p_empresa:=dm.tempresaid.AsInteger
      else
        begin
          dm.tempresa.Open;
          p_empresa:=dm.tempresaid.AsInteger;
        end;
      if grupo=0 then p_grupo:='%' else p_grupo:=inttostr(grupo);
      p_empleados:='%'+buscarempleado.Text+'%';
      if chktodos.Checked then p_activo:='%' else p_activo:='1';
      qempleados.Prepare;
      qempleados.parambyname('EMPRESA').AsInteger:=p_empresa;
      qempleados.parambyname('GRUPO').Asstring:=p_grupo;
      qempleados.parambyname('EMPLEADO').Asstring:=p_empleados;
      qempleados.parambyname('ACTIVO').Asstring:=p_activo;
end;

procedure Tticados.qticadosAfterOpen(DataSet: TDataSet);
begin
    qaux.Close;
    qaux.SQL.Clear;
    qaux.SQL.Add('select count(distinct(idt)) from ('+qticados.SQL.Text+') as qticados');
    qaux.open;
    lnumtrabajadores.Caption:='Trabajadores seleccionados: '+(qaux.fields[0].asstring);
end;

procedure Tticados.qticadosAfterPost(DataSet: TDataSet);
begin
   qticados.Refresh;
   qticados.Locate('id',vidticados,[locaseinsensitive]);
end;

procedure Tticados.qticadosBeforeEdit(DataSet: TDataSet);
begin
    oldhoras:=qticadoshorascobrar.AsFloat;
end;

procedure Tticados.qticadosBeforePost(DataSet: TDataSet);
var hora:string;
begin
{    if qticadossalidat.AsString<>'' then
    begin
        hora:=qticadossalidat.asstring;
        qticadoshorafinmostrar.Value:=strtotime(hora);
    end;
    if (qticadossalidam.AsString<>'') and (qticadossalidat.AsString='') then
    begin
        hora:=qticadossalidam.asstring;
       qticadoshorafinmostrar.Value:=strtotime(hora);
    end; }
    if (qticadoshorascobrar.AsFloat<>oldhoras) and (qticadosmodificando.asinteger=0) then
    begin
       qticadosmodificando.value:=1;
    end;
    vidticados:=qticadosid.AsInteger;

end;

procedure Tticados.tgrupoChange(Sender: TObject);
begin
  grupo:=qgrupostrabajadores2id.asinteger;
  qempleados.Close;
  qempleados.Open;
end;

end.
