﻿unit empleados;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
  Vcl.ComCtrls, Vcl.DBCtrls, Vcl.Mask, Vcl.Grids, Vcl.DBGrids, Data.DB,
  ZAbstractRODataset, ZDataset, ZAbstractDataset, ZAbstractTable, frxClass,
  frxDBSet,Vcl.OleServer,  ComObj, Excel2000,  SHDocVw, wgssSTU_TLB,SignatureForm,
   Vcl.ToolWin, Vcl.ImgList,dateutils,
   Vcl.ExtDlgs, Vcl.Imaging.jpeg, Vcl.Imaging.pngimage, Vcl.Buttons, VCLTee.TeEngine, VCLTee.Series,
   VCLTee.TeeData, VCLTee.TeeProcs, VCLTee.Chart, VCLTee.DBChart,
   Vcl.OleCtrls,IdHTTP,mshtml, frxExportPDF, frxExportCSV, frxCtrls,
   frxExportText, frxExportRTF, Vcl.Menus, frxChBox, frxPreview,
  
   uEmailWhatsApp, uEnviarDocumento, frxExportBaseDialog;



type
  Tfempleados = class(TForm)
    Panel2: TPanel;
    Panel1: TPanel;
    Label1: TLabel;
    Label28: TLabel;
    ltotalgrupo: TLabel;
    tbuscar: TEdit;
    chktodosempleados: TCheckBox;
    checktodos2: TCheckBox;
    listagrupos2: TDBLookupComboBox;
    LabelSexo: TLabel;
    cbsexo: TComboBox;
    DBGrid1: TDBGrid;
    PageEmpleados: TPageControl;
    tabDatosGenerales: TTabSheet;
    Panel9: TPanel;
    Label12: TLabel;
    gridplantillaext: TDBGrid;
    gridplantillacomu: TDBGrid;
    Panel164: TPanel;
    Label2: TLabel;
    Label3: TLabel;
    Label5: TLabel;
    Label6: TLabel;
    Label7: TLabel;
    Label25: TLabel;
    Label54: TLabel;
    Label11: TLabel;
    Label30: TLabel;
    DBEdit1: TDBEdit;
    DBEdit2: TDBEdit;
    DBEdit4: TDBEdit;
    DBEdit5: TDBEdit;
    DBEdit6: TDBEdit;
    DBEdit9: TDBEdit;
    DBEdit22: TDBEdit;
    DBEdit23: TDBEdit;
    DBEdit24: TDBEdit;
    DBEdit25: TDBEdit;
    DBEdit17: TDBEdit;
    DBEdit8: TDBEdit;
    DBEdit27: TDBEdit;
    Panel8: TPanel;
    TabJornales: TTabSheet;
    Panel5: TPanel;
    DBGrid2: TDBGrid;
    Panel4: TPanel;
    Label47: TLabel;
    Label48: TLabel;
    Label49: TLabel;
    Label50: TLabel;
    Label51: TLabel;
    Label52: TLabel;
    tfechajornal: TDateTimePicker;
    lparcela: TDBLookupComboBox;
    ltrabajo: TDBLookupComboBox;
    ltipohora: TDBLookupComboBox;
    thoras: TEdit;
    lprecio: TEdit;
    Panel13: TPanel;
    Label53: TLabel;
    Shape3: TShape;
    Label67: TLabel;
    Label70: TLabel;
    Shape6: TShape;
    Label71: TLabel;
    Shape7: TShape;
    Label72: TLabel;
    Shape8: TShape;
    DBEdit39: TDBEdit;
    Panel3: TPanel;
    Label9: TLabel;
    Label37: TLabel;
    Label38: TLabel;
    Tanyo: TComboBox;
    TMES: TComboBox;
    TabAnticipos: TTabSheet;
    Panel12: TPanel;
    DBGrid3: TDBGrid;
    Panel11: TPanel;
    Panel163: TPanel;
    Label171: TLabel;
    Label138: TLabel;
    Label45: TLabel;
    Label44: TLabel;
    limporteanticipo: TEdit;
    lopciones: TComboBox;
    lobservaciones: TEdit;
    fechaanticipo: TDateTimePicker;
    Panel10: TPanel;
    Label40: TLabel;
    Label41: TLabel;
    Label42: TLabel;
    tanyo2: TComboBox;
    tmes2: TComboBox;
    Panel23: TPanel;
    Label109: TLabel;
    Shape13: TShape;
    Label110: TLabel;
    Label111: TLabel;
    Shape14: TShape;
    Label112: TLabel;
    Shape15: TShape;
    Label113: TLabel;
    Shape16: TShape;
    DBEdit64: TDBEdit;
    Panel14: TPanel;
    btEcancelar: TButton;
    btEmodificar: TButton;
    btEborrar: TButton;
    btEnuevo: TButton;
    btEguardar: TButton;
    listaimpresion: TComboBox;
    bteimprimir: TButton;
    btnEnviarDoc: TButton;
    qgrupos: TZReadOnlyQuery;
    dsqgrupos: TDataSource;
    dsqgrupos2: TDataSource;
    qgrupos2: TZReadOnlyQuery;
    dsqlistaempleados: TDataSource;
    qlistaempleados: TZReadOnlyQuery;
    qlistaempleadoside: TIntegerField;
    qlistaempleadosid: TSmallintField;
    qlistaempleadosnombre: TWideStringField;
    qgrupos2ide: TIntegerField;
    qgrupos2id: TIntegerField;
    qgrupos2descripcion: TWideStringField;
    qgruposide: TIntegerField;
    qgruposid: TIntegerField;
    qgruposdescripcion: TWideStringField;
    qempleados: TZQuery;
    dsqempleados: TDataSource;
    DBText1: TDBText;
    DBText2: TDBText;
    qempleadoside: TIntegerField;
    qempleadosID: TSmallintField;
    qempleadosNIF: TWideStringField;
    qempleadosnombre: TWideStringField;
    qempleadosNOMBRECORTO: TWideStringField;
    qempleadosAPELLIDOS: TWideStringField;
    qempleadosDIRECCION: TWideStringField;
    qempleadosCP: TWideStringField;
    qempleadosPOBLACION: TWideStringField;
    qempleadosPROVINCIA: TWideStringField;
    qempleadosFECHANACIMIENTO: TDateField;
    qempleadosPAISNAC: TWideStringField;
    qempleadosNACIONALIDAD: TWideStringField;
    qempleadosSEXO: TWideStringField;
    qempleadosCBIBAN: TWideStringField;
    qempleadosCBBANCO: TWideStringField;
    qempleadosCBOFICINA: TWideStringField;
    qempleadosCBDC: TWideStringField;
    qempleadosCBCC: TWideStringField;
    qempleadosPAGARPORBANCO: TIntegerField;
    qempleadosTELEFONO1: TWideStringField;
    qempleadosTELEFONO2: TWideStringField;
    qempleadosTELEFONO3: TWideStringField;
    qempleadosTELEFONO4: TWideStringField;
    qempleadosREGIMEN_COT: TWideStringField;
    qempleadosNUMSEGSOCIAL: TWideStringField;
    qempleadosIRPF: TFloatField;
    qempleadosIRPF2: TFloatField;
    qempleadosDESEMPLEO: TFloatField;
    qempleadosDESEMPLEO2: TFloatField;
    qempleadosFORMACION: TFloatField;
    qempleadosFORMACION2: TFloatField;
    qempleadosIMAGEN: TIntegerField;
    qempleadosOBSERVACIONES: TWideStringField;
    qempleadosFECHAALTA: TDateField;
    qempleadosFECHABAJA: TDateField;
    qempleadosempresa: TIntegerField;
    qempleadosseleccionado: TIntegerField;
    qempleadoscodart: TWideStringField;
    dsqtipohora: TDataSource;
    qtipohora: TZReadOnlyQuery;
    dsqregimencotizacion: TDataSource;
    qregimencotizacion: TZReadOnlyQuery;
    qtipohoracodart: TWideStringField;
    qtipohoradescrip: TWideStringField;
    qtipohoraprecio: TFloatField;
    qtipohoraequivalenciahoras: TFloatField;
    qtipohoraactivo: TIntegerField;
    qtipohoraempresa: TIntegerField;
    qtipohorafacturar: TIntegerField;
    qtipohoraseleccionado: TIntegerField;
    qregimencotizacionid: TIntegerField;
    qregimencotizaciondescripcion: TWideStringField;
    qregimencotizacionirpf: TFloatField;
    qregimencotizaciondesempleo: TFloatField;
    qregimencotizacionformacion: TFloatField;
    qregimencotizacioncontingencias: TFloatField;
    dsempfotos: TDataSource;
    informedb: TfrxDBDataset;
    informes: TfrxReport;
    qaux: TZQuery;
    dsqinftrabajadores: TDataSource;
    qinftrabajadores: TZReadOnlyQuery;
    qinftrabajadoresID: TSmallintField;
    qinftrabajadoresNIF: TWideStringField;
    qinftrabajadoresnombre: TWideStringField;
    qinftrabajadoresNOMBRECORTO: TWideStringField;
    qinftrabajadoresAPELLIDOS: TWideStringField;
    qinftrabajadoresDIRECCION: TWideStringField;
    qinftrabajadoresCP: TWideStringField;
    qinftrabajadoresPOBLACION: TWideStringField;
    qinftrabajadoresPROVINCIA: TWideStringField;
    qinftrabajadoresFECHANACIMIENTO: TDateField;
    qinftrabajadoresPAISNAC: TWideStringField;
    qinftrabajadoresNACIONALIDAD: TWideStringField;
    qinftrabajadoresSEXO: TWideStringField;
    qinftrabajadoresCBIBAN: TWideStringField;
    qinftrabajadoresCBBANCO: TWideStringField;
    qinftrabajadoresCBOFICINA: TWideStringField;
    qinftrabajadoresCBDC: TWideStringField;
    qinftrabajadoresCBCC: TWideStringField;
    qinftrabajadoresPAGARPORBANCO: TIntegerField;
    qinftrabajadoresTELEFONO1: TWideStringField;
    qinftrabajadoresTELEFONO2: TWideStringField;
    qinftrabajadoresTELEFONO3: TWideStringField;
    dsqaux: TDataSource;
    SaveDialog1: TSaveDialog;
    Panel15: TPanel;
    Label74: TLabel;
    Button2: TButton;
    Image2: TImage;
    Formacion: TTabSheet;
    Panel16: TPanel;
    qempleadosplanificacion: TZQuery;
    dsqempleadosplanificacion: TDataSource;
    Panel18: TPanel;
    DBEdit10: TDBEdit;
    Panel19: TPanel;
    Label16: TLabel;
    DBEdit13: TDBEdit;
    Panel20: TPanel;
    Label23: TLabel;
    Label24: TLabel;
    DBEdit20: TDBEdit;
    DBEdit21: TDBEdit;
    DBEdit26: TDBEdit;
    Label55: TLabel;
    Label56: TLabel;
    Label57: TLabel;
    Panel7: TPanel;
    Label19: TLabel;
    Label21: TLabel;
    Label22: TLabel;
    Label26: TLabel;
    DBEdit16: TDBEdit;
    DBEdit18: TDBEdit;
    DBEdit19: TDBEdit;
    DBEdit28: TDBEdit;
    DBCheckBox5: TDBCheckBox;
    DBCheckBox6: TDBCheckBox;
    DBCheckBox7: TDBCheckBox;
    Label46: TLabel;
    Label58: TLabel;
    DBEdit40: TDBEdit;
    DBLookupComboBox2: TDBLookupComboBox;
    Label59: TLabel;
    dsqpuestostrabajo: TDataSource;
    qpuestostrabajo: TZReadOnlyQuery;
    DBCheckBox8: TDBCheckBox;
    DBCheckBox9: TDBCheckBox;
    DBCheckBox10: TDBCheckBox;
    DBCheckBox11: TDBCheckBox;
    DBCheckBox12: TDBCheckBox;
    DBCheckBox13: TDBCheckBox;
    DBCheckBox14: TDBCheckBox;
    DBCheckBox15: TDBCheckBox;
    DBCheckBox16: TDBCheckBox;
    Label10: TLabel;
    DBCheckBox17: TDBCheckBox;
    qempleadosplanificacionidt: TSmallintField;
    qempleadosplanificacionide: TIntegerField;
    qempleadosplanificacionlocalizacion: TWideStringField;
    qempleadosplanificacionvto_permisotrabajo: TDateField;
    qempleadosplanificacionpuesto: TIntegerField;
    qempleadosplanificacionfecha_recmedico: TDateField;
    qempleadosplanificacionfecha_ren_recmedico: TDateField;
    qempleadosplanificaciontest_agricultura: TWideStringField;
    qempleadosplanificacionfecha_testcovid19: TDateField;
    qempleadosplanificacionformacionrecepdoc: TWideStringField;
    qempleadosplanificacionmanejo_maquinaria: TWideStringField;
    qempleadosplanificacionprimeros_auxilios: TWideStringField;
    qempleadosplanificacionfitosanitario_basico: TWideStringField;
    qempleadosplanificacionfitosanitario_cualificado: TWideStringField;
    qempleadosplanificacionformacion_riego: TWideStringField;
    qempleadosplanificacionbuenaspract_higiene: TWideStringField;
    qempleadosplanificacioncurso_sulfuroso: TWideStringField;
    qempleadosplanificacionmanipulador_frutas: TWideStringField;
    qempleadosplanificacionmantenimiento: TWideStringField;
    qempleadosplanificacionfecha_carnetmanipulador: TDateField;
    qempleadosplanificacionlimpieza: TWideStringField;
    qempleadosplanificacionembargos: TWideStringField;
    Label27: TLabel;
    Label31: TLabel;
    Label32: TLabel;
    Label33: TLabel;
    Label34: TLabel;
    Label35: TLabel;
    Label36: TLabel;
    Label13: TLabel;
    Label309: TLabel;
    DBText8: TDBText;
    DBEdit34: TDBEdit;
    DBEdit35: TDBEdit;
    DBEdit36: TDBEdit;
    DBEdit37: TDBEdit;
    DBMemo1: TDBMemo;
    DBCheckBox1: TDBCheckBox;
    DBCheckBox2: TDBCheckBox;
    DBCheckBox3: TDBCheckBox;
    DBEdit38: TDBEdit;
    DBCheckBox4: TDBCheckBox;
    DBEdit32: TDBEdit;
    DBEdit29: TDBEdit;
    DBEdit30: TDBEdit;
    DBEdit31: TDBEdit;
    DBEdit33: TDBEdit;
    DBLookupComboBox13: TDBLookupComboBox;
    DBLookupComboBox1: TDBLookupComboBox;
    Panel6: TPanel;
    Panel21: TPanel;
    Panel22: TPanel;
    Label14: TLabel;
    Button3: TButton;
    Button4: TButton;
    Button6: TButton;
    Button7: TButton;
    Button9: TButton;
    Panel24: TPanel;
    imgfoto: TImage;
    DBGrid4: TDBGrid;
    Button10: TButton;
    Memo1: TMemo;
    Button11: TButton;
    Panel25: TPanel;
    DBText3: TDBText;
    btplaceptar: TButton;
    btplcancelar: TButton;
    btplmodificar: TButton;
    qlistadoplanificacion: TZReadOnlyQuery;
    dsqlistadoplanificacion: TDataSource;
    qlistadoplanificacionidt: TSmallintField;
    qlistadoplanificacionide: TIntegerField;
    qlistadoplanificacionlocalizacion: TWideStringField;
    qlistadoplanificacionvto_permisotrabajo: TDateField;
    qlistadoplanificacionfecha_recmedico: TDateField;
    qlistadoplanificacionfecha_ren_recmedico: TDateField;
    qlistadoplanificaciontest_agricultura: TWideStringField;
    qlistadoplanificacionfecha_testcovid19: TDateField;
    qlistadoplanificacionformacionrecepdoc: TWideStringField;
    qlistadoplanificacionmanejo_maquinaria: TWideStringField;
    qlistadoplanificacionprimeros_auxilios: TWideStringField;
    qlistadoplanificacionfitosanitario_basico: TWideStringField;
    qlistadoplanificacionfitosanitario_cualificado: TWideStringField;
    qlistadoplanificacionformacion_riego: TWideStringField;
    qlistadoplanificacionbuenaspract_higiene: TWideStringField;
    qlistadoplanificacioncurso_sulfuroso: TWideStringField;
    qlistadoplanificacionmanipulador_frutas: TWideStringField;
    qlistadoplanificacionmantenimiento: TWideStringField;
    qlistadoplanificacionfecha_carnetmanipulador: TDateField;
    qlistadoplanificacionlimpieza: TWideStringField;
    qlistadoplanificacionembargos: TWideStringField;
    qlistadoplanificacionnombre: TWideStringField;
    qlistadoplanificacionnif: TWideStringField;
    qlistadoplanificacionfechaalta: TDateField;
    qlistadoplanificacionfechabaja: TDateField;
    dsdocumentos: TDataSource;
    OpenDialog2: TOpenDialog;
    dsqjornales: TDataSource;
    qjornales: TZQuery;
    dsqanticipos: TDataSource;
    qanticipos: TZQuery;
    documentos: TZQuery;
    documentosid: TIntegerField;
    documentoside: TIntegerField;
    documentosfecha: TDateField;
    documentosdescripcion: TWideStringField;
    documentosnomarchivo: TWideStringField;
    documentosextension: TWideStringField;
    documentosidt: TIntegerField;
    documentos_tmp: TZTable;
    Panel26: TPanel;
    btptcancelar: TButton;
    btptmodificar: TButton;
    btptborrar: TButton;
    btptnuevo: TButton;
    btptguardar: TButton;
    qtareas: TZReadOnlyQuery;
    dsqtareas: TDataSource;
    qparcelas: TZReadOnlyQuery;
    dsqparcelas: TDataSource;
    qtareasid: TWideStringField;
    qtareasnombre: TWideStringField;
    qtareasactivo: TIntegerField;
    qtareasempresa: TIntegerField;
    qtareascoste_elavoracion_campo: TIntegerField;
    qtareascoste_elavoracion_almacen: TIntegerField;
    qtareaselavoracion_produccion: TIntegerField;
    qtareasenvasado_produccion: TIntegerField;
    qtareaslogistica_produccion: TIntegerField;
    qtareasseleccionado: TIntegerField;
    qtareasalmacen_trabajo: TIntegerField;
    dsqentregasmaterial: TDataSource;
    qentregasmaterial: TZQuery;
    Tabentregas: TTabSheet;
    Panel27: TPanel;
    btEMcancelar: TButton;
    btEMmodificar: TButton;
    btEMborrar: TButton;
    btEMnuevo: TButton;
    btEMaceptar: TButton;
    btEMimprimir: TButton;
    Panel28: TPanel;
    DBText4: TDBText;
    DBGrid5: TDBGrid;
    Panel29: TPanel;
    DBGrid6: TDBGrid;
    Panel30: TPanel;
    qentregasmaterialid: TIntegerField;
    qentregasmaterialide: TIntegerField;
    qentregasmaterialidt: TIntegerField;
    qentregasmaterialfecha: TDateField;
    qentregasmaterialconcepto: TWideStringField;
    Panel31: TPanel;
    Label17: TLabel;
    Button8: TButton;
    Button13: TButton;
    fentregamaterial: TDateTimePicker;
    Label18: TLabel;
    Label20: TLabel;
    Edit1: TEdit;
    Label60: TLabel;
    Edit2: TEdit;
    qentregasmaterialcantidad: TFloatField;
    qlistadoentregasmaterial: TZReadOnlyQuery;
    dsqlistadoentregasmaterial: TDataSource;
    qlistadoentregasmaterialnombre: TWideStringField;
    qlistadoentregasmaterialnif: TWideStringField;
    qlistadoentregasmaterialid: TIntegerField;
    qlistadoentregasmaterialide: TIntegerField;
    qlistadoentregasmaterialidt: TIntegerField;
    qlistadoentregasmaterialfecha: TDateField;
    qlistadoentregasmaterialconcepto: TWideStringField;
    qlistadoentregasmaterialcantidad: TFloatField;
    qlistadoplanificaciondescripcion: TWideStringField;
    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;
    qjornalesfechainsmod: TDateTimeField;
    qjornalesusuario: TIntegerField;
    qjornalescontrol: TIntegerField;
    qjornaleshoras_nomina: TFloatField;
    qjornaleshoras_acumuladas: TFloatField;
    qjornalesidparte1: TIntegerField;
    qjornalesidparte2: TIntegerField;
    qparcelascodpar: TWideStringField;
    qparcelasnombre: TWideStringField;
    Button14: TButton;
    Panel32: TPanel;
    bteacancelar: TButton;
    bteamodificar: TButton;
    bteaborrar: TButton;
    bteanuevo: TButton;
    bteaguardar: TButton;
    bteaimprimir: TButton;
    qanticiposid: TIntegerField;
    qanticiposidt: TIntegerField;
    qanticipostrabajador: TWideStringField;
    qanticiposfecha: TDateField;
    qanticiposimporte: TFloatField;
    qanticiposindemnizacion: TFloatField;
    qanticipospenalizacion: TFloatField;
    qanticiposobservaciones: TWideStringField;
    qanticiposestado: TWideStringField;
    qanticiposformapago: TWideStringField;
    qanticiposimporteletras: TWideStringField;
    qanticiposembargo: TFloatField;
    OpenPictureDialog1: TOpenPictureDialog;
    DBMemo2: TDBMemo;
    Label39: TLabel;
    qempleadosplanificacionobservaciones: TWideStringField;
    Panel33: TPanel;
    Label4: TLabel;
    Label8: TLabel;
    Label29: TLabel;
    DBEdit3: TDBEdit;
    DBEdit7: TDBEdit;
    DBCheckBox26: TDBCheckBox;
    listagrupos: TDBLookupComboBox;
    Panel34: TPanel;
    Panel35: TPanel;
    Panel36: TPanel;
    Label43: TLabel;
    Button5: TButton;
    Button15: TButton;
    Button16: TButton;
    Button17: TButton;
    Button19: TButton;
    Panel37: TPanel;
    DBGrid7: TDBGrid;
    Button20: TButton;
    Memo2: TMemo;
    Button21: TButton;
    DBEdit11: TDBEdit;
    qlistadoplanificacionpuesto: TIntegerField;
    qlistadoplanificacionobservaciones: TWideStringField;
    qlistadoplanificaciontipo_carnetconducir: TWideStringField;
    qlistadoplanificacionfecha_caducidadconducir: TDateField;
    qlistadoplanificacionfecha_cursosulfuroso: TDateField;
    qempleadosplanificaciontipo_carnetconducir: TWideStringField;
    qempleadosplanificacionfecha_caducidadconducir: TDateField;
    qempleadosplanificacionfecha_cursosulfuroso: TDateField;
    DBCheckBox18: TDBCheckBox;
    DBEdit12: TDBEdit;
    Label61: TLabel;
    Label62: TLabel;
    DBEdit14: TDBEdit;
    qlistadoplanificacioncarnet_conducir: TWideStringField;
    qempleadosplanificacioncarnet_conducir: TWideStringField;
    qlistaempleadosvto_permisotrabajo: TDateField;
    dsqplantillaextincion: TDataSource;
    qplantillaextincion: TZQuery;
    dsqplantillacomunicacion: TDataSource;
    qplantillacomunicacion: TZQuery;
    qplantillacomunicacionid: TSmallintField;
    qplantillacomunicacionnif: TWideStringField;
    qplantillacomunicacionnombre: TWideStringField;
    qplantillacomunicacionfechabaja: TDateField;
    qplantillacomunicacionjorreales: TWideStringField;
    qplantillacomunicacioncausa: TWideStringField;
    qplantillacomunicaciond1: TWideStringField;
    qplantillacomunicaciond2: TWideStringField;
    qplantillacomunicaciond3: TWideStringField;
    qplantillacomunicaciond4: TWideStringField;
    qplantillacomunicaciond5: TWideStringField;
    qplantillacomunicaciond6: TWideStringField;
    qplantillacomunicaciond7: TWideStringField;
    qplantillacomunicaciond8: TWideStringField;
    qplantillacomunicaciond9: TWideStringField;
    qplantillacomunicaciond10: TWideStringField;
    qplantillacomunicaciond11: TWideStringField;
    qplantillacomunicaciond12: TWideStringField;
    qplantillacomunicaciond13: TWideStringField;
    qplantillacomunicaciond14: TWideStringField;
    qplantillacomunicaciond15: TWideStringField;
    qplantillacomunicaciond16: TWideStringField;
    qplantillacomunicaciond17: TWideStringField;
    qplantillacomunicaciond18: TWideStringField;
    qplantillacomunicaciond19: TWideStringField;
    qplantillacomunicaciond20: TWideStringField;
    qplantillacomunicaciond21: TWideStringField;
    qplantillacomunicaciond22: TWideStringField;
    qplantillacomunicaciond23: TWideStringField;
    qplantillacomunicaciond24: TWideStringField;
    qplantillacomunicaciond25: TWideStringField;
    qplantillacomunicaciond26: TWideStringField;
    qplantillacomunicaciond27: TWideStringField;
    qplantillacomunicaciond28: TWideStringField;
    qplantillacomunicaciond29: TWideStringField;
    qplantillacomunicaciond30: TWideStringField;
    qplantillacomunicaciond31: TWideStringField;
    qplantillaextincionid: TSmallintField;
    qplantillaextincionnif: TWideStringField;
    qplantillaextincionnombre: TWideStringField;
    qplantillaextincionjorreales: TWideStringField;
    qplantillaextinciond1: TWideStringField;
    qplantillaextinciond2: TWideStringField;
    qplantillaextinciond3: TWideStringField;
    qplantillaextinciond4: TWideStringField;
    qplantillaextinciond5: TWideStringField;
    qplantillaextinciond6: TWideStringField;
    qplantillaextinciond7: TWideStringField;
    qplantillaextinciond8: TWideStringField;
    qplantillaextinciond9: TWideStringField;
    qplantillaextinciond10: TWideStringField;
    qplantillaextinciond11: TWideStringField;
    qplantillaextinciond12: TWideStringField;
    qplantillaextinciond13: TWideStringField;
    qplantillaextinciond14: TWideStringField;
    qplantillaextinciond15: TWideStringField;
    qplantillaextinciond16: TWideStringField;
    qplantillaextinciond17: TWideStringField;
    qplantillaextinciond18: TWideStringField;
    qplantillaextinciond19: TWideStringField;
    qplantillaextinciond20: TWideStringField;
    qplantillaextinciond21: TWideStringField;
    qplantillaextinciond22: TWideStringField;
    qplantillaextinciond23: TWideStringField;
    qplantillaextinciond24: TWideStringField;
    qplantillaextinciond25: TWideStringField;
    qplantillaextinciond26: TWideStringField;
    qplantillaextinciond27: TWideStringField;
    qplantillaextinciond28: TWideStringField;
    qplantillaextinciond29: TWideStringField;
    qplantillaextinciond30: TWideStringField;
    qplantillaextinciond31: TWideStringField;
    dsqempleadosnacion: TDataSource;
    qempleadosnacion: TZQuery;
    gridempleadosnacion: TDBGrid;
    qempleadosnacionid: TSmallintField;
    qempleadosnacionnif: TWideStringField;
    qempleadosnacionnombre: TWideStringField;
    qempleadosnacionpaisnac: TWideStringField;
    qempleadosnacionnacionalidad: TWideStringField;
    qplantillaextincionfechabaja: TDateField;
    qplantillaextincioncausa: TWideStringField;
    qlistadoplanificacionfechanacimiento: TDateField;
    documentos_tmpid: TIntegerField;
    documentos_tmpide: TIntegerField;
    documentos_tmpfecha: TDateField;
    documentos_tmpdescripcion: TWideStringField;
    documentos_tmparchivo: TBlobField;
    documentos_tmpnomarchivo: TWideStringField;
    documentos_tmpextension: TWideStringField;
    documentos_tmpidlote: TIntegerField;
    documentos_tmpcodpar: TWideStringField;
    documentos_tmpidea: TIntegerField;
    documentos_tmpidt: TIntegerField;
    frxRTFExport1: TfrxRTFExport;
    frxSimpleTextExport1: TfrxSimpleTextExport;
    GRIDPLANTILLAROPA: TDBGrid;
    qplantillaropa: TZQuery;
    dsqplantillaropa: TDataSource;
    qplantillaropaid: TSmallintField;
    qplantillaropanif: TWideStringField;
    qplantillaropanombre: TWideStringField;
    qplantillaropaGUANTES: TWideStringField;
    qplantillaropaCASULLA: TWideStringField;
    qplantillaropaCAMISETA: TWideStringField;
    qplantillaropaCOFIA: TWideStringField;
    qplantillaropaGORRA: TWideStringField;
    qplantillaropaTIJERA: TWideStringField;
    qplantillaropaFECHA: TWideStringField;
    qplantillaropaTAQUILLA: TWideStringField;
    Label63: TLabel;
    DBEdit15: TDBEdit;
    qempleadoscontrolcalidad: TIntegerField;
    qempleadoshorascontrato: TFloatField;
    btEimagen: TButton;
    imgfotoe: TImage;
    panelfotoe: TPanel;
    MenubtAimagen: TPopupMenu;
    Cargar1: TMenuItem;
    Capturar1: TMenuItem;
    btdesactivarcamara: TButton;
    btactivarcamara: TButton;
    btEoKimagen: TButton;
    Button1: TButton;
    Label64: TLabel;
    tfirmas: TImage;
    DBCheckBox19: TDBCheckBox;
    dsemp_firmas: TDataSource;
    listadocsfirma: TComboBox;
    Label65: TLabel;
    Button18: TButton;
    tfirmadocs: TImage;
    dsfirmasdoc: TDataSource;
    firmasdoc: TZTable;
    firmasdocide: TIntegerField;
    firmasdocidt: TIntegerField;
    firmasdocfirma: TBlobField;
    informefirmadoc: TfrxDBDataset;
    topdf: TfrxPDFExport;
    frxCheckBoxObject1: TfrxCheckBoxObject;
    Button22: TButton;
    TabSheet1: TTabSheet;
    Panel17: TPanel;
    Label15: TLabel;
    Panel166: TPanel;
    Label73: TLabel;
    btedoccancelar: TButton;
    Button12: TButton;
    DBGrid75: TDBGrid;
    qanticiposide: TIntegerField;
    qemp_fotos: TZQuery;
    qemp_fotoside: TIntegerField;
    qemp_fotosidt: TIntegerField;
    qemp_fotosimagen: TBlobField;
    qemp_fotosextension: TWideStringField;
    qemp_firmas: TZQuery;
    qemp_firmasid: TIntegerField;
    qemp_firmaside: TIntegerField;
    qemp_firmasidt: TIntegerField;
    qemp_firmasfirma: TBlobField;
    qtemp_doc: TZQuery;
    qtemp_docid: TIntegerField;
    qtemp_docide: TIntegerField;
    qtemp_docarchivo: TBlobField;
    qtemp_docextension: TWideStringField;
    qtemp_docnomarchivo: TWideStringField;
    qempleadosCONTINGENCIAS: TFloatField;
    qinftrabajadoreside: TIntegerField;
    qinftrabajadoresTELEFONO4: TWideStringField;
    qinftrabajadoresREGIMEN_COT: TWideStringField;
    qinftrabajadoresNUMSEGSOCIAL: TWideStringField;
    qinftrabajadoresIRPF: TFloatField;
    qinftrabajadoresIRPF2: TFloatField;
    qinftrabajadoresDESEMPLEO: TFloatField;
    qinftrabajadoresDESEMPLEO2: TFloatField;
    qinftrabajadoresFORMACION: TFloatField;
    qinftrabajadoresFORMACION2: TFloatField;
    qinftrabajadoresIMAGEN: TIntegerField;
    qinftrabajadoresOBSERVACIONES: TWideStringField;
    qinftrabajadoresFECHAALTA: TDateField;
    qinftrabajadoresFECHABAJA: TDateField;
    qinftrabajadoresCONTINGENCIAS: TFloatField;
    qinftrabajadoresempresa: TIntegerField;
    qinftrabajadoresseleccionado: TIntegerField;
    qinftrabajadorescodart: TWideStringField;
    qinftrabajadorescontrolcalidad: TIntegerField;
    qinftrabajadoreshorascontrato: TFloatField;
    qinftrabajadoresimagen_1: TBlobField;
    qempleadosFIJO: TIntegerField;
    qempleadosFIJODISCONTINUO: TIntegerField;
    qempleadosTEMPORAL: TIntegerField;
    qinftrabajadoresFIJO: TIntegerField;
    qinftrabajadoresFIJODISCONTINUO: TIntegerField;
    qinftrabajadoresTEMPORAL: TIntegerField;
    Label66: TLabel;
    DBEdit41: TDBEdit;
    qempleadosnum_taquilla: TIntegerField;
    Label68: TLabel;
    DBEdit42: TDBEdit;
    qempleadosemail: TWideStringField;
    Label69: TLabel;
    DBEdit43: TDBEdit;
    qempleadosconvocatoria: TWideStringField;
    dsqconvocatorias: TDataSource;
    qconvocatorias: TZReadOnlyQuery;
    qconvocatoriasconvocatoria: TWideStringField;
    listaconvocatorias: TDBLookupListBox;
    DBEdit44: TDBEdit;
    Label75: TLabel;
    DBEdit45: TDBEdit;
    Label76: TLabel;
    Button23: TButton;
    qid: TZReadOnlyQuery;
    qidid: TLargeintField;
    qempleadosnacionnum_taquilla: TIntegerField;
    qemp_historico: TZQuery;
    qemp_historicoide: TIntegerField;
    qemp_historicoidt: TIntegerField;
    qemp_historicofecha_alta: TDateField;
    qemp_historicofecha_baja: TDateField;
    qemp_historicomotivo_alta: TWideStringField;
    qemp_historicomotivo_baja: TWideStringField;
    dsqemp_historico: TDataSource;
    dsqempresaformularios: TDataSource;
    qempresaformularios: TZReadOnlyQuery;
    comboformulario: TDBLookupComboBox;
    qempresaformularioscif: TWideStringField;
    qempresaformulariosnombre: TWideStringField;
    INFEMPRESAEMP: TfrxDBDataset;
    qemp_historicofecha_incorporacion: TDateField;
    Label77: TLabel;
    DBEdit46: TDBEdit;
    qemp_historicofecha_desconexion: TDateField;
    Label78: TLabel;
    DBEdit47: TDBEdit;
    qtaquillas: TZReadOnlyQuery;
    qtaquillasid: TIntegerField;
    qaltasbajas: TZQuery;
    qtripartita: TZReadOnlyQuery;
    dsqtripartita: TDataSource;
    GRIDTRIPARTITA: TDBGrid;
    qempresaformulariosid: TIntegerField;
    qtripartitaid: TSmallintField;
    qtripartitaapellidos: TWideStringField;
    qtripartitanombre: TWideStringField;
    qtripartitanif: TWideStringField;
    qtripartitanumsegsocial: TWideStringField;
    qtripartitasexo: TWideStringField;
    qtripartitafechanacimiento: TDateField;
    qtripartitaemail: TWideStringField;
    qtripartitatelefono1: TWideStringField;
    qtripartitacategoria_prof: TFloatField;
    qtripartitagrupo_cotizacion: TFloatField;
    qtripartitanivel_estudios: TFloatField;
    qtripartitacif_empresa: TWideStringField;
    qtripartitacoste_cotiz: TFloatField;
    qtripartitacoste_bruto_hora: TFloatField;
    qtripartitaempresa: TWideStringField;
    qempresaformulariosdireccion: TWideStringField;
    qempresaformularioscodpost: TWideStringField;
    qempresaformulariospoblacion: TWideStringField;
    qempresaformulariosprovincia: TWideStringField;
    qempresaformulariosemail: TWideStringField;
    DBGrid8: TDBGrid;
    dsqepis: TDataSource;
    qepis: TZReadOnlyQuery;
    qepisid: TIntegerField;
    qepiside: TIntegerField;
    qepisdescripcion: TWideStringField;
    Panel38: TPanel;
    Button24: TButton;
    Button25: TButton;
    dsqinfentregasmaterial: TDataSource;
    qinfentregasmaterial: TZQuery;
    qinfentregasmaterialid: TIntegerField;
    qinfentregasmaterialide: TIntegerField;
    qinfentregasmaterialidt: TIntegerField;
    qinfentregasmaterialfecha: TDateField;
    qinfentregasmaterialconcepto: TWideStringField;
    qinfentregasmaterialcantidad: TFloatField;
    DBCheckBox20: TDBCheckBox;
    DBCheckBox21: TDBCheckBox;
    qempleadosresponsable: TIntegerField;
    qempleadosfumigador: TIntegerField;
    qempleadosgrupo: TIntegerField;
    qempleadosactivo: TIntegerField;
    qinftrabajadoresgrupo: TIntegerField;
    qinftrabajadoresactivo: TIntegerField;
    qinftrabajadoresnum_taquilla: TIntegerField;
    qinftrabajadoresemail: TWideStringField;
    qinftrabajadoresconvocatoria: TWideStringField;
    Label79: TLabel;
    DBEdit48: TDBEdit;
    qempleadosretencion_me: TFloatField;
    DBEdit49: TDBEdit;
    Label80: TLabel;
    qempleadosjornada_continua: TSmallintField;
    qempleadossalariobasedia: TFloatField;
    qemp_historicofecha_fin_contrato: TDateField;
    procedure FormShow(Sender: TObject);
    procedure dsqlistaempleadosDataChange(Sender: TObject; Field: TField);
    procedure tbuscarKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure tbuscarKeyPress(Sender: TObject; var Key: Char);
    procedure qlistaempleadosBeforeOpen(DataSet: TDataSet);
    procedure qlistaempleadosAfterOpen(DataSet: TDataSet);
    procedure listagrupos2CloseUp(Sender: TObject);
    procedure VaciarClick(Sender: TObject);
    procedure Vaciar2Click(Sender: TObject);
    procedure bteimprimirClick(Sender: TObject);
    procedure btnEnviarDocClick(Sender: TObject);
    procedure checktodos2Click(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure chktodosempleadosClick(Sender: TObject);
    procedure CargarFiltroSexo;
    procedure cbsexoChange(Sender: TObject);
    procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure FormKeyPress(Sender: TObject; var Key: Char);
    procedure btEguardarClick(Sender: TObject);
    procedure btEcancelarClick(Sender: TObject);
    procedure dsqempleadosStateChange(Sender: TObject);
    procedure DBLookupComboBox1DropDown(Sender: TObject);
    procedure DBEdit8Change(Sender: TObject);
    procedure DBEdit27Change(Sender: TObject);
    procedure btEborrarClick(Sender: TObject);
    procedure btEmodificarClick(Sender: TObject);
    procedure dsqempleadosplanificacionStateChange(Sender: TObject);
    procedure btplmodificarClick(Sender: TObject);
    procedure btplaceptarClick(Sender: TObject);
    procedure btplcancelarClick(Sender: TObject);
    procedure btedoccancelarClick(Sender: TObject);
    procedure Button9Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Button6Click(Sender: TObject);
    procedure Button7Click(Sender: TObject);
    procedure TanyoChange(Sender: TObject);
    procedure TESTADOChange(Sender: TObject);
    procedure Button11Click(Sender: TObject);
    procedure Button10Click(Sender: TObject);
    procedure btEMnuevoClick(Sender: TObject);
    procedure btEMaceptarClick(Sender: TObject);
    procedure btEMcancelarClick(Sender: TObject);
    procedure btEMmodificarClick(Sender: TObject);
    procedure btEMborrarClick(Sender: TObject);
    procedure PageEmpleadosChange(Sender: TObject);
    procedure Button8Click(Sender: TObject);
    procedure Button12Click(Sender: TObject);
    procedure DBEdit9Exit(Sender: TObject);
    procedure DBEdit21KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure DBEdit21Exit(Sender: TObject);
    procedure FechaPlanificacionSetText(Sender: TField; const Text: string);
    procedure FechaPlanificacionGetText(Sender: TField; var Text: string; DisplayText: Boolean);
    procedure ConfigurarCamposFechaPlanificacion;
    procedure qempleadosplanificacionBeforePost(DataSet: TDataSet);
    procedure qempleadosplanificacionfecha_recmedicoValidate(Sender: TField);
    procedure qempleadosplanificacionvto_permisotrabajoValidate(Sender: TField);
    procedure qempleadosplanificacionfecha_ren_recmedicoValidate(
      Sender: TField);
    procedure qempleadosplanificacionfecha_testcovid19Validate(Sender: TField);
    procedure qempleadosplanificacionfecha_carnetmanipuladorValidate(
      Sender: TField);
    procedure DBEdit26Exit(Sender: TObject);
    procedure DBEdit40Exit(Sender: TObject);
    procedure DBEdit13Exit(Sender: TObject);
    procedure DBEdit10Exit(Sender: TObject);
    procedure DBEdit26KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure DBEdit40KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure DBEdit13KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure DBEdit10KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure dsqjornalesStateChange(Sender: TObject);
    procedure btptnuevoClick(Sender: TObject);
    procedure btptmodificarClick(Sender: TObject);
    procedure btptborrarClick(Sender: TObject);
    procedure btptguardarClick(Sender: TObject);
    procedure DBGrid2DrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumn; State: TGridDrawState);
    procedure ltipohoraCloseUp(Sender: TObject);
    procedure Button14Click(Sender: TObject);
    procedure btptcancelarClick(Sender: TObject);
    procedure dsqanticiposStateChange(Sender: TObject);
    procedure bteanuevoClick(Sender: TObject);
    procedure bteaborrarClick(Sender: TObject);
    procedure bteamodificarClick(Sender: TObject);
    procedure bteaguardarClick(Sender: TObject);
    procedure bteacancelarClick(Sender: TObject);
    procedure DBGrid2CellClick(Column: TColumn);
    procedure Button15Click(Sender: TObject);
    procedure DBGrid1TitleClick(Column: TColumn);
    procedure qempleadosBeforePost(DataSet: TDataSet);
    procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumn; State: TGridDrawState);
    procedure DBGrid75DrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumn; State: TGridDrawState);
    procedure tbuscarExit(Sender: TObject);
    procedure dsqregimencotizacionDataChange(Sender: TObject; Field: TField);
    procedure btEimagenClick(Sender: TObject);
    procedure Cargar1Click(Sender: TObject);
    procedure Capturar1Click(Sender: TObject);
    procedure btactivarcamaraClick(Sender: TObject);
    procedure btdesactivarcamaraClick(Sender: TObject);
    procedure btEoKimagenClick(Sender: TObject);
    procedure Button18Click(Sender: TObject);
    procedure Image2DblClick(Sender: TObject);
    procedure Button22Click(Sender: TObject);
    procedure qempleadosBeforeDelete(DataSet: TDataSet);
    procedure DBEdit43Enter(Sender: TObject);
    procedure listaconvocatoriasExit(Sender: TObject);
    procedure listaconvocatoriasDblClick(Sender: TObject);
    procedure Button23Click(Sender: TObject);
    procedure btEnuevoClick(Sender: TObject);
    procedure qempleadosAfterInsert(DataSet: TDataSet);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure qempleadosAfterPost(DataSet: TDataSet);
    procedure qemp_historicoBeforePost(DataSet: TDataSet);
    procedure qemp_historicoBeforeDelete(DataSet: TDataSet);
    procedure qemp_historicoAfterPost(DataSet: TDataSet);
    procedure DBEdit41KeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure Button24Click(Sender: TObject);
    procedure Button25Click(Sender: TObject);
    procedure DBGrid5CellClick(Column: TColumn);
    procedure btEMimprimirClick(Sender: TObject);
    procedure tanyo2Change(Sender: TObject);
  private
    { Private declarations }
    hWndC,hWndC2 : THandle;
    procedure SetResolution(Width, Height: integer);
    procedure CargarBlobEnImagen(CampoBlob: TBlobField; Destino: TPicture; const Ext: string);
    procedure CargarDatosEmpleadoActual(ActiveTabIndex: Integer);
    procedure FiltrarListaEmpleados;
  public
    { Public declarations }
    procedure ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar = nil);

  end;

var
  fempleados: Tfempleados;
  filtrotrabajadores,todostrabajadores,tlimitado,filtrolotes,filtroparcelas:string;
  vtactivo,seleccionando:integer;
  pidt,pide:integer;
const

  WM_CAP_START         = WM_USER;
  WM_CONNECT           = WM_USER + 10;
  WM_DISCONNECT        = WM_USER + 11;
  WM_SAVEDIB                  = WM_USER + 25;
  WM_GET_VIDEOFORMAT          = WM_USER + 44;
  WM_SET_VIDEOFORMAT          = WM_USER + 45;
  WM_SET_PREVIEW              = WM_USER + 50;
  WM_SET_OVERLAY              = WM_USER + 51;
  WM_SET_PREVIEWRATE          = WM_USER + 52;
  WM_SET_SCALE                = WM_USER + 53;
  rojo=$00AAAAFF;
  amarillo=$00B9FFFF;
  verde=$00C7FBAA;
  azul=$00FFFFBB;


function capCreateCaptureWindowA(lpszWindowName: PCHAR; dwStyle, x, y, nWidth, nHeight: integer; ParentWin: HWND; nId: integer): HWND; stdcall external 'AVICAP32.DLL';


implementation

{$R *.dfm}

uses fdlgfecha,shellapi, datos, fdlgllamamientos, femphistorico, principal,
  fseleccionartaquilla, fdlgfechas;


function Letra(Numero: Integer): string;
begin
  Result:= copy('TRWAGMYFPDXBNJZSQVHLCKET',1 + numero mod 23,1);
end;
function EsNif(NIF: String): Boolean;
var
  Numero: Integer;
begin
   Result:= FALSE;
   if TryStrToInt(Copy(NIF,1,Length(NIF)-1),Numero) then
      Result:= Uppercase(Copy(NIF,Length(NIF),1)) = Letra(Numero);
end;

function EsNumero(Num: Char): Boolean;
begin
  try
    StrToInt(Num);
    Result:=True;
  Except
    result:=False;
  end;
end;

function CadCambioCar(Cadena, CarOrig, CarCambio : String) : String;
var
 i : Integer;
 Temp : String;
begin
 Temp := '';
 for i := 1 to Length(Cadena) do
 if Copy(Cadena, i, 1) = CarOrig then
 Temp := Temp + CarCambio
 else
 Temp := Temp + Copy(Cadena, i, 1);
 Result := Temp;
end;
function EsCif(Cif : String) : Boolean;
var
 Suma, Control : Integer;
 n : Byte;
begin
 Result := False;
 {Se pasa todo a may�sculas limpio de espacios y de caracteres especiales}
 Cif := UpperCase(Trim(Cif));
 {Se limpia de los caracteres '-' y '/'. }
 Cif := CadCambioCar(Cif,'-','');
 Cif := CadCambioCar(Cif,'/','');
 {El cif debe ser de 9 cifras}
 if Length(Cif) = 9 then
 begin
 {Comprobamos que sea un NIF}
 if EsNumero(Cif[1]) then
 Result := EsNif(Cif)
 else
 {Se comprueba que la letra que designa el tipo de cif sea correcta}
 if (Pos(Cif[1], 'ABCDEFGHPQSKLMX') = 0) then
 Result := False
 else
 {Se comprueba si es un extranjero,
 en ese caso se calcula el nif, cambiando la X, por 0}
 if Cif[1] = 'X' then
 Result := EsNif('0'+Copy(Cif,2,8))
 else
 begin
 Suma:= StrToInt(Cif[3])+StrToInt(Cif[5])+StrToInt(Cif[7]);
 for n := 1 to 4 do
 Suma := Suma + ((2*StrToInt(Cif[2*n])) mod 10)+((2*StrToInt(Cif[2*n])));
 Control := 10 - (Suma mod 10);
 {Se comprueba si es de tipo 'P' o 'S', es decir,
 Corporaciones Locales (Ayuntamientos, etc.)
 y Organismos p�blicos.}
 if Pos(Cif[1],'PS')<>0 then
 {Control tipo letra}
 Result := (Cif[9] = Chr(64+Control))
 else
 {Resto de tipos de CIF}
 begin
 {Control tipo n�mero}
 if Control = 10 then
 Control := 0;
 Result:= ( StrToInt(Cif[9]) = Control);
 end;
 end;
 end;
end;
procedure Tfempleados.SetResolution(Width, Height: integer);
var
  bi,bi2: BITMAPINFO;
begin
  SendMessage(hWndC, WM_GET_VIDEOFORMAT, sizeof(bi), Cardinal(@bi));
  bi.bmiHeader.biWidth:= Width;
  bi.bmiHeader.biHeight:= Height;

  if SendMessage(hWndC, WM_SET_VIDEOFORMAT, sizeof(bi), Cardinal(@bi)) <> 0 then
  begin
    SendMessage(hWndC, WM_DISCONNECT, 0, 0);
    SendMessage(hWndC, WM_CONNECT, 0, 0);

  end;

  bi2.bmiHeader.biWidth:= Width;
  bi2.bmiHeader.biHeight:= Height;
  SendMessage(hWndC2, WM_GET_VIDEOFORMAT, sizeof(bi2), Cardinal(@bi2));
  if SendMessage(hWndC2, WM_SET_VIDEOFORMAT, sizeof(bi2), Cardinal(@bi2)) <> 0 then
  begin
    SendMessage(hWndC2, WM_DISCONNECT, 0, 0);
    SendMessage(hWndC2, WM_CONNECT, 0, 0);

  end;

end;
procedure Tfempleados.btactivarcamaraClick(Sender: TObject);
begin
    Panelfotoe.Width:= 120;
    Panelfotoe.Height:= 120;
    hWndC := capCreateCaptureWindowA('Ventana de captura', WS_CHILD or WS_VISIBLE ,0, 0,Panelfotoe.Height,Panelfotoe.Width,Panelfotoe.Handle,0);

      if hWndC <> 0 then
      begin
        SendMessage(hWndC, WM_CONNECT, 0, 0);
        SendMessage(hWndC, WM_SET_SCALE, 1, 0);
        SendMessage(hWndC, WM_SET_PREVIEWRATE, 20, 0);
        SendMessage(hWndC, WM_SET_OVERLAY, 1, 0);
        SendMessage(hWndC, WM_SET_PREVIEW, 1, 0);
        SetResolution(Panelfotoe.Height,Panelfotoe.Width);
//        SetResolution(1912,1072);
      end;
end;

procedure Tfempleados.btdesactivarcamaraClick(Sender: TObject);
begin
  if hWndC <> 0 then
  begin
    SendMessage(hWndC, WM_DISCONNECT, 0, 0);
  end;

end;

procedure Tfempleados.bteaborrarClick(Sender: TObject);
begin
   qanticipos.Delete;
end;

procedure Tfempleados.bteacancelarClick(Sender: TObject);
begin
   qanticipos.Cancel;
end;

procedure Tfempleados.bteaguardarClick(Sender: TObject);
begin
    if limporteanticipo.Text<>'' then limporteanticipo.Text:=stringreplace((limporteanticipo.Text),'.',',',[rfreplaceall]);
    if qanticipos.State=dsedit then
    begin
        qanticiposfecha.Value:=fechaanticipo.Date;
        if lopciones.ItemIndex=0 then
        begin
            qanticiposimporte.Value:=strtofloat(limporteanticipo.Text);
            qanticipospenalizacion.Value:=0;
            qanticiposindemnizacion.Value:=0;
            qanticiposembargo.value:=0;
        end;
        if lopciones.ItemIndex=1 then
        begin
            qanticiposimporte.Value:=0;
            qanticipospenalizacion.Value:=0;
            qanticiposindemnizacion.Value:=strtofloat(limporteanticipo.Text);
            qanticiposembargo.value:=0;
        end;
        if lopciones.ItemIndex=2 then
        begin
            qanticiposimporte.Value:=0;
            qanticipospenalizacion.Value:=strtofloat(limporteanticipo.Text);
            qanticiposindemnizacion.Value:=0;
            qanticiposembargo.value:=0;
        end;
        if lopciones.ItemIndex=3 then
        begin
            qanticiposimporte.Value:=0;
            qanticipospenalizacion.Value:=0;
            qanticiposindemnizacion.Value:=0;
            qanticiposembargo.value:=strtofloat(limporteanticipo.Text);

        end;

        qanticiposobservaciones.Value:=lobservaciones.Text;
        qanticiposestado.Value:='C';
        qanticipos.Post;
    end;
    if qanticipos.State=dsinsert then
    begin

        qaux.Close;
        qaux.SQL.Clear;
        qaux.SQL.Add('select max(id)+1 from anticipos');
        qaux.Open;
        qanticiposid.Value:=qaux.Fields[0].Asinteger;
        qanticiposfecha.Value:=fechaanticipo.Date;
        qanticiposidt.Value:=qlistaempleadosid.asinteger;
        qanticipostrabajador.value:=qlistaempleadosnombre.AsString;
        if lopciones.ItemIndex=0 then
        begin
            qanticiposimporte.Value:=strtofloat(limporteanticipo.Text);
            qanticipospenalizacion.Value:=0;
            qanticiposindemnizacion.Value:=0;
            qanticiposembargo.value:=0;
        end;
        if lopciones.ItemIndex=1 then
        begin
            qanticiposimporte.Value:=0;
            qanticipospenalizacion.Value:=0;
            qanticiposindemnizacion.Value:=strtofloat(limporteanticipo.Text);
            qanticiposembargo.value:=0;
        end;
        if lopciones.ItemIndex=2 then
        begin
            qanticiposimporte.Value:=0;
            qanticipospenalizacion.Value:=strtofloat(limporteanticipo.Text);
            qanticiposindemnizacion.Value:=0;
            qanticiposembargo.value:=0;
        end;
        if lopciones.ItemIndex=3 then
        begin
            qanticiposimporte.Value:=0;
            qanticipospenalizacion.Value:=0;
            qanticiposindemnizacion.Value:=0;
            qanticiposembargo.value:=strtofloat(limporteanticipo.Text);
        end;
        qanticiposobservaciones.Value:=UPPERCASE(lobservaciones.Text);
        qanticiposestado.Value:='C';
        qanticipos.Post;
    end;

end;

procedure Tfempleados.bteamodificarClick(Sender: TObject);
begin
   qanticipos.Edit;
   fechaanticipo.SetFocus;
end;

procedure Tfempleados.bteanuevoClick(Sender: TObject);
begin
    qanticipos.Append;
    fechaanticipo.SetFocus;
end;

procedure Tfempleados.btEborrarClick(Sender: TObject);
begin
    qempleados.Delete;
    qlistaempleados.Refresh;
end;

procedure Tfempleados.btEcancelarClick(Sender: TObject);
begin
    if qempleados.State in [dsedit,dsinsert] then qempleados.Cancel;
    if qempleadosplanificacion.State in [dsedit,dsinsert] then qempleadosplanificacion.Cancel;
    panel33.Enabled:=false;
    panel9.Enabled:=false;

end;

procedure Tfempleados.btedoccancelarClick(Sender: TObject);
var archivo:string;
begin

    savedialog1.FileName:='PLANIFICACION-FORMACI�N.xlsx';
    savedialog1.Execute();
    archivo:=savedialog1.FileName;
    try
    Exportaraexcel(archivo,'PLANIFICACION-FORMACIN.xlsx',dbgrid75);
    finally
      showmessage('Los datos han sido exportados correctamente a '+archivo);
    end;
end;

procedure Tfempleados.bteimprimirClick(Sender: TObject);
var i,diacomunicacion,mescomunicacion,anyocomunicacion,vimprimirfecha:integer;
    actual : TBookMarkStr;
    archivo,fecha,fecha2,fechamenos3,fechamenos3texto,fechamenos15,fechamenos15texto,textmes,llamamiento:string;
    dia,mes,anyo:word;
    sfecha:tdate;
    shora,sfecha2:string;
    LIds, LFiltroConT, LFiltroSinT, LFiltroLlamamiento: string;
begin
    Deletefile('c:\agrigest\tmp\firma.bmp');
    seleccionando:=1;
     if listaimpresion.itemindex=-1 then listaimpresion.itemindex:=0;

    if (listaimpresion.ItemIndex>=10) and (listaimpresion.ItemIndex<=14) then
    begin
        dlgfecha := Tdlgfecha.Create(nil);
      try
        dlgfecha.showmodal();
      finally
        sfecha:=strtodate(dlgfecha.lfecha.text);
        if dlgfecha.CheckBox1.Checked then vimprimirfecha:=1 else vimprimirfecha:=0;
        dlgfecha.Free;
      end;
    end else sfecha:=date();
    if listaimpresion.ItemIndex=17 then
    begin
      dlgllamamientos := tdlgllamamientos.create(nil);
      try
        dlgllamamientos.showmodal();
      finally
        llamamiento:=dlgllamamientos.qconvocatoriasconvocatoria.asstring;
        sfecha:=strtodate(dlgllamamientos.lfecha.text);
        sfecha2:=dlgllamamientos.lfecha2.text;
        shora:=dlgllamamientos.lhora.Text;
        dlgllamamientos.Free;
      end;
    end;
    decodedate(sfecha,anyo,mes,dia);
    case mes of
        1: textmes:='enero';
        2: textmes:='febrero';
        3: textmes:='marzo';
        4: textmes:='abril';
        5: textmes:='mayo';
        6: textmes:='junio';
        7: textmes:='julio';
        8: textmes:='agosto';
        9: textmes:='septiembre';
        10: textmes:='octubre';
        11: textmes:='noviembre';
        12: textmes:='diciembre';
    end;
    fecha:=floattostr(dia)+' de '+textmes+' de '+floattostr(anyo);

    mescomunicacion:=mes;
    anyocomunicacion:=anyo;
    diacomunicacion:=dia-3;
    if diacomunicacion<1 then
    begin
       mescomunicacion:=mescomunicacion-1;
       case mescomunicacion of
        1: diacomunicacion:=31+diacomunicacion;
        2: diacomunicacion:=28+diacomunicacion;
        3: diacomunicacion:=31+diacomunicacion;
        4: diacomunicacion:=30+diacomunicacion;
        5: diacomunicacion:=31+diacomunicacion;
        6: diacomunicacion:=30+diacomunicacion;
        7: diacomunicacion:=31+diacomunicacion;
        8: diacomunicacion:=31+diacomunicacion;
        9: diacomunicacion:=30+diacomunicacion;
        10: diacomunicacion:=31+diacomunicacion;
        11: diacomunicacion:=30+diacomunicacion;
        12: diacomunicacion:=31+diacomunicacion;

       end;
    end;
    if mescomunicacion<1 then anyocomunicacion:=anyocomunicacion-1;
    case mescomunicacion of
        1: textmes:='enero';
        2: textmes:='febrero';
        3: textmes:='marzo';
        4: textmes:='abril';
        5: textmes:='mayo';
        6: textmes:='junio';
        7: textmes:='julio';
        8: textmes:='agosto';
        9: textmes:='septiembre';
        10: textmes:='octubre';
        11: textmes:='noviembre';
        12: textmes:='diciembre';
    end;

    fechamenos3texto:=floattostr(diacomunicacion)+' de '+textmes+' de '+floattostr(anyocomunicacion);
    fechamenos3:=floattostr(diacomunicacion)+'/'+floattostr(mescomunicacion)+'/'+floattostr(anyocomunicacion);
    mescomunicacion:=mes;
    anyocomunicacion:=anyo;
    diacomunicacion:=dia-15;
    if diacomunicacion<1 then
    begin
       mescomunicacion:=mescomunicacion-1;
       case mescomunicacion of
        1: diacomunicacion:=31+diacomunicacion;
        2: diacomunicacion:=28+diacomunicacion;
        3: diacomunicacion:=31+diacomunicacion;
        4: diacomunicacion:=30+diacomunicacion;
        5: diacomunicacion:=31+diacomunicacion;
        6: diacomunicacion:=30+diacomunicacion;
        7: diacomunicacion:=31+diacomunicacion;
        8: diacomunicacion:=31+diacomunicacion;
        9: diacomunicacion:=30+diacomunicacion;
        10: diacomunicacion:=31+diacomunicacion;
        11: diacomunicacion:=30+diacomunicacion;
        12: diacomunicacion:=31+diacomunicacion;

       end;
    end;
    if mescomunicacion<1 then anyocomunicacion:=anyocomunicacion-1;
        case mescomunicacion of
        1: textmes:='enero';
        2: textmes:='febrero';
        3: textmes:='marzo';
        4: textmes:='abril';
        5: textmes:='mayo';
        6: textmes:='junio';
        7: textmes:='julio';
        8: textmes:='agosto';
        9: textmes:='septiembre';
        10: textmes:='octubre';
        11: textmes:='noviembre';
        12: textmes:='diciembre';
    end;
    fechamenos15texto:=floattostr(diacomunicacion)+' de '+textmes+' de '+floattostr(anyocomunicacion);
    fecha2:=floattostr(dia)+'/'+floattostr(mes)+'/'+floattostr(anyo);

    fechamenos15:=floattostr(diacomunicacion)+'/'+floattostr(mescomunicacion)+'/'+floattostr(anyocomunicacion);
    if vimprimirfecha=0 then
    begin
      fecha:='';
      fechamenos15texto:='';//floattostr(diacomunicacion)+' de '+textmes+' de '+floattostr(anyocomunicacion);
      fecha2:='';//floattostr(dia)+'/'+floattostr(mes)+'/'+floattostr(anyo);
      fechamenos15:='';//floattostr(diacomunicacion)+'/'+floattostr(mescomunicacion)+'/'+floattostr(anyocomunicacion);
    end;

    if dbgrid1.SelectedRows.Count > 0 then
    begin
      LIds := '';
      for i := 0 to dbgrid1.SelectedRows.Count - 1 do
      begin
        qlistaempleados.GotoBookmark(dbgrid1.SelectedRows[i]);
        if LIds <> '' then
          LIds := LIds + ',' + qlistaempleadosid.AsString
        else
          LIds := qlistaempleadosid.AsString;
      end;
      LFiltroConT := ' t.id in (' + LIds + ') ';
      LFiltroSinT := ' id in (' + LIds + ') ';
    end
    else
    begin
      LFiltroConT := ' t.activo = 1 ';
      LFiltroSinT := ' activo = 1 ';
    end;

    case listaimpresion.ItemIndex of
        0:begin
            qinftrabajadores.Close;
            qinftrabajadores.SQL.Clear;
            qinftrabajadores.SQL.Add('select t.* ,f.imagen from trabajadores t left join emp_fotos f on t.ide=f.ide and t.id=f.idt where ' + LFiltroConT + ' order by nombre');
            qinftrabajadores.Open;
            informedb.Datasource:=dsqinftrabajadores;
            informes.Report.Clear;
            informes.LoadFromFile('c:\agrigest\informes\tarjeta2.fr3');
            informes.ShowReport();
         end;
        1: begin
            qinftrabajadores.Close;
            qinftrabajadores.SQL.Clear;
            qinftrabajadores.SQL.Add('select t.* ,f.imagen from trabajadores t left join emp_fotos f on t.ide=f.ide and t.id=f.idt where t.id='+qempleadosid.AsString+' order by nombre');
            qinftrabajadores.Open;
            informedb.Datasource:=dsqinftrabajadores;
            informes.Report.Clear;
            informes.LoadFromFile('c:\agrigest\informes\FICHAEMPLEADO.fr3');
            informes.ShowReport();
        end;
        2:begin
            qaux.close;
            qaux.SQL.Clear;
            qaux.SQL.Add('select * from trabajadores where ' + LFiltroSinT + ' order by nombre');
            qaux.Open;
            if qaux.RecordCount=0 then showmessage(' DEBE SELECCIONAR AL MENOS UN EMPLEADO ')
            else
               begin
                  informedb.Datasource:=dsqaux;
                  informes.Report.Clear;
                  informes.LoadFromFile('c:\agrigest\informes\plantillapartetrabajo.fr3');
                  informes.Variables.Variables['v_cuadrilla']:=QUOTEDSTR(qgrupos2descripcion.asstring);
                  informes.Variables.Variables['v_trabajadores']:=QUOTEDSTR(inttostr(qaux.RecordCount));
                  informes.ShowReport();
               end;


        end;
        3:begin
            qaux.close;
            qaux.SQL.Clear;
            qaux.SQL.Add('select * from trabajadores where ' + LFiltroSinT + ' order by nombre');
            qaux.Open;
            if qaux.RecordCount=0 then showmessage(' DEBE SELECCIONAR AL MENOS UN EMPLEADO ')
            else
               begin
                  informedb.Datasource:=dsqaux;
                  informes.Report.Clear;
                  informes.LoadFromFile('c:\agrigest\informes\plantillapartesemanal.fr3');
                  informes.Variables.Variables['v_cuadrilla']:=QUOTEDSTR(qgrupos2descripcion.asstring);
                  informes.Variables.Variables['v_trabajadores']:=QUOTEDSTR(inttostr(qaux.RecordCount));
                  informes.ShowReport();
               end;


        end;

        4:begin
            qaux.close;
            qaux.SQL.Clear;
            qaux.SQL.Add('select * from trabajadores where ' + LFiltroSinT + ' order by nombre');
            qaux.Open;
            if qaux.RecordCount=0 then showmessage(' DEBE SELECCIONAR AL MENOS UN EMPLEADO ')
            else
               begin
                  informedb.Datasource:=dsqaux;
                  informes.Report.Clear;
                  informes.LoadFromFile('c:\agrigest\informes\plantillapartealmacen.fr3');
                  informes.Variables.Variables['v_cuadrilla']:=QUOTEDSTR(qgrupos2descripcion.asstring);
                  informes.Variables.Variables['v_trabajadores']:=QUOTEDSTR(inttostr(qaux.RecordCount));
                  informes.ShowReport();
               end;
        end;

        5:begin
            qaux.close;
            qaux.SQL.Clear;
            qaux.SQL.Add('select * from trabajadores where ' + LFiltroSinT + ' order by nombre');
            qaux.Open;
            if qaux.RecordCount=0 then showmessage(' DEBE SELECCIONAR AL MENOS UN EMPLEADO ')
            else
               begin
                  informedb.Datasource:=dsqaux;
                  informes.Report.Clear;
                  informes.LoadFromFile('c:\agrigest\informes\plantillacontratacion.fr3');
                  informes.ShowReport();
               end;
        end;
        6:begin
            qplantillaextincion.Open;
            savedialog1.FileName:='PLANTILLA EXTINCION.xlsx0';
            savedialog1.Execute();
            archivo:=savedialog1.FileName;
            try
            Exportaraexcel(archivo,'PLANTILLA EXTINCION',GRIDPLANTILLAEXT);
            finally
              showmessage('Los datos han sido exportados correctamente a '+archivo);
            end;
            qplantillaextincion.Close;

        end;
        7:begin
           qplantillacomunicacion.Open;
            savedialog1.FileName:='PLANTILLA COMUNICACION.xlsx';
            savedialog1.Execute();
            archivo:=savedialog1.FileName;
            try
            Exportaraexcel(archivo,'PLANTILLA COMUNICACION',GRIDPLANTILLACOMU);
            finally
              showmessage('Los datos han sido exportados correctamente a '+archivo);
            end;
        end;

        8:begin
            qaux.close;
            qaux.SQL.Clear;
            qaux.SQL.Add('select * from trabajadores where ' + LFiltroSinT + ' order by nombre');
            qaux.Open;
            if qaux.RecordCount=0 then showmessage(' DEBE SELECCIONAR AL MENOS UN EMPLEADO ')
            else
               begin
                  informedb.Datasource:=dsqaux;
                  informes.Report.Clear;
                  informes.LoadFromFile('c:\agrigest\informes\plantillaropatrabajo.fr3');
                  informes.Variables.Variables['v_cuadrilla']:=QUOTEDSTR(qgrupos2descripcion.asstring);
                  informes.Variables.Variables['v_trabajadores']:=QUOTEDSTR(inttostr(qaux.RecordCount));
                  informes.ShowReport();
               end;
        end;
        9:begin
            qplantillaropa.Open;
            savedialog1.FileName:='PLANTILLA ROPA DE TRABAJO.xls';
            savedialog1.Execute();
            archivo:=savedialog1.FileName;
            try
            Exportaraexcel(archivo,'PLANTILLA ROPA DE TRABAJO',GRIDPLANTILLAROPA);
            finally
              showmessage('Los datos han sido exportados correctamente a '+archivo);
            end;

        end;
        10:begin
            qaux.close;
            qaux.SQL.Clear;
            qaux.SQL.Add('select * from trabajadores where ' + LFiltroSinT + ' order by nombre');
            qaux.Open;
            if qaux.RecordCount=0 then showmessage(' DEBE SELECCIONAR AL MENOS UN EMPLEADO ')
            else
               begin
                  informedb.Datasource:=dsqaux;
                  informes.Report.Clear;
                  informes.LoadFromFile('c:\agrigest\informes\bajavoluntaria.fr3');
                  informes.Variables.Variables['v_fecha']:=QUOTEDSTR(fecha);
                  informes.Variables.Variables['v_fecha2']:=QUOTEDSTR(fecha2);
                  informes.ShowReport();
               end;
        end;
        11:begin
            qaux.close;
            qaux.SQL.Clear;
            qaux.SQL.Add('select * from trabajadores where ' + LFiltroSinT + ' order by nombre');
            qaux.Open;
            if qaux.RecordCount=0 then showmessage(' DEBE SELECCIONAR AL MENOS UN EMPLEADO ')
            else
               begin
                  informedb.Datasource:=dsqaux;
                  informes.Report.Clear;
                  informes.LoadFromFile('c:\agrigest\informes\bajafincontrato.fr3');
                  informes.Variables.Variables['v_fecha']:=QUOTEDSTR(fechamenos15texto);
                  informes.Variables.Variables['v_fecha2']:=QUOTEDSTR(fecha2);
                  informes.ShowReport();
               end;
        end;

        12:begin
            qaux.close;
            qaux.SQL.Clear;
            qaux.SQL.Add('select * from trabajadores where ' + LFiltroSinT + ' order by nombre');
            qaux.Open;
            if qaux.RecordCount=0 then showmessage(' DEBE SELECCIONAR AL MENOS UN EMPLEADO ')
            else
               begin
                  informedb.Datasource:=dsqaux;
                  informes.Report.Clear;
                  informes.LoadFromFile('c:\agrigest\informes\bajarechazo.fr3');
                  informes.Variables.Variables['v_fecha']:=QUOTEDSTR(fecha);
                  informes.ShowReport();
               end;
        end;
        13:begin
            qaux.close;
            qaux.SQL.Clear;
            qaux.SQL.Add('select * from trabajadores where ' + LFiltroSinT + ' order by nombre');
            qaux.Open;
            if qaux.RecordCount=0 then showmessage(' DEBE SELECCIONAR AL MENOS UN EMPLEADO ')
            else
               begin
                  informedb.Datasource:=dsqaux;
                  informes.Report.Clear;
                  informes.LoadFromFile('c:\agrigest\informes\bajadisciplinaria.fr3');
                  informes.Variables.Variables['v_fecha']:=QUOTEDSTR(fechamenos3texto);
                  informes.Variables.Variables['v_fecha2']:=QUOTEDSTR(fechamenos3);
                  informes.ShowReport();
               end;
        end;
        14:begin
            qaux.close;
            qaux.SQL.Clear;
            qaux.SQL.Add('select * from trabajadores where ' + LFiltroSinT + ' order by nombre');
            qaux.Open;
            if qaux.RecordCount=0 then showmessage(' DEBE SELECCIONAR AL MENOS UN EMPLEADO ')
            else
               begin
                  informedb.Datasource:=dsqaux;
                  informes.Report.Clear;
                  informes.LoadFromFile('c:\agrigest\informes\renunciarecmedico.fr3');
                  informes.Variables.Variables['v_fecha']:=QUOTEDSTR(fecha);
                  informes.Variables.Variables['v_fecha2']:=QUOTEDSTR(fecha);
                  informes.ShowReport();
                  checktodos2.Checked:=false;
               end;
        end;

        15:begin
            qempleadosnacion.Open;
            savedialog1.FileName:='LISTADO EMPLEADOS CON NACIONALIDADES.xlsx';
            savedialog1.Execute();
            archivo:=savedialog1.FileName;
            try
            Exportaraexcel(archivo,'EMPLEADOS NACION',gridempleadosnacion);
            finally
              showmessage('Los datos han sido exportados correctamente a '+archivo);
            end;
            qempleadosnacion.Close;
        end;
        16:begin
            qaux.close;
            qaux.SQL.Clear;
            qaux.SQL.Add('select * from trabajadores where ' + LFiltroSinT + ' order by nombre');
            qaux.Open;
            if qaux.RecordCount=0 then showmessage(' DEBE SELECCIONAR AL MENOS UN EMPLEADO ')
            else
               begin
                  informedb.Datasource:=dsqaux;
                  informes.Report.Clear;
                  informes.LoadFromFile('c:\agrigest\informes\plantillaasistencia.fr3');
                  informes.ShowReport();
               end;
        end;
        17:begin
            if dbgrid1.SelectedRows.Count > 0 then
              LFiltroLlamamiento := LFiltroSinT
            else
              LFiltroLlamamiento := ' convocatoria=' + QuotedStr(llamamiento);

            qaux.close;
            qaux.SQL.Clear;
            qaux.SQL.Add('select * from trabajadores where ' + LFiltroLlamamiento + ' order by nombre');
            qaux.Open;
            if qaux.RecordCount=0 then showmessage(' DEBE SELECCIONAR AL MENOS UN EMPLEADO ')
            else
               begin
                  informedb.Datasource:=dsqaux;
                  informes.Report.Clear;
                  informes.LoadFromFile('c:\agrigest\informes\infllamamiento.fr3');
                  informes.Variables.Variables['v_fecha']:=QUOTEDSTR(fecha);
                  informes.Variables.Variables['v_fecha2']:=QUOTEDSTR(sfecha2);
                  informes.Variables.Variables['v_hora']:=QUOTEDSTR(shora);
                  informes.ShowReport();
                  checktodos2.Checked:=false;
               end;
        end;
        18:begin
            qaux.close;
            qaux.SQL.Clear;
            qaux.SQL.Add('select * from trabajadores where ' + LFiltroSinT + ' order by nombre');
            qaux.Open;
            if qaux.RecordCount=0 then showmessage(' DEBE SELECCIONAR AL MENOS UN EMPLEADO ')
            else
               begin
                  informedb.Datasource:=dsqaux;
                  informes.Report.Clear;
                  informes.LoadFromFile('c:\agrigest\informes\plantillapeonadas.fr3');
                  informes.Variables.Variables['v_cuadrilla']:=QUOTEDSTR(qgrupos2descripcion.asstring);
                  informes.Variables.Variables['v_trabajadores']:=QUOTEDSTR(inttostr(qaux.RecordCount));
                  informes.ShowReport();
               end;
        end;
        19:begin
            qtripartita.close;
            qtripartita.SQL.Clear;
            qtripartita.SQL.Add('select id,apellidos,nombre,nif,concat('+''''+'/'+''''+',numsegsocial) as numsegsocial,sexo,fechanacimiento,email,telefono1,0.0 as categoria_prof,0.0 as grupo_cotizacion,0.0 as nivel_estudios,'+''''+qempresaformulariosnombre.AsString+''''+' as empresa,'+''''+qempresaformularioscif.AsString+''''+' as cif_empresa,');
            qtripartita.sql.Add('0.0 as coste_cotiz,0.0 as coste_bruto_hora from trabajadores where ' + LFiltroSinT + ' and grupo='+qgrupos2id.asstring+' order by apellidos,nombre');
            qtripartita.Open;
            savedialog1.FileName:='TRABAJADORES FORMACION TRIPARTITA.xlsx';
            savedialog1.Execute();
            archivo:=savedialog1.FileName;
            try
            Exportaraexcel(archivo,'TRABAJADORES TRIPARTITA',GRIDTRIPARTITA);
            finally
              showmessage('Los datos han sido exportados correctamente a '+archivo);
              qtripartita.Close;
            end;
        end;
        20:begin
            dlgfechas := Tdlgfechas.Create(nil);
            try
              if dlgfechas.ShowModal = mrOk then
              begin
                qaux.Close;
                qaux.SQL.Clear;
                qaux.SQL.Add('SELECT DISTINCT ');
                qaux.SQL.Add('  t.NIF, ');
                qaux.SQL.Add('  COALESCE(t.nombre, '#39#39') as nombre_completo,');
                qaux.SQL.Add('  CONCAT_WS('#39', '#39', NULLIF(t.DIRECCION, '#39#39'), NULLIF(t.CP, '#39#39'), NULLIF(t.POBLACION, '#39#39'), NULLIF(t.PROVINCIA, '#39#39')) AS direccion_completa, ');
                qaux.SQL.Add('  COALESCE(t.TELEFONO1, t.TELEFONO2, t.TELEFONO3, t.TELEFONO4, '#39#39') AS telefono, ');
                qaux.SQL.Add('  COALESCE(t.email, '#39#39') AS email, ');
                qaux.SQL.Add('  COALESCE(t.convocatoria, '#39#39') AS convocatoria, ');
                qaux.SQL.Add('  h.fecha_incorporacion, ');
                qaux.SQL.Add('  h.fecha_desconexion, ');
                qaux.SQL.Add('  h.motivo_baja ');
                qaux.SQL.Add('FROM trabajadores t ');
                qaux.SQL.Add('JOIN emp_historico h ON h.ide = t.ide AND h.idt = t.ID ');
                qaux.SQL.Add('WHERE t.ide = :EMPRESA ');
                qaux.SQL.Add('  AND h.fecha_incorporacion <= :FECHAHASTA ');
                qaux.SQL.Add('  AND (h.fecha_desconexion IS NULL OR h.fecha_desconexion >= :FECHADESDE) ');
                qaux.SQL.Add('ORDER BY t.nombre');
                qaux.ParamByName('EMPRESA').AsInteger := 1;// pide;
                qaux.ParamByName('FECHADESDE').AsDate := dlgfechas.fdesde.Date;
                qaux.ParamByName('FECHAHASTA').AsDate := dlgfechas.fhasta.Date;
                qaux.Open;

                if qaux.IsEmpty then
                  ShowMessage('No se encontraron trabajadores activos en el período seleccionado.')
                else
                begin
                  informedb.Datasource := dsqaux;
                  informes.Report.Clear;
                  informes.LoadFromFile('c:\agrigest\informes\listado_trabajadores_periodo.fr3');
                  informes.Variables.Variables['v_fechadesde'] := QUOTEDSTR(DateToStr(dlgfechas.fdesde.Date));
                  informes.Variables.Variables['v_fechahasta'] := QUOTEDSTR(DateToStr(dlgfechas.fhasta.Date));
                  informes.ShowReport();
                end;
              end;
            finally
              dlgfechas.Free;
            end;
        end;

    end;
    qaux.SQL.Clear;
    qaux.SQL.Add('update trabajadores set seleccionado=0');
    qaux.ExecSQL;
    qempleados.Close;
    qempleados.Open;
    checktodos2.Checked:=false;
    seleccionando:=0;
end;

procedure Tfempleados.Button10Click(Sender: TObject);
var nomarchivo:string;
begin
    qtemp_doc.Close;
    qtemp_doc.Prepare;
    qtemp_doc.ParamByName('EMPRESA').AsInteger:=documentoside.asinteger;
    qtemp_doc.ParamByName('ID').AsInteger:=documentosid.asinteger;
    qtemp_doc.Open;
    nomarchivo:=qtemp_docnomarchivo.AsString;
    deletefile('c:\agrigest\tmp\*.*');
    qtemp_docarchivo.SaveToFile('c:\agrigest\tmp\'+nomarchivo);
    ShellExecute(Handle,nil,PChar('c:\agrigest\tmp\'+nomarchivo),'','',SW_SHOWNORMAL);
   // borrarficheros('c:\agrigest\tmp\');
end;

procedure Tfempleados.Button11Click(Sender: TObject);
var  archivo:string;
begin
    qtemp_doc.Close;
    qtemp_doc.Prepare;
    qtemp_doc.ParamByName('EMPRESA').AsInteger:=documentoside.asinteger;
    qtemp_doc.ParamByName('ID').AsInteger:=documentosid.asinteger;
    qtemp_doc.Open;
    archivo:=qtemp_docnomarchivo.AsString;
    savedialog1.FileName:=archivo;
    savedialog1.Execute();
    archivo:=savedialog1.FileName;
    qtemp_docarchivo.SaveToFile(archivo);
  //  borrarficheros('c:\agrigest\tmp\');

end;

procedure Tfempleados.Button12Click(Sender: TObject);
begin
    informedb.Datasource:=dsqlistadoplanificacion;
    informes.Report.Clear;
    informes.LoadFromFile('c:\agrigest\informes\planificacionformacion.fr3');
    informes.ShowReport();
end;

procedure Tfempleados.Button14Click(Sender: TObject);
begin
    informedb.Datasource:=dsqjornales;
    informes.Report.Clear;
    informes.LoadFromFile('c:\agrigest\informes\JORNALES.fr3');
    informes.Report.FileName:=TMES.Text+' ' + qjornalestrabajador.asstring;
    informes.ShowReport();
    informes.Clear
end;

procedure Tfempleados.Button15Click(Sender: TObject);
var ext,nomarchivo:string;
    ruta:widestring;
    origen,destino:pwidechar;
    x:integer;
begin
  if opendialog2.Execute then
  begin
    try
    finally
       if opendialog2.Files.Count=1 then
       begin
          qaux.SQL.Clear;
          qaux.SQL.Add('delete from documentos_tmp ');
          qaux.ExecSQL;
          ext:= ExtractFileExt(opendialog2.FileName);
          nomarchivo:= extractfilename(opendialog2.FileName);
          ruta:=extractfilepath(opendialog2.FileName)+nomarchivo;
          origen:=pwidechar(ruta);
          ruta:='c:\agrigest\tmp\'+nomarchivo;
          destino:=pwidechar(ruta);
          CopyFileEx(origen,destino, nil, nil, nil, 0);
          documentos_tmp.Open;
          documentos_tmp.Append;
          documentos_tmpidt.Value:=qempleadosid.Asinteger;
          documentos_tmpfecha.Value:=date();
          documentos_tmpide.Value:=qempleadoside.AsInteger;
          documentos_tmpnomarchivo.Value:=nomarchivo;
          documentos_tmpdescripcion.Value:=nomarchivo;
          documentos_tmpextension.Value:=ext;
          documentos_tmparchivo.LoadFromFile('c:\agrigest\tmp\'+nomarchivo);
          documentos_tmp.Post;
          qaux.SQL.Clear;
          qaux.SQL.Add('insert into documentos (ide,fecha,descripcion,archivo,nomarchivo,extension,idlote,codpar,idea,idt) (select ide,fecha,descripcion,archivo,nomarchivo,extension,idlote,codpar,idea,idt from documentos_tmp)');
          qaux.ExecSQL;
          qaux.SQL.Clear;
          qaux.SQL.Add('delete from documentos_tmp ');
          qaux.ExecSQL;
          documentos.Close;
          documentos.Prepare;
          documentos.ParamByName('EMPLEADO').AsInteger:=qlistaempleadosid.AsInteger;
          documentos.ParamByName('EMPRESA').AsInteger:=qlistaempleadoside.AsInteger;
          documentos.open;
          panel37.Visible:=true;
       end else
       begin
          memo1.Clear;
          memo1.Lines.AddStrings(opendialog2.files);
          for x := 0 to opendialog2.Files.Count-1 do
            begin
                qaux.SQL.Clear;
                qaux.SQL.Add('delete from documentos_tmp ');
                qaux.ExecSQL;
                documentos_tmp.Open;
                documentos_tmp.Append;
                ext:= ExtractFileExt(memo1.Lines[x]);
                nomarchivo:= extractfilename(memo1.Lines[x]);
                ruta:=extractfilepath(opendialog2.FileName)+nomarchivo;
                origen:=pwidechar(ruta);
                ruta:='c:\agrigest\tmp\'+nomarchivo;
                destino:=pwidechar(ruta);
                CopyFileEx(origen,destino, nil, nil, nil, 0);
                documentos_tmpidt.Value:=qempleadosid.Asinteger;
                documentos_tmpfecha.Value:=date();
                documentos_tmpide.Value:=qempleadoside.AsInteger;
                documentos_tmpnomarchivo.Value:=nomarchivo;
                documentos_tmpdescripcion.Value:=nomarchivo;
                documentos_tmpextension.Value:=ext;
                documentos_tmparchivo.LoadFromFile('c:\agrigest\tmp\'+nomarchivo);
                documentos_tmp.Post;
                qaux.SQL.Clear;
                qaux.SQL.Add('insert into documentos (ide,fecha,descripcion,archivo,nomarchivo,extension,idlote,codpar,idea,idt) (select ide,fecha,descripcion,archivo,nomarchivo,extension,idlote,codpar,idea,idt from documentos_tmp)');
                qaux.ExecSQL;
                qaux.SQL.Clear;
                qaux.SQL.Add('delete from documentos_tmp ');
                qaux.ExecSQL;
                documentos.Close;
                documentos.Prepare;
                documentos.ParamByName('EMPLEADO').AsInteger:=qlistaempleadosid.AsInteger;
                documentos.ParamByName('EMPRESA').AsInteger:=qlistaempleadoside.AsInteger;
                documentos.open;
                panel37.Visible:=true;
            end;
       end;
    end;
  end;
//  principal.borrarficheros ('c:\agrigest\tmp\');
end;

procedure Tfempleados.Button18Click(Sender: TObject);
var
  usbDevices : IUsbDevices;
  usbDevice  : IUsbDevice;
    actual : TBookMarkStr;
    archivo,fecha,fecha2,fechamenos3,fechamenos3texto,fechamenos15,fechamenos15texto,textmes:string;
    dia,mes,anyo:word;
    sfecha:tdate;
    i:integer;
    ext,nomarchivo,LIds,LFiltroSeleccionados:string;
begin

    usbDevices := CoUsbDevices.Create();
    if (usbDevices.Count > 0) then
    begin
      try
        begin
          usbDevice := usbDevices.Item[0]; //select the first device
          vfirmas := Tvfirmas.Create(nil);
          try
            VFirmas.connect(usbDevice);
            VFirmas.ShowModal();
          finally
            vfirmas.Free;
            firmasdoc.Open;
            if firmasdoc.RecordCount=0 then
            begin
              firmasdoc.Append;
              firmasdocide.Value:=qempleadoside.asinteger;
              firmasdocidt.Value:=qempleadosid.asinteger;
              firmasdocfirma.LoadFromFile('c:\agrigest\tmp\firma.bmp');
              firmasdoc.Post;

            end else
            begin
              firmasdoc.edit;
              firmasdocide.Value:=qempleadoside.asinteger;
              firmasdocidt.Value:=qempleadosid.asinteger;
              firmasdocfirma.LoadFromFile('c:\agrigest\tmp\firma.bmp');
              firmasdoc.Post;
            end;
            if qemp_firmas.RecordCount=0 then
            begin
              qemp_firmas.Append;
              qemp_firmaside.Value:=qempleadoside.asinteger;
              qemp_firmasidt.Value:=qempleadosid.asinteger;
              qemp_firmasfirma.LoadFromFile('c:\agrigest\tmp\firma.bmp');
              qemp_firmas.Post;
            end else
            begin
              qemp_firmas.edit;
              qemp_firmaside.Value:=qempleadoside.asinteger;
              qemp_firmasidt.Value:=qempleadosid.asinteger;
              qemp_firmasfirma.LoadFromFile('c:\agrigest\tmp\firma.bmp');
              qemp_firmas.Post;
            end;
            tfirmas.Picture:=nil;
            tfirmas.Picture.LoadFromFile('c:\agrigest\tmp\firma.bmp');
            tfirmadocs.Picture.LoadFromFile('c:\agrigest\tmp\firma.bmp');
           end;

        end;
      except
        on e : Exception do ShowMessage(e.Message);
      end;
    end else
        begin
          ShowMessage('Dispositivo de firmas no conectado');
          if qemp_firmasfirma.asstring<>'' then
          begin
              qemp_firmasfirma.SaveToFile('c:\agrigest\tmp\firma.bmp');
              firmasdoc.Open;
              if firmasdoc.RecordCount=0 then
              begin
                firmasdoc.Append;
                firmasdocide.Value:=qempleadoside.asinteger;
                firmasdocidt.Value:=qempleadosid.asinteger;
                firmasdocfirma.LoadFromFile('c:\agrigest\tmp\firma.bmp');
                firmasdoc.Post;
              end else
              begin
                firmasdoc.edit;
                firmasdocide.Value:=qempleadoside.asinteger;
                firmasdocidt.Value:=qempleadosid.asinteger;
                firmasdocfirma.LoadFromFile('c:\agrigest\tmp\firma.bmp');
                firmasdoc.Post;
              end;
              tfirmadocs.Picture.LoadFromFile('c:\agrigest\tmp\firma.bmp');
            end;
           end;

        seleccionando:=1;
        if listadocsfirma.itemindex=-1 then listadocsfirma.itemindex:=0;

        if (listadocsfirma.ItemIndex>=0) and (listadocsfirma.ItemIndex<=10) then
        begin
            dlgfecha := Tdlgfecha.Create(nil);
          try
            dlgfecha.showmodal();
          finally
            sfecha:=strtodate(dlgfecha.lfecha.text);
            dlgfecha.Free;
          end;
        end else sfecha:=date();
        decodedate(sfecha,anyo,mes,dia);
        case mes of
            1: textmes:='enero';
            2: textmes:='febrero';
            3: textmes:='marzo';
            4: textmes:='abril';
            5: textmes:='mayo';
            6: textmes:='junio';
            7: textmes:='julio';
            8: textmes:='agosto';
            9: textmes:='septiembre';
            10: textmes:='octubre';
            11: textmes:='noviembre';
            12: textmes:='diciembre';
        end;
        fecha:=floattostr(dia)+' de '+textmes+' de '+floattostr(anyo);
        fechamenos3texto:=floattostr(dia-3)+' de '+textmes+' de '+floattostr(anyo);
        fechamenos15texto:=floattostr(dia-15)+' de '+textmes+' de '+floattostr(anyo);
        fecha2:=floattostr(dia)+'/'+floattostr(mes)+'/'+floattostr(anyo);
        fechamenos3:=floattostr(dia-3)+'/'+floattostr(mes)+'/'+floattostr(anyo);
        fechamenos15:=floattostr(dia-15)+'/'+floattostr(mes)+'/'+floattostr(anyo);

        if dbgrid1.SelectedRows.Count > 0 then
        begin
          LIds := '';
          for i := 0 to dbgrid1.SelectedRows.Count - 1 do
          begin
            qlistaempleados.GotoBookmark(dbgrid1.SelectedRows[i]);
            if LIds <> '' then
              LIds := LIds + ',' + qlistaempleadosid.AsString
            else
              LIds := qlistaempleadosid.AsString;
          end;
          LFiltroSeleccionados := ' id in (' + LIds + ') ';
        end
        else
        begin
          LFiltroSeleccionados := ' id = ' + qempleadosid.AsString + ' ';
        end;

        case listadocsfirma.ItemIndex of
            0:begin
                qaux.close;
                qaux.SQL.Clear;
                qaux.SQL.Add('select * from trabajadores where ' + LFiltroSeleccionados + ' order by nombre');
                qaux.Open;
                if qaux.RecordCount=0 then showmessage('DEBE SELECCIONAR AL MENOS UN EMPLEADO')
                else
                   begin
                      informedb.Datasource:=dsqaux;
                      informes.Report.Clear;
                      informes.LoadFromFile('c:\agrigest\informes\bajavoluntaria.fr3');
                      informes.Variables.Variables['v_fecha']:=QUOTEDSTR('Aspe a '+fecha);
                      informes.Variables.Variables['v_fecha2']:=QUOTEDSTR(fecha2);
                      informes.ShowReport();
///  grabo en documentos el documento firmado

                      topdf.FileName:='BAJA VOLUNTARIA-'+qempleadosnombre.AsString+'.pdf';
                      topdf.DefaultPath:='c:\agrigest\tmp\';
                      informes.Export(topdf);
                      qaux.SQL.Clear;
                      qaux.SQL.Add('delete from documentos_tmp ');
                      qaux.ExecSQL;
                      documentos_tmp.Open;
                      try
                      documentos_tmp.Append;
                      ext:= '.pdf';//ExtractFileExt(opendialog2.FileName);
                      nomarchivo:='BAJA VOLUNTARIA-'+qempleadosnombre.AsString+'.pdf';//extractfilename(opendialog2.FileName);
                      documentos_tmpidt.Value:=qempleadosid.Asinteger;
                      documentos_tmpfecha.Value:=date();
                      documentos_tmpide.Value:=qempleadoside.AsInteger;
                      documentos_tmpnomarchivo.Value:=nomarchivo;
                      documentos_tmpdescripcion.Value:=nomarchivo;
                      documentos_tmpextension.Value:=ext;
                      documentos_tmparchivo.LoadFromFile(topdf.DefaultPath+nomarchivo);
                      documentos_tmp.Post;
                      finally
                        deletefile(topdf.FileName);
                      end;
                      qaux.SQL.Clear;
                      qaux.SQL.Add('insert into documentos (ide,fecha,descripcion,archivo,nomarchivo,extension,idlote,codpar,idea,idt) (select ide,fecha,descripcion,archivo,nomarchivo,extension,idlote,codpar,idea,idt from documentos_tmp)');
                      qaux.ExecSQL;
                      qaux.SQL.Clear;
                      qaux.SQL.Add('delete from documentos_tmp ');
                      qaux.ExecSQL;
                      documentos.refresh;

                      qaux.SQL.Clear;
                      qaux.SQL.Add('update trabajadores set seleccionado=0');
                      qaux.ExecSQL;
                      qempleados.Close;
                      qempleados.Open;
                      checktodos2.Checked:=false;
                   end;
            end;
            1:begin
                qaux.close;
                qaux.SQL.Clear;
                qaux.SQL.Add('select * from trabajadores where ' + LFiltroSeleccionados + ' order by nombre');
                qaux.Open;
                if qaux.RecordCount=0 then showmessage('DEBE SELECCIONAR AL MENOS UN EMPLEADO')
                else
                   begin
                      informedb.Datasource:=dsqaux;
                      informes.Report.Clear;
                      informes.LoadFromFile('c:\agrigest\informes\bajafincontrato.fr3');
                      informes.Variables.Variables['v_fecha']:=QUOTEDSTR('Aspe a '+fechamenos15texto);
                      informes.Variables.Variables['v_fecha2']:=QUOTEDSTR(fecha2);
                      informes.ShowReport();
///  grabo en documentos el documento firmado

                      topdf.FileName:='BAJA FINCONTRATO-'+qempleadosnombre.AsString+'.pdf';
                      topdf.DefaultPath:='c:\agrigest\tmp\';
                      informes.Export(topdf);
                      qaux.SQL.Clear;
                      qaux.SQL.Add('delete from documentos_tmp ');
                      qaux.ExecSQL;
                      documentos_tmp.Open;
                      try
                      documentos_tmp.Append;
                      ext:= '.pdf';//ExtractFileExt(opendialog2.FileName);
                      nomarchivo:='BAJA FINCONTRATO-'+qempleadosnombre.AsString+'.pdf';//extractfilename(opendialog2.FileName);
                      documentos_tmpidt.Value:=qempleadosid.Asinteger;
                      documentos_tmpfecha.Value:=date();
                      documentos_tmpide.Value:=qempleadoside.AsInteger;
                      documentos_tmpnomarchivo.Value:=nomarchivo;
                      documentos_tmpdescripcion.Value:=nomarchivo;
                      documentos_tmpextension.Value:=ext;
                      documentos_tmparchivo.LoadFromFile(topdf.DefaultPath+nomarchivo);
                      documentos_tmp.Post;
                      finally
                        deletefile(topdf.FileName);
                      end;
                      qaux.SQL.Clear;
                      qaux.SQL.Add('insert into documentos (ide,fecha,descripcion,archivo,nomarchivo,extension,idlote,codpar,idea,idt) (select ide,fecha,descripcion,archivo,nomarchivo,extension,idlote,codpar,idea,idt from documentos_tmp)');
                      qaux.ExecSQL;
                      qaux.SQL.Clear;
                      qaux.SQL.Add('delete from documentos_tmp ');
                      qaux.ExecSQL;
                      documentos.refresh;


                      qaux.SQL.Clear;
                      qaux.SQL.Add('update trabajadores set seleccionado=0');
                      qaux.ExecSQL;
                      qempleados.Close;
                      qempleados.Open;
                      checktodos2.Checked:=false;
                   end;
            end;

            2:begin
                qaux.close;
                qaux.SQL.Clear;
                qaux.SQL.Add('select * from trabajadores where ' + LFiltroSeleccionados + ' order by nombre');
                qaux.Open;
                if qaux.RecordCount=0 then showmessage('DEBE SELECCIONAR AL MENOS UN EMPLEADO')
                else
                   begin
                      informedb.Datasource:=dsqaux;
                      informes.Report.Clear;
                      informes.LoadFromFile('c:\agrigest\informes\bajarechazo.fr3');
                      informes.Variables.Variables['v_fecha']:=QUOTEDSTR('Aspe a '+fecha);
                      informes.ShowReport();
///  grabo en documentos el documento firmado

                      topdf.FileName:='BAJA RECHAZO-'+qempleadosnombre.AsString+'.pdf';
                      topdf.DefaultPath:='c:\agrigest\tmp\';
                      informes.Export(topdf);
                      qaux.SQL.Clear;
                      qaux.SQL.Add('delete from documentos_tmp ');
                      qaux.ExecSQL;
                      documentos_tmp.Open;
                      try
                      documentos_tmp.Append;
                      ext:= '.pdf';//ExtractFileExt(opendialog2.FileName);
                      nomarchivo:='BAJA RECHAZO-'+qempleadosnombre.AsString+'.pdf';//extractfilename(opendialog2.FileName);
                      documentos_tmpidt.Value:=qempleadosid.Asinteger;
                      documentos_tmpfecha.Value:=date();
                      documentos_tmpide.Value:=qempleadoside.AsInteger;
                      documentos_tmpnomarchivo.Value:=nomarchivo;
                      documentos_tmpdescripcion.Value:=nomarchivo;
                      documentos_tmpextension.Value:=ext;
                      documentos_tmparchivo.LoadFromFile(topdf.DefaultPath+nomarchivo);
                      documentos_tmp.Post;
                      finally
                        deletefile(topdf.FileName);
                      end;
                      qaux.SQL.Clear;
                      qaux.SQL.Add('insert into documentos (ide,fecha,descripcion,archivo,nomarchivo,extension,idlote,codpar,idea,idt) (select ide,fecha,descripcion,archivo,nomarchivo,extension,idlote,codpar,idea,idt from documentos_tmp)');
                      qaux.ExecSQL;
                      qaux.SQL.Clear;
                      qaux.SQL.Add('delete from documentos_tmp ');
                      qaux.ExecSQL;
                      documentos.refresh;

                      qaux.SQL.Clear;
                      qaux.SQL.Add('update trabajadores set seleccionado=0');
                      qaux.ExecSQL;
                      qempleados.Close;
                      qempleados.Open;
                      checktodos2.Checked:=false;
                   end;
            end;
            3:begin
                qaux.close;
                qaux.SQL.Clear;
                qaux.SQL.Add('select * from trabajadores where ' + LFiltroSeleccionados + ' order by nombre');
                qaux.Open;
                if qaux.RecordCount=0 then showmessage('DEBE SELECCIONAR AL MENOS UN EMPLEADO')
                else
                   begin
                      informedb.Datasource:=dsqaux;
                      informes.Report.Clear;
                      informes.LoadFromFile('c:\agrigest\informes\bajadisciplinaria.fr3');
                      informes.Variables.Variables['v_fecha']:=QUOTEDSTR(fechamenos3texto);
                      informes.Variables.Variables['v_fecha2']:=QUOTEDSTR(fechamenos3);
                      informes.ShowReport();
///  grabo en documentos el documento firmado

                      topdf.FileName:='BAJA DISCIPLINARIA-'+qempleadosnombre.AsString+'.pdf';
                      topdf.DefaultPath:='c:\agrigest\tmp\';
                      informes.Export(topdf);
                      qaux.SQL.Clear;
                      qaux.SQL.Add('delete from documentos_tmp ');
                      qaux.ExecSQL;
                      documentos_tmp.Open;
                      try
                      documentos_tmp.Append;
                      ext:= '.pdf';//ExtractFileExt(opendialog2.FileName);
                      nomarchivo:='BAJA DISCIPLINARIA-'+qempleadosnombre.AsString+'.pdf';//extractfilename(opendialog2.FileName);
                      documentos_tmpidt.Value:=qempleadosid.Asinteger;
                      documentos_tmpfecha.Value:=date();
                      documentos_tmpide.Value:=qempleadoside.AsInteger;
                      documentos_tmpnomarchivo.Value:=nomarchivo;
                      documentos_tmpdescripcion.Value:=nomarchivo;
                      documentos_tmpextension.Value:=ext;
                      documentos_tmparchivo.LoadFromFile(topdf.DefaultPath+nomarchivo);
                      documentos_tmp.Post;
                      finally
                        deletefile(topdf.FileName);
                      end;
                      qaux.SQL.Clear;
                      qaux.SQL.Add('insert into documentos (ide,fecha,descripcion,archivo,nomarchivo,extension,idlote,codpar,idea,idt) (select ide,fecha,descripcion,archivo,nomarchivo,extension,idlote,codpar,idea,idt from documentos_tmp)');
                      qaux.ExecSQL;
                      qaux.SQL.Clear;
                      qaux.SQL.Add('delete from documentos_tmp ');
                      qaux.ExecSQL;
                      documentos.refresh;

                      qaux.SQL.Clear;
                      qaux.SQL.Add('update trabajadores set seleccionado=0');
                      qaux.ExecSQL;
                      qempleados.Close;
                      qempleados.Open;
                      checktodos2.Checked:=false;
                   end;
            end;
            4:begin
                qaux.close;
                qaux.SQL.Clear;
                qaux.SQL.Add('select * from trabajadores where ' + LFiltroSeleccionados + ' order by nombre');
                qaux.Open;
                if qaux.RecordCount=0 then showmessage('DEBE SELECCIONAR AL MENOS UN EMPLEADO')
                else
                   begin
                      informedb.Datasource:=dsqaux;
                      informes.Report.Clear;
                      informes.LoadFromFile('c:\agrigest\informes\renunciarecmedico.fr3');
                      informes.Variables.Variables['v_fecha']:=QUOTEDSTR(fecha);
                      informes.Variables.Variables['v_fecha2']:=QUOTEDSTR(fecha);
                      informes.ShowReport();
///  grabo en documentos el documento firmado

                      topdf.FileName:='RECONOCIMIENTO MEDICO-'+qempleadosnombre.AsString+'.pdf';
                      topdf.DefaultPath:='c:\agrigest\tmp\';
                      informes.Export(topdf);
                      qaux.SQL.Clear;
                      qaux.SQL.Add('delete from documentos_tmp ');
                      qaux.ExecSQL;
                      documentos_tmp.Open;
                      try
                      documentos_tmp.Append;
                      ext:= '.pdf';//ExtractFileExt(opendialog2.FileName);
                      nomarchivo:='RECONOCIMIENTO MEDICO-'+qempleadosnombre.AsString+'.pdf';//extractfilename(opendialog2.FileName);
                      documentos_tmpidt.Value:=qempleadosid.Asinteger;
                      documentos_tmpfecha.Value:=date();
                      documentos_tmpide.Value:=qempleadoside.AsInteger;
                      documentos_tmpnomarchivo.Value:=nomarchivo;
                      documentos_tmpdescripcion.Value:=nomarchivo;
                      documentos_tmpextension.Value:=ext;
                      documentos_tmparchivo.LoadFromFile(topdf.DefaultPath+nomarchivo);
                      documentos_tmp.Post;
                      finally
                        deletefile(topdf.FileName);
                      end;
                      qaux.SQL.Clear;
                      qaux.SQL.Add('insert into documentos (ide,fecha,descripcion,archivo,nomarchivo,extension,idlote,codpar,idea,idt) (select ide,fecha,descripcion,archivo,nomarchivo,extension,idlote,codpar,idea,idt from documentos_tmp)');
                      qaux.ExecSQL;
                      qaux.SQL.Clear;
                      qaux.SQL.Add('delete from documentos_tmp ');
                      qaux.ExecSQL;
                      documentos.refresh;

                      qaux.SQL.Clear;
                      qaux.SQL.Add('update trabajadores set seleccionado=0');
                      qaux.ExecSQL;
                      qempleados.Close;
                      qempleados.Open;
                      checktodos2.Checked:=false;
                   end;
            end;
            5:begin
                qaux.close;
                qaux.SQL.Clear;
                qaux.SQL.Add('select * from trabajadores where ' + LFiltroSeleccionados + ' order by nombre');
                qaux.Open;
                if qaux.RecordCount=0 then showmessage('DEBE SELECCIONAR AL MENOS UN EMPLEADO')
                else
                   begin
                      informedb.Datasource:=dsqaux;
                      informes.Report.Clear;
                      informes.LoadFromFile('c:\agrigest\informes\acuerdoconfidencialidad.fr3');
                      informes.Variables.Variables['v_fecha']:=QUOTEDSTR(fecha);
                      informes.Variables.Variables['v_fecha2']:=QUOTEDSTR(fecha);
                      informes.ShowReport();
///  grabo en documentos el documento firmado

                      topdf.FileName:='ACUERDOCONFIDENCIALIDAD-'+qempleadosnombre.AsString+'.pdf';
                      topdf.DefaultPath:='c:\agrigest\tmp\';
                      informes.Export(topdf);
                      qaux.SQL.Clear;
                      qaux.SQL.Add('delete from documentos_tmp ');
                      qaux.ExecSQL;
                      documentos_tmp.Open;
                      try
                      documentos_tmp.Append;
                      ext:= '.pdf';//ExtractFileExt(opendialog2.FileName);
                      nomarchivo:='ACUERDOCONFIDENCIALIDAD-'+qempleadosnombre.AsString+'.pdf';//extractfilename(opendialog2.FileName);
                      documentos_tmpidt.Value:=qempleadosid.Asinteger;
                      documentos_tmpfecha.Value:=date();
                      documentos_tmpide.Value:=qempleadoside.AsInteger;
                      documentos_tmpnomarchivo.Value:=nomarchivo;
                      documentos_tmpdescripcion.Value:=nomarchivo;
                      documentos_tmpextension.Value:=ext;
                      documentos_tmparchivo.LoadFromFile(topdf.DefaultPath+nomarchivo);
                      documentos_tmp.Post;
                      finally
                        deletefile(topdf.FileName);
                      end;
                      qaux.SQL.Clear;
                      qaux.SQL.Add('insert into documentos (ide,fecha,descripcion,archivo,nomarchivo,extension,idlote,codpar,idea,idt) (select ide,fecha,descripcion,archivo,nomarchivo,extension,idlote,codpar,idea,idt from documentos_tmp)');
                      qaux.ExecSQL;
                      qaux.SQL.Clear;
                      qaux.SQL.Add('delete from documentos_tmp ');
                      qaux.ExecSQL;
                      documentos.refresh;

                      qaux.SQL.Clear;
                      qaux.SQL.Add('update trabajadores set seleccionado=0');
                      qaux.ExecSQL;
                      qempleados.Close;
                      qempleados.Open;
                      checktodos2.Checked:=false;
                   end;
            end;

        end;
    seleccionando:=0;
    tfirmadocs.Picture:=nil;
    firmasdoc.Open;
    if firmasdoc.RecordCount>0 then
    firmasdoc.Delete;
    Deletefile('c:\agrigest\tmp\firma.bmp');




end;

procedure Tfempleados.Button1Click(Sender: TObject);
var
  usbDevices : IUsbDevices;
  usbDevice  : IUsbDevice;
begin
    usbDevices := CoUsbDevices.Create();
    if (usbDevices.Count > 0) then
    begin
      try
        begin
          usbDevice := usbDevices.Item[0]; //select the first device
          vfirmas := Tvfirmas.Create(nil);
          try
            VFirmas.connect(usbDevice);
            VFirmas.ShowModal();
          finally
            vfirmas.Free;
          end;

        end;
      except
        on e : Exception do
          ShowMessage(e.Message);
      end;
      qemp_firmas.Open;
      if qemp_firmas.RecordCount=0 then
      begin
        qemp_firmas.Append;
        qemp_firmaside.Value:=qempleadoside.asinteger;
        qemp_firmasidt.Value:=qempleadosid.asinteger;
        qemp_firmasfirma.LoadFromFile('c:\agrigest\tmp\firma.bmp');
        qemp_firmas.Post;
      end else
      begin
        qemp_firmas.edit;
        qemp_firmaside.Value:=qempleadoside.asinteger;
        qemp_firmasidt.Value:=qempleadosid.asinteger;
        qemp_firmasfirma.LoadFromFile('c:\agrigest\tmp\firma.bmp');
        qemp_firmas.Post;

      end;
      tfirmas.Picture.LoadFromFile('c:\agrigest\tmp\firma.bmp');
      Deletefile('c:\agrigest\tmp\firma.bmp');
    end
    else
    begin
      ShowMessage('Dispositivo de firmas no conectado');
    end;





end;

procedure Tfempleados.Button22Click(Sender: TObject);
begin
   qemp_firmas.Delete;
   tfirmas.Picture:=nil;
end;

procedure Tfempleados.Button23Click(Sender: TObject);
begin
    emp_historico := Temp_historico.Create(nil);
    try
      emp_historico.showmodal();
    finally
      emp_historico.Free;
      qemp_historico.close;
      qemp_historico.Open;
    end;
end;

procedure Tfempleados.Button24Click(Sender: TObject);
begin
  qentregasmaterial.Append;
  qentregasmaterialide.Value:=qempleadoside.AsInteger;
  qentregasmaterialidt.Value:=qempleadosid.AsInteger;
  qentregasmaterialfecha.Value:=fentregamaterial.Date;
  qentregasmaterialconcepto.value:=qepisdescripcion.AsString;
  qentregasmaterialcantidad.Value:=1;
  qentregasmaterial.Post;
end;

procedure Tfempleados.Button25Click(Sender: TObject);
begin
  qentregasmaterial.Delete;
end;

procedure Tfempleados.Button2Click(Sender: TObject);
begin
   if qemp_fotosidt.asinteger=qempleadosid.asinteger then qemp_fotos.delete;

   image2.Picture:=nil;
   Deletefile('c:\agrigest\tmp\empimg'+qemp_fotosextension.AsString);
end;

procedure Tfempleados.Button3Click(Sender: TObject);
begin
    documentos.Delete;
end;

procedure Tfempleados.Button6Click(Sender: TObject);
var  archivo:TMemorystream;
     ext,nomarchivo: string;
begin
    try
      ext:= ExtractFileExt(opendialog2.FileName);
      nomarchivo:= extractfilename(opendialog2.FileName);
      documentosidt.Value:=qempleadosid.Asinteger;
      documentoside.Value:=qempleadoside.AsInteger;
      documentosnomarchivo.Value:=nomarchivo;
      documentosfecha.Value:=date();
      documentosextension.Value:=ext;
      //documentosarchivo.LoadFromFile(opendialog2.FileName);
      documentos.Post;
    finally
    end;
end;

procedure Tfempleados.Button7Click(Sender: TObject);
begin
    documentos.Cancel;
end;

procedure Tfempleados.Button8Click(Sender: TObject);
var archivo:string;
begin
    savedialog1.FileName:='ENTREGAS DE MATERIAL.xls';
    savedialog1.Execute();
    archivo:=savedialog1.FileName;
    try
    Exportaraexcel(archivo,'ENTREGAS DE MATERIAL',dbgrid6);
    finally
      showmessage('Los datos han sido exportados correctamente a '+archivo);
    end;
end;
procedure Tfempleados.Button9Click(Sender: TObject);
var ext:string;
begin
  if opendialog2.Execute then
  begin
    try
      ext:= ExtractFileExt(opendialog2.FileName);
      if (ext='.jpg') or (ext='.jpeg') or (ext='.bmp') or (ext='.png') then
      begin
        imgfoto.Picture.LoadFromFile(opendialog2.FileName);
        imgfoto.Visible:=true;
      end
    finally
       documentos.edit;
       dbgrid75.SetFocus;
    end;
  end;

end;

procedure Tfempleados.Capturar1Click(Sender: TObject);
begin
    btEimagen.Caption:='Capturar imagen';
    panelfotoe.Visible:=true;
    imgfotoe.Visible:=true;
    btactivarcamara.Click;
end;

procedure Tfempleados.Cargar1Click(Sender: TObject);
begin
   bteimagen.Caption:='Cargar imagen';
   bteimagen.Click;

end;

procedure Tfempleados.btEMaceptarClick(Sender: TObject);
var i:integer;
    dia,mes,anyo:word;
    fecha,concepto,cantidad,LIds:string;
begin
  if qentregasmaterial.State in [dsedit] then
  begin
    decodedate(fentregamaterial.Date,anyo,mes,dia);
    concepto:=edit1.Text;
    cantidad:=stringreplace((edit2.text),',','.',[rfreplaceall]);
    qentregasmaterialfecha.Value:=fentregamaterial.Date;
    qentregasmaterialconcepto.Value:=concepto;
    qentregasmaterialcantidad.Value:=strtofloat(cantidad);
    qentregasmaterial.Post;
  end else
  begin
    if dbgrid1.Selectedrows.Count > 0 then
    begin
      decodedate(fentregamaterial.Date,anyo,mes,dia);
      fecha:=''''+inttostr(anyo)+'-'+inttostr(mes)+'-'+inttostr(dia)+'''';
      concepto:=''''+edit1.Text+'''';
      cantidad:=stringreplace((edit2.text),',','.',[rfreplaceall]);
      LIds := '';
      for i := 0 to dbgrid1.Selectedrows.Count - 1 do
      begin
        qlistaempleados.GotoBookmark(dbgrid1.selectedrows[i]);
        if LIds <> '' then
          LIds := LIds + ',' + qlistaempleadosid.AsString
        else
          LIds := qlistaempleadosid.AsString;
      end;
      qaux.close;
      qaux.SQL.Clear;
      qaux.SQL.Add('insert into emp_entregasmaterial (ide,idt,fecha,concepto,cantidad) (select ide,id,'+fecha+','+concepto+','+cantidad+' from trabajadores where id in (' + LIds + '))' );
      qaux.Execsql;
    end
    else if qempleados.Active and (qempleados.RecordCount > 0) then
    begin
      decodedate(fentregamaterial.Date,anyo,mes,dia);
      fecha:=''''+inttostr(anyo)+'-'+inttostr(mes)+'-'+inttostr(dia)+'''';
      concepto:=''''+edit1.Text+'''';
      cantidad:=stringreplace((edit2.text),',','.',[rfreplaceall]);
      qaux.close;
      qaux.SQL.Clear;
      qaux.SQL.Add('insert into emp_entregasmaterial (ide,idt,fecha,concepto,cantidad) (select ide,id,'+fecha+','+concepto+','+cantidad+' from trabajadores where id=' + qempleadosid.AsString + ')' );
      qaux.Execsql;
    end
    else
      showmessage('DEBE SELECCIONAR AL MENOS UN TRABAJADOR');
  end;
//    panel30.Visible:=false;
    btEMaceptar.Enabled:=false;
    btEMcancelar.Enabled:=false;
    btEMnuevo.Enabled:=true;
    btEMmodificar.Enabled:=true;
    btEMborrar.Enabled:=true;
    qentregasmaterial.Refresh;
    qlistadoentregasmaterial.Refresh;
end;

procedure Tfempleados.btEMborrarClick(Sender: TObject);
begin
    qentregasmaterial.Delete;
    qlistadoentregasmaterial.Refresh;
end;

procedure Tfempleados.btEMcancelarClick(Sender: TObject);
begin
    if qentregasmaterial.State in [dsedit] then qentregasmaterial.Cancel;
//    panel30.Visible:=false;
    btEMaceptar.Enabled:=false;
    btEMcancelar.Enabled:=false;
    btEMnuevo.Enabled:=true;
    btEMmodificar.Enabled:=true;
    btEMborrar.Enabled:=true;
    qlistadoentregasmaterial.Refresh;
end;

procedure Tfempleados.btEMimprimirClick(Sender: TObject);
var
  usbDevices : IUsbDevices;
  usbDevice  : IUsbDevice;
    actual : TBookMarkStr;
    archivo,fecha,fecha2,fechamenos3,fechamenos3texto,fechamenos15,fechamenos15texto,textmes:string;
    dia,mes,anyo:word;
    sfecha:tdate;
    i:integer;
    ext,nomarchivo:string;
begin
    qinfentregasmaterial.Close;
    qinfentregasmaterial.ParamByName('EMPRESA').AsInteger:=qempleadoside.AsInteger;
    qinfentregasmaterial.ParamByName('EMPLEADO').AsInteger:=qempleadosid.AsInteger;
    qinfentregasmaterial.ParamByName('FECHA').Asdate:=fentregamaterial.Date;
    qinfentregasmaterial.open;
    usbDevices := CoUsbDevices.Create();
    if (usbDevices.Count > 0) then
    begin
      try
        begin
          usbDevice := usbDevices.Item[0]; //select the first device
          vfirmas := Tvfirmas.Create(nil);
          try
            VFirmas.connect(usbDevice);
            VFirmas.ShowModal();
          finally
            vfirmas.Free;
            firmasdoc.Open;
            if firmasdoc.RecordCount=0 then
            begin
              firmasdoc.Append;
              firmasdocide.Value:=qempleadoside.asinteger;
              firmasdocidt.Value:=qempleadosid.asinteger;
              firmasdocfirma.LoadFromFile('c:\agrigest\tmp\firma.bmp');
              firmasdoc.Post;
            end else
            begin
              firmasdoc.edit;
              firmasdocide.Value:=qempleadoside.asinteger;
              firmasdocidt.Value:=qempleadosid.asinteger;
              firmasdocfirma.LoadFromFile('c:\agrigest\tmp\firma.bmp');
              firmasdoc.Post;
            end;
            if qemp_firmas.RecordCount=0 then
            begin
              qemp_firmas.Append;
              qemp_firmaside.Value:=qempleadoside.asinteger;
              qemp_firmasidt.Value:=qempleadosid.asinteger;
              qemp_firmasfirma.LoadFromFile('c:\agrigest\tmp\firma.bmp');
              qemp_firmas.Post;
            end else
            begin
              qemp_firmas.edit;
              qemp_firmaside.Value:=qempleadoside.asinteger;
              qemp_firmasidt.Value:=qempleadosid.asinteger;
              qemp_firmasfirma.LoadFromFile('c:\agrigest\tmp\firma.bmp');
              qemp_firmas.Post;
            end;
            tfirmas.Picture:=nil;
            tfirmas.Picture.LoadFromFile('c:\agrigest\tmp\firma.bmp');
            tfirmadocs.Picture.LoadFromFile('c:\agrigest\tmp\firma.bmp');
           end;

        end;
      except
        on e : Exception do ShowMessage(e.Message);
      end;
    end else
        begin
          ShowMessage('Dispositivo de firmas no conectado');
          if qemp_firmasfirma.asstring<>'' then
          begin
              qemp_firmasfirma.SaveToFile('c:\agrigest\tmp\firma.bmp');
              firmasdoc.Open;
              if firmasdoc.RecordCount=0 then
              begin
                firmasdoc.Append;
                firmasdocide.Value:=qempleadoside.asinteger;
                firmasdocidt.Value:=qempleadosid.asinteger;
                firmasdocfirma.LoadFromFile('c:\agrigest\tmp\firma.bmp');
                firmasdoc.Post;
              end else
              begin
                firmasdoc.edit;
                firmasdocide.Value:=qempleadoside.asinteger;
                firmasdocidt.Value:=qempleadosid.asinteger;
                firmasdocfirma.LoadFromFile('c:\agrigest\tmp\firma.bmp');
                firmasdoc.Post;
              end;
              tfirmadocs.Picture.LoadFromFile('c:\agrigest\tmp\firma.bmp');
            end;
           end;

        seleccionando:=1;
        decodedate(fentregamaterial.date,anyo,mes,dia);
        case mes of
            1: textmes:='enero';
            2: textmes:='febrero';
            3: textmes:='marzo';
            4: textmes:='abril';
            5: textmes:='mayo';
            6: textmes:='junio';
            7: textmes:='julio';
            8: textmes:='agosto';
            9: textmes:='septiembre';
            10: textmes:='octubre';
            11: textmes:='noviembre';
            12: textmes:='diciembre';
        end;
        fecha:=floattostr(dia)+' de '+textmes+' de '+floattostr(anyo);
        informedb.Datasource:=dsqinfentregasmaterial;
                informes.Report.Clear;
                informes.LoadFromFile('c:\agrigest\informes\entregamaterial.fr3');
                informes.Variables.Variables['v_fecha']:=QUOTEDSTR(' a '+fecha);
                informes.Variables.Variables['v_empleado']:=QUOTEDSTR(qempleadosnombre.AsString);
                informes.ShowReport();
///  grabo en documentos el documento firmado

                topdf.FileName:='ENTREGA DE MATERIAL-'+qempleadosnombre.AsString+'.pdf';
                topdf.DefaultPath:='c:\agrigest\tmp\';
                informes.Export(topdf);
                qaux.SQL.Clear;
                qaux.SQL.Add('delete from documentos_tmp ');
                qaux.ExecSQL;
                documentos_tmp.Open;
                try
                documentos_tmp.Append;
                ext:= '.pdf';//ExtractFileExt(opendialog2.FileName);
                nomarchivo:='ENTREGA DE MATERIAL-'+qempleadosnombre.AsString+'.pdf';//extractfilename(opendialog2.FileName);
                documentos_tmpidt.Value:=qempleadosid.Asinteger;
                documentos_tmpfecha.Value:=fentregamaterial.date;
                documentos_tmpide.Value:=qempleadoside.AsInteger;
                documentos_tmpnomarchivo.Value:=nomarchivo;
                documentos_tmpdescripcion.Value:=nomarchivo;
                documentos_tmpextension.Value:=ext;
                documentos_tmparchivo.LoadFromFile(topdf.DefaultPath+nomarchivo);
                documentos_tmp.Post;
                finally
                  deletefile(topdf.FileName);
                end;
                qaux.SQL.Clear;
                qaux.SQL.Add('insert into documentos (ide,fecha,descripcion,archivo,nomarchivo,extension,idlote,codpar,idea,idt) (select ide,fecha,descripcion,archivo,nomarchivo,extension,idlote,codpar,idea,idt from documentos_tmp)');
                qaux.ExecSQL;
                qaux.SQL.Clear;
                qaux.SQL.Add('delete from documentos_tmp ');
                qaux.ExecSQL;
                documentos.Open;
                documentos.refresh;
end;

procedure Tfempleados.btEMmodificarClick(Sender: TObject);
begin
    panel30.Visible:=true;
    fentregamaterial.SetFocus;
    btEMaceptar.Enabled:=true;
    btEMcancelar.Enabled:=true;
    btEMnuevo.Enabled:=false;
    btEMmodificar.Enabled:=false;
    btEMborrar.Enabled:=false;
    fentregamaterial.Date:=qentregasmaterialfecha.Asdatetime;
    edit1.Text:=qentregasmaterialconcepto.AsString;
    edit2.Text:=qentregasmaterialcantidad.AsString;
    qentregasmaterial.Edit;
end;

procedure Tfempleados.btEMnuevoClick(Sender: TObject);
begin
    panel30.Enabled:=true;
    panel30.Visible:=true;
    fentregamaterial.Date:=date();
    fentregamaterial.SetFocus;
    btEMaceptar.Enabled:=true;
    btEMcancelar.Enabled:=true;
    btEMnuevo.Enabled:=false;
    btEMmodificar.Enabled:=false;
    btEMborrar.Enabled:=false;
end;

procedure Tfempleados.btEmodificarClick(Sender: TObject);
begin
    qempleados.Edit;
    if qempleadosplanificacion.Active then
    begin
      if qempleadosplanificacion.IsEmpty then
      begin
        qempleadosplanificacion.Append;
        qempleadosplanificacionidt.AsInteger := qempleadosid.AsInteger;
        qempleadosplanificacionide.AsInteger := qempleadoside.AsInteger;
        qempleadosplanificacionembargos.AsString := 'NO';
      end
      else
        qempleadosplanificacion.Edit;
    end;
    panel33.Enabled:=true;
    panel9.Enabled:=true;

end;

procedure Tfempleados.btEnuevoClick(Sender: TObject);
begin
    qempleados.Append;
    qempleadosplanificacion.Close;
    qempleadosplanificacion.ParamByName('EMPRESA').AsInteger := dm.tempresaid.AsInteger;
    qempleadosplanificacion.ParamByName('EMPLEADO').AsInteger := -1;
    qempleadosplanificacion.Open;
    qempleadosplanificacion.Append;
    qempleadosplanificacionidt.AsInteger := qempleadosid.AsInteger;
    qempleadosplanificacionide.AsInteger := dm.tempresaid.AsInteger;
    qempleadosplanificacionembargos.AsString := 'NO';
    panel33.Enabled:=true;
    panel9.Enabled:=true;
end;

procedure Tfempleados.btEoKimagenClick(Sender: TObject);
var  imagen : TBitmap;
     imagen2: tPicture;
     archivo:TMemorystream;
     ext: string;
begin
if bteimagen.Caption ='Capturar imagen' then
begin
    imagen := TBitmap.Create;
    imagen2:= tPicture.Create;
    archivo:= tMemorystream.Create;
    try
      archivo.LoadFromFile('c:\agrigest\tmp\'+qempleadosid.AsString+'.bmp');
      imagen2.loadFromFile('c:\agrigest\tmp\'+qempleadosid.AsString+'.bmp');
      image2.Picture.LoadFromFile('c:\agrigest\tmp\'+qempleadosid.AsString+'.bmp');
      image2.Visible:=true;
//      qempleados.edit;
//      dm.trabajadoresimagen.LoadFromFile('c:\controlgest\IMAGENES\'+dm.trabajadoresid.AsString+'.bmp');
//      dm.trabajadorestipoimagen.Value:=ext;
//      qempleados.Post;
     if qemp_fotos.RecordCount=0 then
     begin
       qemp_fotos.Append;
       qemp_fotosidt.Value:=qempleadosid.Asinteger;
       qemp_fotoside.Value:=qempleadoside.AsInteger;
       qemp_fotosimagen.LoadFromFile('c:\agrigest\tmp\'+qempleadosid.AsString+'.bmp');//openpicturedialog1.FileName);
       qemp_fotosextension.Value:='.bmp';
       qemp_fotos.Post;
       If not DirectoryExists('c:\agrigest\tmp') then CreateDir('c:\agrigest\tmp');
       Deletefile('c:\agrigest\tmp\'+qempleadosid.AsString+'.bmp');
       image2.Picture:=nil;
       qemp_fotosimagen.savetofile('c:\agrigest\tmp\'+qempleadosid.AsString+'.bmp');
       image2.Picture.LoadFromFile('c:\agrigest\tmp\'+qempleadosid.AsString+'.bmp');
     end else
     begin
       qemp_fotos.edit;
       qemp_fotosidt.Value:=qempleadosid.Asinteger;
       qemp_fotoside.Value:=qempleadoside.AsInteger;
       qemp_fotosimagen.LoadFromFile('c:\agrigest\tmp\'+qempleadosid.AsString+'.bmp');//openpicturedialog1.FileName);
       qemp_fotosextension.Value:='.bmp';
       qemp_fotos.Post;
       If not DirectoryExists('c:\agrigest\tmp') then CreateDir('c:\agrigest\tmp');
       Deletefile('c:\agrigest\tmp\'+qempleadosid.AsString+'.bmp');
       image2.Picture:=nil;
       qemp_fotosimagen.savetofile('c:\agrigest\tmp\'+qempleadosid.AsString+'.bmp');
       image2.Picture.LoadFromFile('c:\agrigest\tmp\'+qempleadosid.AsString+'.bmp');
     end;

    finally
      imagen.Free;
      imgfotoe.Picture:=nil;
      imgfotoe.Visible:=false;
      panelfotoe.Visible:=false;
      Deletefile('c:\agrigest\tmp\'+qempleadosid.AsString+'.bmp');
    end;


end else
begin
     if qemp_fotos.RecordCount=0 then
     begin
       qemp_fotos.Append;
       qemp_fotosidt.Value:=qempleadosid.Asinteger;
       qemp_fotoside.Value:=qempleadoside.AsInteger;
       qemp_fotosimagen.LoadFromFile(openpicturedialog1.FileName);
       ext:=ExtractFileExt(openpicturedialog1.FileName);
       qemp_fotosextension.Value:=ext;//ExtractFileExt(openpicturedialog1.FileName);//'.bmp';
       qemp_fotos.Post;
       If not DirectoryExists('c:\agrigest\tmp') then CreateDir('c:\agrigest\tmp');
       Deletefile('c:\agrigest\tmp\empimg'+ext);
       image2.Picture:=nil;
       qemp_fotosimagen.savetofile('c:\agrigest\tmp\empimg'+ext);
       image2.Picture.LoadFromFile('c:\agrigest\tmp\empimg'+ext);
     end else
     begin
       qemp_fotos.edit;
       qemp_fotosidt.Value:=qempleadosid.Asinteger;
       qemp_fotoside.Value:=qempleadoside.AsInteger;
       qemp_fotosimagen.LoadFromFile(openpicturedialog1.FileName);
       ext:=ExtractFileExt(openpicturedialog1.FileName);
       qemp_fotosextension.Value:=ext;//ExtractFileExt(openpicturedialog1.FileName);//'.bmp';
       qemp_fotos.Post;
       If not DirectoryExists('c:\agrigest\tmp') then CreateDir('c:\agrigest\tmp');
       Deletefile('c:\agrigest\tmp\empimg'+ext);
       image2.Picture:=nil;
       qemp_fotosimagen.savetofile('c:\agrigest\tmp\empimg'+ext);
       image2.Picture.LoadFromFile('c:\agrigest\tmp\empimg'+ext);
     end;

end;
    bteimagen.Caption:='Cargar imagen';
    panelfotoe.Visible:=false;
    imgfotoe.Visible:=false;
    btdesactivarcamara.Click;
    bteokimagen.Visible:=false;
end;


procedure Tfempleados.FechaPlanificacionSetText(Sender: TField; const Text: string);
var
  LClean: string;
  LDate: TDateTime;
begin
  LClean := StringReplace(Text, '/', '', [rfReplaceAll]);
  LClean := StringReplace(LClean, '_', '', [rfReplaceAll]);
  LClean := StringReplace(LClean, '-', '', [rfReplaceAll]);
  LClean := StringReplace(LClean, '.', '', [rfReplaceAll]);
  LClean := Trim(LClean);

  if LClean = '' then
    Sender.Clear
  else
  begin
    if TryStrToDate(Trim(Text), LDate) then
      Sender.AsDateTime := LDate
    else
      raise Exception.CreateFmt('"%s" no es una fecha válida.', [Trim(Text)]);
  end;
end;

procedure Tfempleados.FechaPlanificacionGetText(Sender: TField; var Text: string; DisplayText: Boolean);
begin
  if Sender.IsNull or (Sender.AsDateTime = 0) then
    Text := ''
  else
    Text := FormatDateTime('dd/mm/yyyy', Sender.AsDateTime);
end;

procedure Tfempleados.ConfigurarCamposFechaPlanificacion;
var
  i: Integer;
  LField: TField;
begin
  for i := 0 to qempleadosplanificacion.FieldCount - 1 do
  begin
    LField := qempleadosplanificacion.Fields[i];
    if (LField is TDateField) or (LField is TDateTimeField) then
    begin
      TDateField(LField).DisplayFormat := 'dd/mm/yyyy';
      LField.EditMask := '!99/99/9999;1;_';
      LField.OnGetText := FechaPlanificacionGetText;
      LField.OnSetText := FechaPlanificacionSetText;
    end;
  end;
end;

procedure Tfempleados.qempleadosplanificacionBeforePost(DataSet: TDataSet);
var
  i: Integer;
  LField: TField;
  LClean: string;
  LDate: TDateTime;
begin
  for i := 0 to DataSet.FieldCount - 1 do
  begin
    LField := DataSet.Fields[i];
    if (LField is TDateField) or (LField is TDateTimeField) then
    begin
      if not LField.IsNull then
      begin
        LClean := StringReplace(LField.AsString, '/', '', [rfReplaceAll]);
        LClean := StringReplace(LClean, '_', '', [rfReplaceAll]);
        LClean := StringReplace(LClean, '-', '', [rfReplaceAll]);
        LClean := StringReplace(LClean, '.', '', [rfReplaceAll]);
        LClean := Trim(LClean);
        if LClean = '' then
          LField.Clear
        else if not TryStrToDate(Trim(LField.AsString), LDate) then
          LField.Clear;
      end;
    end;
  end;
end;

procedure Tfempleados.btplaceptarClick(Sender: TObject);
var idt,ide:string;
begin
   if qempleadosplanificacion.State in [dsEdit, dsInsert] then
     qempleadosplanificacion.Post;
   if qlistadoplanificacion.Active then
     qlistadoplanificacion.Refresh;
   idt:=qempleadosplanificacionidt.AsString;
   ide:=qempleadosplanificacionide.AsString;
   qlistaempleados.Refresh;
   qlistaempleados.Locate('id',idt,[locaseinsensitive]);
end;

procedure Tfempleados.btplcancelarClick(Sender: TObject);
begin
    if qempleadosplanificacion.State in [dsEdit, dsInsert] then
      qempleadosplanificacion.Cancel;
end;

procedure Tfempleados.btplmodificarClick(Sender: TObject);
begin
    qempleadosplanificacion.Edit;
end;

procedure Tfempleados.btptborrarClick(Sender: TObject);
begin
   qjornales.Delete;
end;

procedure Tfempleados.btptcancelarClick(Sender: TObject);
begin
    if qjornales.State in [dsedit,dsinsert] then qjornales.Cancel;

end;

procedure Tfempleados.btptguardarClick(Sender: TObject);
var totaljornal:real;
begin

if dsqjornales.State in [dsinsert] then
begin
    qaux.Close;
    qaux.SQL.Clear;
    qaux.SQL.Add('select max(id)+1 from trabajo_diario');
    qaux.Open;
    qjornalesid.Value:=qaux.Fields[0].Asinteger;
    qjornalesfecha.Value:=tfechajornal.Date;
    qjornalesparcela.value:=lparcela.KeyValue;
    qjornalesidt.Value:=qlistaempleadosid.asinteger;
    qjornalestrabajador.Value:=qlistaempleadosnombre.asstring;
    qjornalestypework.Value:=ltrabajo.KeyValue;
    qjornalesarticulo.Value:=ltipohora.KeyValue;
    qjornalesqhoras.Value:=strtofloat(thoras.text);
    qjornalesprecio.value:=strtofloat(lprecio.Text);
    totaljornal:=strtofloat(thoras.text)*strtofloat(lprecio.Text);
    qjornalestotal.Value:=strtofloat(FormatFloat('0.00',totaljornal));
    qjornalesestado.Value:='C';
    qjornales.Post;
    qjornales.Refresh;
    qjornales.First;
    tfechajornal.Enabled:=false;
    lparcela.Enabled:=false;
    ltrabajo.Enabled:=false;
    ltipohora.Enabled:=false;
    thoras.Enabled:=false;
    lprecio.Enabled:=false;
end;
if dsqjornales.State=dsedit then
begin
   qjornalesfecha.Value:=tfechajornal.Date;
   qjornalesparcela.value:=lparcela.KeyValue;
   qjornalestypework.Value:=ltrabajo.KeyValue;
   qjornalesarticulo.Value:=ltipohora.KeyValue;
   qjornalesqhoras.Value:=strtofloat(thoras.text);
   qjornalesprecio.value:=strtofloat(lprecio.Text);
   totaljornal:=strtofloat(thoras.text)*strtofloat(lprecio.Text);
   qjornalestotal.Value:=strtofloat(FormatFloat('0.00',totaljornal));
   qjornalesestado.Value:='C';
   qjornales.Post;
   qjornales.Refresh;
   qjornales.First;
   tfechajornal.Enabled:=false;
   lparcela.Enabled:=false;
   ltrabajo.Enabled:=false;
   ltipohora.Enabled:=false;
   thoras.Enabled:=false;
   lprecio.Enabled:=false;
end;

end;

procedure Tfempleados.btptmodificarClick(Sender: TObject);
begin
   tfechajornal.Date:=qjornalesfecha.AsDateTime;
   ltrabajo.KeyValue:= qjornalestypework.AsString;
   lparcela.KeyValue:= qjornalesparcela.AsString;
   ltipohora.KeyValue:= qjornalesarticulo.AsString;
   lprecio.Text:=qtipohoraprecio.asstring;
   thoras.Text:= qjornalesqhoras.AsString;
   tfechajornal.Enabled:=true;
   lparcela.Enabled:=true;
   ltrabajo.Enabled:=true;
   ltipohora.Enabled:=true;
   thoras.Enabled:=true;
   lprecio.Enabled:=true;
   qjornales.Edit;

end;

procedure Tfempleados.btptnuevoClick(Sender: TObject);
begin
    tfechajornal.Enabled:=true;
    lparcela.Enabled:=true;
    ltrabajo.Enabled:=true;
    ltipohora.Enabled:=true;
    thoras.Enabled:=true;
    lprecio.Enabled:=true;
    tfechajornal.SetFocus;
    qjornales.Append;
end;

procedure Tfempleados.btEguardarClick(Sender: TObject);
var
  tid: string;
  vEraNuevo: Boolean;
  vEmbargosNuevo: string;
begin
    tid:=qempleadosid.AsString;
    vEraNuevo := (qempleados.State = dsInsert);
    if vEraNuevo and (qempleadosplanificacion.State in [dsEdit, dsInsert]) then
    begin
      vEmbargosNuevo := qempleadosplanificacionembargos.AsString;
      qempleadosplanificacion.Cancel;
    end
    else
      vEmbargosNuevo := '';

    if qempleados.State in [dsedit,dsinsert] then qempleados.Post;

    if vEraNuevo then
    begin
      if (vEmbargosNuevo <> '') and (vEmbargosNuevo <> 'NO') then
      begin
        qaux.Close;
        qaux.SQL.Text := 'update empleados_planificacion set embargos = :EMBARGOS where idt = :IDT and ide = :IDE';
        qaux.ParamByName('EMBARGOS').AsString := vEmbargosNuevo;
        qaux.ParamByName('IDT').AsInteger := pidt;
        qaux.ParamByName('IDE').AsInteger := pide;
        qaux.ExecSQL;
      end;
    end
    else if qempleadosplanificacion.State in [dsEdit, dsInsert] then
      qempleadosplanificacion.Post;

    qlistaempleados.Refresh;
    qlistaempleados.Locate('id',tid,[locaseinsensitive]);
    panel33.Enabled:=false;
    panel9.Enabled:=false;
    if qconvocatorias.Active then
      qconvocatorias.Refresh
    else
      qconvocatorias.Open;

end;

procedure Tfempleados.btEimagenClick(Sender: TObject);
var
  PanelDC: HDC;
  Jpg : TJPEGImage;
  bmp : Tbitmap;
  imagen : TPicture;
  ext:string;
//  imagen : TJPEGImage;

begin

if (Sender as TButton).Caption ='Cargar imagen' then
begin

  if OpenPictureDialog1.Execute then
  begin
//    imagen := TJPEGImage.Create;
    imagen := TPicture.Create;
    bmp:= TBitmap.Create;
    jpg:=TJPEGImage.Create;

    try

      ext:= ExtractFileExt(openpicturedialog1.FileName);
      if (ext='.jpg') or (ext='jpeg') then
      begin
        imgfotoe.Picture.LoadFromFile(OpenPictureDialog1.FileName);//'c:\formagest\imagenes\'+dm.alumnosid.asstring+'.bmp');
        bteokimagen.Visible:=true;
      end else
      begin
          imgfotoe.Picture.LoadFromFile(OpenPictureDialog1.FileName);//'c:\formagest\imagenes\'+dm.alumnosid.asstring+'.bmp');
          bteokimagen.Visible:=true;
      end;
      imgfotoe.Visible:=true;
    finally
      imagen.Free;
    end;
  end;
end;


end;

procedure Tfempleados.checktodos2Click(Sender: TObject);
begin
  seleccionando:=1;
  if checktodos2.checked then
  begin
      with qlistaempleados do
      begin
        First;
        while not EOF do
        begin
          Dbgrid1.SelectedRows.CurrentRowSelected := True;
          next;
        end
      end;
  end else
  begin
      with qlistaempleados do
      begin
        First;
        while not EOF do
        begin
          Dbgrid1.SelectedRows.CurrentRowSelected := false;
          next;
        end
      end;
  end;
  seleccionando:=0;
end;

procedure Tfempleados.chktodosempleadosClick(Sender: TObject);
begin
  FiltrarListaEmpleados;
end;

{-------------------------------------------------------------------------------
  Carga los valores distintos del campo SEXO desde la base de datos (trabajadores)
  incluyendo la opción 'cualquiera' por defecto.
  Utiliza TZQuery con conexión DM.DBagrigest y gestión estricta con try..finally.
-------------------------------------------------------------------------------}
procedure Tfempleados.CargarFiltroSexo;
var
  LQuery: TZQuery;
begin
  cbsexo.Items.BeginUpdate;
  try
    cbsexo.Items.Clear;
    cbsexo.Items.Add('cualquiera');

    LQuery := TZQuery.Create(nil);
    try
      LQuery.Connection := dm.DBagrigest;
      LQuery.SQL.Text := 'SELECT DISTINCT sexo FROM trabajadores ' +
                         'WHERE (sexo IS NOT NULL) AND (TRIM(sexo) <> '''') ' +
                         'ORDER BY sexo';
      LQuery.Open;
      while not LQuery.Eof do
      begin
        if Trim(LQuery.FieldByName('sexo').AsString) <> '' then
          cbsexo.Items.Add(Trim(LQuery.FieldByName('sexo').AsString));
        LQuery.Next;
      end;
    finally
      LQuery.Free;
    end;
  finally
    cbsexo.Items.EndUpdate;
  end;
  cbsexo.ItemIndex := 0;
end;

procedure Tfempleados.cbsexoChange(Sender: TObject);
begin
  FiltrarListaEmpleados;
end;

procedure Tfempleados.DBEdit10Exit(Sender: TObject);
begin
end;

procedure Tfempleados.DBEdit10KeyUp(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
end;

procedure Tfempleados.DBEdit13Exit(Sender: TObject);
begin
end;

procedure Tfempleados.DBEdit13KeyUp(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
end;

procedure Tfempleados.DBEdit21Exit(Sender: TObject);
begin
end;

procedure Tfempleados.DBEdit21KeyUp(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
end;

procedure Tfempleados.DBEdit26Exit(Sender: TObject);
begin
end;

procedure Tfempleados.DBEdit26KeyUp(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
end;

procedure Tfempleados.DBEdit27Change(Sender: TObject);
begin
    DBEDIT2.Text:=DBEDIT8.Text+' '+DBEDIT27.Text;
end;

procedure Tfempleados.DBEdit40Exit(Sender: TObject);
begin
end;

procedure Tfempleados.DBEdit40KeyUp(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
end;

procedure Tfempleados.DBEdit41KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
    if (key=115) then
    begin
      qtaquillas.Close;
      qtaquillas.Open;
      seleccionartaquilla := Tseleccionartaquilla.Create(nil);
      try
        seleccionartaquilla.showmodal();
      finally
        seleccionartaquilla.Free;
        qempleadosnum_taquilla.value:=qtaquillasid.AsInteger;
      end;
    end;
end;

procedure Tfempleados.DBEdit43Enter(Sender: TObject);
begin
    if qconvocatorias.Active then
      qconvocatorias.Refresh
    else
      qconvocatorias.Open;
    listaconvocatorias.Visible:=not listaconvocatorias.Visible;
end;

procedure Tfempleados.DBEdit8Change(Sender: TObject);
begin
    DBEDIT2.Text:=DBEDIT8.Text+' '+DBEDIT27.Text;
end;

procedure Tfempleados.DBEdit9Exit(Sender: TObject);
begin
    qaux.Close;
    qaux.SQL.Clear;
    qaux.SQL.Add('select nombre,nif from trabajadores where nif='+''''+dbedit9.Text+'''');
    qaux.Open;
    if (qaux.RecordCount=0) and (qempleados.State in [dsinsert]) then
    begin
       if (not esnif(dbedit9.Text)) and (not escif(dbedit9.Text)) then showmessage('��� EL NIF INTRODUCIDO ES ERRONEO ���');
    end;
    if (qaux.RecordCount=0) and (qempleados.State in [dsedit]) then
    begin
       if (not esnif(dbedit9.Text)) and (not escif(dbedit9.Text)) then showmessage('��� EL NIF INTRODUCIDO ES ERRONEO ���');
    end;
    if (qaux.RecordCount>0) then
    begin
       showmessage('��� EL TRABAJADOR/A YA EXISTE ���');
       qempleados.Cancel;
       tbuscar.Text:=qaux.Fields[0].AsString;
       chktodosempleados.Checked:=true;
    end;

end;

procedure Tfempleados.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
  DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
     if (qlistaempleadosvto_permisotrabajo.AsString<>'') and (qlistaempleadosvto_permisotrabajo.asdatetime<=date()+10 )then
    begin
        DBGrid1.Canvas.brush.Color := rojo;
    end;
    DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;

procedure Tfempleados.DBGrid1TitleClick(Column: TColumn);
var
  st:ZAbstractRODataset.TSortType;
begin
  st:=qlistaempleados.SortType;
  qlistaempleados.SortedFields:=Column.FieldName;
  If st = stAscending then qlistaempleados.SortType:=stDescending else qlistaempleados.SortType:=stAscending;
  dsqlistaempleados.DataSet.First;
end;

procedure Tfempleados.DBGrid2CellClick(Column: TColumn);
begin
   if (qjornalesestado.AsString='C') OR (qjornalesestado.AsString='S') then
   BEGIN
    if qjornalesestado.AsString='C' then
    begin
       qjornales.Edit;
       qjornalesestado.value:='S';
       qjornales.Post;
    end ELSE
    begin

       qjornales.Edit;
       qjornalesestado.value:='C';
       qjornales.Post;
    end;
   END;

end;

procedure Tfempleados.DBGrid2DrawColumnCell(Sender: TObject; const Rect: TRect;
  DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
    if qjornalesestado.AsString='C' then
    begin
        DBGrid2.Canvas.brush.Color := amarillo;
    end;
    if qjornalesestado.AsString='S' then
    begin
        DBGrid2.Canvas.brush.Color := rojo;
    end;
    if qjornalesestado.AsString='V' then
    begin
        DBGrid2.Canvas.brush.Color := azul;
    end;
    if qjornalesestado.AsString='P' then
    begin
        DBGrid2.Canvas.brush.Color := verde;
    end;

    DBGrid2.DefaultDrawColumnCell(Rect, DataCol, Column, State);

end;

procedure Tfempleados.DBGrid5CellClick(Column: TColumn);
begin
  fentregamaterial.Date:=qentregasmaterialfecha.AsDateTime;
end;

procedure Tfempleados.DBGrid75DrawColumnCell(Sender: TObject; const Rect: TRect;
  DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
     if (qlistadoplanificacionvto_permisotrabajo.AsString<>'') and (qlistadoplanificacionvto_permisotrabajo.asdatetime<=date()+10 )then
    begin
        DBGrid75.Canvas.brush.Color := rojo;
    end;
    DBGrid75.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;

procedure Tfempleados.DBLookupComboBox1DropDown(Sender: TObject);
begin
    if qempleados.State in [dsinsert] then
    begin
      qempleadosirpf.Value:=qregimencotizacionirpf.AsFloat;
      qempleadosformacion.Value:=qregimencotizacionformacion.AsFloat;
      qempleadosdesempleo.Value:=qregimencotizaciondesempleo.AsFloat;
      qempleadoscontingencias.Value:=qregimencotizacioncontingencias.AsFloat;
    end;
end;

procedure Tfempleados.dsqanticiposStateChange(Sender: TObject);
begin
    if qanticipos.State in [dsedit,dsinsert] then
    begin
        bteanuevo.Enabled:=false;
        bteamodificar.Enabled:=false;
        bteaborrar.Enabled:=false;
        bteacancelar.Enabled:=true;
        bteaguardar.Enabled:=true;
    end else
    begin
        bteanuevo.Enabled:=true;
        bteamodificar.Enabled:=true;
        bteaborrar.Enabled:=true;
        bteacancelar.Enabled:=false;
        bteaguardar.Enabled:=false;
    end;
end;

procedure Tfempleados.dsqempleadosplanificacionStateChange(Sender: TObject);
begin
    if qempleadosplanificacion.State in [dsedit] then
    begin
        panel18.Enabled:=true;
        panel19.Enabled:=true;
        panel20.Enabled:=true;
        btplaceptar.Enabled:=true;
        btplcancelar.Enabled:=true;
        btplmodificar.Enabled:=false;
    end else
    begin
        panel18.Enabled:=false;
        panel19.Enabled:=false;
        panel20.Enabled:=false;
        btplaceptar.Enabled:=false;
        btplcancelar.Enabled:=false;
        btplmodificar.Enabled:=true;
    end;

end;

procedure Tfempleados.dsqempleadosStateChange(Sender: TObject);
begin
    if qempleados.State in [dsedit,dsinsert] then
    begin
        btenuevo.Enabled:=false;
        btemodificar.Enabled:=false;
        bteborrar.Enabled:=false;
        btecancelar.Enabled:=true;
        bteguardar.Enabled:=true;
//        btfanterior.Enabled:=false;
  //      btfsiguiente.Enabled:=false;
    //    btfimportar.Enabled:=false;
      //  btfimprimir.Enabled:=false;
    end else
    begin
        btenuevo.Enabled:=true;
        btemodificar.Enabled:=true;
        bteborrar.Enabled:=true;
        btecancelar.Enabled:=false;
        bteguardar.Enabled:=false;
//        btfanterior.Enabled:=true;
//        btfsiguiente.Enabled:=true;
  //      btfimportar.Enabled:=true;
//        btfimprimir.Enabled:=true;
    end;
end;

procedure Tfempleados.dsqjornalesStateChange(Sender: TObject);
begin
    if qjornales.State in [dsedit,dsinsert] then
    begin
        btptnuevo.Enabled:=false;
        btptmodificar.Enabled:=false;
        btptborrar.Enabled:=false;
        btptcancelar.Enabled:=true;
        btptguardar.Enabled:=true;
    end else
    begin
        btptnuevo.Enabled:=true;
        btptmodificar.Enabled:=true;
        btptborrar.Enabled:=true;
        btptcancelar.Enabled:=false;
        btptguardar.Enabled:=false;
    end;
end;

procedure Tfempleados.CargarBlobEnImagen(CampoBlob: TBlobField; Destino: TPicture; const Ext: string);
var
  Stream: TMemoryStream;
  Jpg: TJPEGImage;
  Png: TPngImage;
  Bmp: TBitmap;
  ExtLimpia: string;
begin
  Destino.Assign(nil);
  if (CampoBlob = nil) or CampoBlob.IsNull or (CampoBlob.BlobSize = 0) then
    Exit;

  Stream := TMemoryStream.Create;
  try
    CampoBlob.SaveToStream(Stream);
    if Stream.Size = 0 then
      Exit;
    Stream.Position := 0;

    ExtLimpia := LowerCase(Trim(Ext));
    if (ExtLimpia = '.jpg') or (ExtLimpia = 'jpg') or (ExtLimpia = '.jpeg') or (ExtLimpia = 'jpeg') then
    begin
      Jpg := TJPEGImage.Create;
      try
        try
          Jpg.LoadFromStream(Stream);
          Destino.Assign(Jpg);
        except
          Stream.Position := 0;
          Bmp := TBitmap.Create;
          try
            Bmp.LoadFromStream(Stream);
            Destino.Assign(Bmp);
          except
          end;
          Bmp.Free;
        end;
      finally
        Jpg.Free;
      end;
    end
    else if (ExtLimpia = '.png') or (ExtLimpia = 'png') then
    begin
      Png := TPngImage.Create;
      try
        try
          Png.LoadFromStream(Stream);
          Destino.Assign(Png);
        except
          Stream.Position := 0;
          Bmp := TBitmap.Create;
          try
            Bmp.LoadFromStream(Stream);
            Destino.Assign(Bmp);
          except
          end;
          Bmp.Free;
        end;
      finally
        Png.Free;
      end;
    end
    else
    begin
      Bmp := TBitmap.Create;
      try
        try
          Bmp.LoadFromStream(Stream);
          Destino.Assign(Bmp);
        except
          Stream.Position := 0;
          Jpg := TJPEGImage.Create;
          try
            Jpg.LoadFromStream(Stream);
            Destino.Assign(Jpg);
          except
          end;
          Jpg.Free;
        end;
      finally
        Bmp.Free;
      end;
    end;
  finally
    Stream.Free;
  end;
end;

procedure Tfempleados.CargarDatosEmpleadoActual(ActiveTabIndex: Integer);
var
  empleado, empresa: Integer;
  anyo, mes: string;
begin
  if (qlistaempleados.Active) and (qlistaempleados.RecordCount > 0) then
  begin
    empleado := qlistaempleadosid.AsInteger;
    empresa := qlistaempleadoside.AsInteger;
  end
  else
  begin
    empleado := 0;
    empresa := 0;
  end;

  case ActiveTabIndex of
    0: // Datos del Empleado
      begin
        if empleado > 0 then
        begin
          if (not qempleados.Active) or (qempleadosid.AsInteger <> empleado) or (qempleadoside.AsInteger <> empresa) then
          begin
            qempleados.Close;
            qempleados.ParamByName('EMPLEADO').AsInteger := empleado;
            qempleados.ParamByName('EMPRESA').AsInteger := empresa;
            qempleados.Open;
          end;

          if (not qempleadosplanificacion.Active) or (qempleadosplanificacionidt.AsInteger <> empleado) or (qempleadosplanificacionide.AsInteger <> empresa) then
          begin
            qempleadosplanificacion.Close;
            qempleadosplanificacion.ParamByName('EMPRESA').AsInteger := empresa;
            qempleadosplanificacion.ParamByName('EMPLEADO').AsInteger := empleado;
            qempleadosplanificacion.Open;
            ConfigurarCamposFechaPlanificacion;
          end;

          if qempleadosplanificacion.IsEmpty then
          begin
            qempleadosplanificacion.Append;
            qempleadosplanificacionidt.AsInteger := empleado;
            qempleadosplanificacionide.AsInteger := empresa;
            qempleadosplanificacionembargos.AsString := 'NO';
            qempleadosplanificacion.Post;
          end;

          if qempleados.RecordCount > 0 then
          begin
            qemp_fotos.Close;
            qemp_fotos.ParamByName('EMPLEADO').AsInteger := empleado;
            qemp_fotos.ParamByName('EMPRESA').AsInteger := empresa;
            qemp_fotos.Open;
            if qemp_fotos.RecordCount > 0 then
              CargarBlobEnImagen(qemp_fotosimagen, image2.Picture, qemp_fotosextension.AsString)
            else
              image2.Picture.Assign(nil);

            qemp_firmas.Close;
            qemp_firmas.ParamByName('EMPLEADO').AsInteger := empleado;
            qemp_firmas.ParamByName('EMPRESA').AsInteger := empresa;
            qemp_firmas.Open;
            if qemp_firmas.RecordCount > 0 then
              CargarBlobEnImagen(qemp_firmasfirma, tfirmas.Picture, 'bmp')
            else
              tfirmas.Picture.Assign(nil);

            if not qemp_historico.Active then
              qemp_historico.Open;

            documentos.Close;
            documentos.ParamByName('EMPLEADO').AsInteger := empleado;
            documentos.ParamByName('EMPRESA').AsInteger := empresa;
            documentos.Open;
          end
          else
          begin
            image2.Picture.Assign(nil);
            tfirmas.Picture.Assign(nil);
            documentos.Close;
          end;
        end
        else
        begin
          qempleados.Close;
          qempleadosplanificacion.Close;
          qemp_fotos.Close;
          qemp_firmas.Close;
          documentos.Close;
          image2.Picture.Assign(nil);
          tfirmas.Picture.Assign(nil);
        end;
      end;

    1: // Planificación
      begin
        if not qpuestostrabajo.Active then
          qpuestostrabajo.Open;

        if empleado > 0 then
        begin
          if (not qempleados.Active) or (qempleadosid.AsInteger <> empleado) or (qempleadoside.AsInteger <> empresa) then
          begin
            qempleados.Close;
            qempleados.ParamByName('EMPLEADO').AsInteger := empleado;
            qempleados.ParamByName('EMPRESA').AsInteger := empresa;
            qempleados.Open;
          end;

          qempleadosplanificacion.Close;
          qempleadosplanificacion.ParamByName('EMPRESA').AsInteger := empresa;
          qempleadosplanificacion.ParamByName('EMPLEADO').AsInteger := empleado;
          qempleadosplanificacion.Open;
          ConfigurarCamposFechaPlanificacion;

          documentos.Close;
          documentos.ParamByName('EMPLEADO').AsInteger := empleado;
          documentos.ParamByName('EMPRESA').AsInteger := empresa;
          documentos.Open;
        end
        else
        begin
          qempleados.Close;
          qempleadosplanificacion.Close;
          documentos.Close;
        end;
      end;

    2: // Entregas de material
      begin
        if not qepis.Active then
          qepis.Open;

        if empleado > 0 then
        begin
          if (not qempleados.Active) or (qempleadosid.AsInteger <> empleado) or (qempleadoside.AsInteger <> empresa) then
          begin
            qempleados.Close;
            qempleados.ParamByName('EMPLEADO').AsInteger := empleado;
            qempleados.ParamByName('EMPRESA').AsInteger := empresa;
            qempleados.Open;
          end;

          btEMaceptar.Enabled := false;
          btEMcancelar.Enabled := false;
          btEMnuevo.Enabled := true;
          btEMmodificar.Enabled := true;
          btEMborrar.Enabled := true;

          qentregasmaterial.Close;
          qentregasmaterial.ParamByName('EMPLEADO').AsInteger := empleado;
          qentregasmaterial.ParamByName('EMPRESA').AsInteger := empresa;
          qentregasmaterial.Open;

          qlistadoentregasmaterial.Close;
          qlistadoentregasmaterial.ParamByName('EMPRESA').AsInteger := empresa;
          qlistadoentregasmaterial.ParamByName('EMPLEADO').AsInteger := empleado;
          qlistadoentregasmaterial.Open;
        end
        else
        begin
          qempleados.Close;
          qentregasmaterial.Close;
          qlistadoentregasmaterial.Close;
        end;
      end;

    3: // Partes de trabajo (Jornales)
      begin
        if not qparcelas.Active then
          qparcelas.Open;
        if not qtareas.Active then
          qtareas.Open;
        if not qtipohora.Active then
          qtipohora.Open;

        if empleado > 0 then
        begin
          if (not qempleados.Active) or (qempleadosid.AsInteger <> empleado) or (qempleadoside.AsInteger <> empresa) then
          begin
            qempleados.Close;
            qempleados.ParamByName('EMPLEADO').AsInteger := empleado;
            qempleados.ParamByName('EMPRESA').AsInteger := empresa;
            qempleados.Open;
          end;

          tfechajornal.Date := Date;
          if tanyo.ItemIndex > 0 then anyo := tanyo.Text else anyo := '%';
          if tmes.ItemIndex > 0 then mes := IntToStr(tmes.ItemIndex) else mes := '%';

          qjornales.Close;
          qjornales.ParamByName('EMPLEADO').AsInteger := empleado;
          qjornales.ParamByName('EMPRESA').AsInteger := empresa;
          qjornales.ParamByName('ANYO').AsString := anyo;
          qjornales.ParamByName('MES').AsString := mes;
          qjornales.Open;
        end
        else
        begin
          qempleados.Close;
          qjornales.Close;
        end;
      end;

    4: // Anticipos
      begin
        if empleado > 0 then
        begin
          fechaanticipo.Date := Date;
          if tanyo2.ItemIndex > 0 then anyo := tanyo2.Text else anyo := '%';
          if tmes2.ItemIndex > 0 then mes := IntToStr(tmes2.ItemIndex) else mes := '%';

          qanticipos.Close;
          qanticipos.ParamByName('EMPLEADO').AsInteger := empleado;
          qanticipos.ParamByName('EMPRESA').AsInteger := empresa;
          qanticipos.ParamByName('ANYO').AsString := anyo;
          qanticipos.ParamByName('MES').AsString := mes;
          qanticipos.Open;
        end
        else
        begin
          qempleados.Close;
          qanticipos.Close;
        end;
      end;

    5: // Listado de planificación
      begin
        if empresa > 0 then
        begin
          qlistadoplanificacion.Close;
          qlistadoplanificacion.ParamByName('EMPRESA').AsInteger := empresa;
          qlistadoplanificacion.Open;
        end
        else
          qlistadoplanificacion.Close;
      end;
  end;
end;

procedure Tfempleados.dsqlistaempleadosDataChange(Sender: TObject;
  Field: TField);
begin
  if Field <> nil then
    Exit;
  CargarDatosEmpleadoActual(PageEmpleados.ActivePageIndex);
end;

procedure Tfempleados.dsqregimencotizacionDataChange(Sender: TObject;
  Field: TField);
begin
    if qempleados.State in [dsedit,dsinsert] then
    begin
      qempleadosirpf.Value:=qregimencotizacionirpf.AsFloat;
      qempleadosdesempleo.Value:=qregimencotizaciondesempleo.AsFloat;
      qempleadosformacion.Value:=qregimencotizacionformacion.AsFloat;
      qempleadoscontingencias.Value:=qregimencotizacioncontingencias.AsFloat;
    end;
end;

procedure Tfempleados.FormClose(Sender: TObject; var Action: TCloseAction);
begin
   borrarficheros('c:\agrigest\tmp\');
end;

procedure Tfempleados.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if (Key = VK_RETURN) and ((ActiveControl = tbuscar) or ((ActiveControl <> nil) and SameText(ActiveControl.Name, 'tbuscar'))) then
  begin
    Key := 0;
    FiltrarListaEmpleados;
    Exit;
  end;

  if (activecontrol is tdbgrid) then
  begin
    if Key = 13 then Key := 9;
  end;
end;

procedure Tfempleados.FormKeyPress(Sender: TObject; var Key: Char);
var
  formatos: TFormatSettings;
  punto: string;
begin
  if (Key = #13) and ((ActiveControl = tbuscar) or ((ActiveControl <> nil) and SameText(ActiveControl.Name, 'tbuscar'))) then
  begin
    Key := #0;
    FiltrarListaEmpleados;
    Exit;
  end;

  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 tedit) then
    begin
      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 (activecontrol is tdatetimepicker) then
  begin
    if Key = #13 then Key := #9;
  end;
  if (activecontrol is tdbcheckbox) then
  begin
    if Key = #13 then Key := #9;
  end;

  if (key = #13) then
  begin
    Perform(WM_NextDLGCtl, 0, 0);
    key := #0;
  end;
end;


procedure Tfempleados.FormShow(Sender: TObject);
var
  LListaEmpleados: string;
  vanyo, vmes, vdia: Word;
begin
    dm.tempresa.Open;
    pageempleados.ActivePageIndex := 0;
    qgrupos.Open;
    qgrupos2.Open;
    qregimencotizacion.Open;
    qtipohora.Open;
    qconvocatorias.Open;
    listagrupos2.KeyValue := 0;
    ConfigurarCamposFechaPlanificacion;

    DecodeDate(Date(), vanyo, vmes, vdia);
    if tanyo.Items.Count > (vanyo - 2014) then
      tanyo.ItemIndex := vanyo - 2014;
    tmes.ItemIndex := vmes;
    if tanyo2.Items.Count > (vanyo - 2014) then
      tanyo2.ItemIndex := vanyo - 2014;
    tmes2.ItemIndex := vmes;

    CargarFiltroSexo;
    FiltrarListaEmpleados;
    seleccionando := 0;

    if dm.ObtenerTrabajadoresFinContratoProximo(LListaEmpleados) then
    begin
      ShowMessage('Atención: Los siguientes trabajadores activos tienen vencimiento de contrato en los próximos 15 días:' + 
                  sLineBreak + sLineBreak + LListaEmpleados);
    end;
end;

procedure Tfempleados.Image2DblClick(Sender: TObject);
var nomarchivo:string;
begin
    if (qemp_fotos.Active) and (qemp_fotos.RecordCount > 0) and (not qemp_fotosimagen.IsNull) then
    begin

      if not DirectoryExists('c:\agrigest\tmp') then CreateDir('c:\agrigest\tmp');
      nomarchivo:='empimg'+qemp_fotosextension.AsString;
      qemp_fotosimagen.SaveToFile('c:\agrigest\tmp\'+nomarchivo);
      ShellExecute(Handle,nil,PChar('c:\agrigest\tmp\'+nomarchivo),'','',SW_SHOWNORMAL);
    end;
end;

procedure Tfempleados.listaconvocatoriasDblClick(Sender: TObject);
begin
    if qempleados.State in [dsedit,dsinsert] then
    begin
        qempleadosconvocatoria.Value:=qconvocatoriasconvocatoria.AsString;
        listaconvocatorias.Visible:=false;
    end;
end;

procedure Tfempleados.listaconvocatoriasExit(Sender: TObject);
begin
  listaconvocatorias.Visible:=false;
end;

procedure Tfempleados.listagrupos2CloseUp(Sender: TObject);
begin
  vtactivo := qgrupos2id.AsInteger;
  FiltrarListaEmpleados;
end;

procedure Tfempleados.ltipohoraCloseUp(Sender: TObject);
begin
    lprecio.Text:=qtipohoraprecio.AsString;
end;

procedure Tfempleados.PageEmpleadosChange(Sender: TObject);
begin
    CargarDatosEmpleadoActual(PageEmpleados.ActivePageIndex);
end;

procedure Tfempleados.qempleadosAfterInsert(DataSet: TDataSet);
begin
    qid.close;
    qid.ParamByName('EMPRESA').AsInteger:=dm.tempresaid.AsInteger;
    qid.open;
    if qidid.asstring='' then qempleadosid.value:=1 else qempleadosid.Value:=qidid.asinteger;
    qempleadosempresa.Value:=dm.tempresaid.AsInteger;
end;

procedure Tfempleados.qempleadosAfterPost(DataSet: TDataSet);
begin
  qlistaempleados.Refresh;
  qlistaempleados.Locate('ide;id',vararrayof([pide,pidt]),[locaseinsensitive]);
end;

procedure Tfempleados.qempleadosBeforeDelete(DataSet: TDataSet);
begin
   case dm.PedirConfirmacion('¿Confirma que desea borrar este empleado?',true,true,false) of
        mrno:Abort;
   end;
end;

procedure Tfempleados.qempleadosBeforePost(DataSet: TDataSet);
var x:integer;
begin
    if qempleadosfechabaja.AsString='' then qempleadosactivo.Value:=1 else qempleadosactivo.value:=0;
    if qempleados.state=dsinsert then x:=dm.PedirConfirmacion('¿Confirma que desea dar de alta este empleado?',true,true,true)
                                     else x:=dm.PedirConfirmacion('¿Confirma que desea modificar este empleado?',true,true,true);
    case x of
        mrno: begin
                 qempleados.cancel;
                 abort;
              end;
        mrcancel:BEGIN
                 abort;
                 END;
    end;
    pidt:=qempleadosid.AsInteger;
    pide:=qempleadoside.AsInteger;
end;

procedure Tfempleados.qempleadosplanificacionfecha_carnetmanipuladorValidate(
  Sender: TField);
begin
end;

procedure Tfempleados.qempleadosplanificacionfecha_recmedicoValidate(
  Sender: TField);
begin
end;

procedure Tfempleados.qempleadosplanificacionfecha_ren_recmedicoValidate(
  Sender: TField);
begin
end;

procedure Tfempleados.qempleadosplanificacionfecha_testcovid19Validate(
  Sender: TField);
begin
end;

procedure Tfempleados.qempleadosplanificacionvto_permisotrabajoValidate(
  Sender: TField);
begin
end;

procedure Tfempleados.qemp_historicoAfterPost(DataSet: TDataSet);
begin
    qemp_historico.Close;
    qemp_historico.Open;
    if (qemp_historicofecha_baja.AsString='') and (qemp_historicofecha_desconexion.AsString='') then
    begin
       qaltasbajas.Close;
       qaltasbajas.Prepare;
       qaltasbajas.ParamByName('MOSTRAR').AsInteger:=1;
       qaltasbajas.ParamByName('FECHA').AsString:='null';
       qaltasbajas.ParamByName('FECHAALTA').Asdate:=qemp_historicofecha_alta.AsDateTime;
       qaltasbajas.ParamByName('EMPRESA').Asinteger:=qemp_historicoide.asinteger;
       qaltasbajas.ParamByName('TRABAJADOR').Asinteger:=qemp_historicoidt.asinteger;
       qaltasbajas.ExecSQL;
{       qaux.SQL.clear;
       qaux.SQL.Add('update trabajadores set mostrar=1,fechabaja=null where empresa='+qemp_historicoide.asstring+' and id='+qemp_historicoidt.AsString);
       qaux.ExecSQL;       }
    end
    else
    begin
       qaltasbajas.Close;
       qaltasbajas.Prepare;
       qaltasbajas.ParamByName('MOSTRAR').AsInteger:=0;
       if qemp_historicofecha_desconexion.AsString<>'' then qaltasbajas.ParamByName('FECHA').AsDate:=qemp_historicofecha_desconexion.AsDateTime;
       if qemp_historicofecha_baja.AsString<>'' then qaltasbajas.ParamByName('FECHA').AsDate:=qemp_historicofecha_baja.AsDateTime;
       qaltasbajas.ParamByName('FECHAALTA').Asdate:=qemp_historicofecha_alta.AsDateTime;
       qaltasbajas.ParamByName('EMPRESA').Asinteger:=qemp_historicoide.asinteger;
       qaltasbajas.ParamByName('TRABAJADOR').Asinteger:=qemp_historicoidt.asinteger;
       qaltasbajas.ExecSQL;

{       qaux.SQL.clear;
       qaux.SQL.Add('update trabajadores set mostrar=0,fechabaja='+''''+ where empresa='+qemp_historicoide.asstring+' and id='+qemp_historicoidt.AsString);
       qaux.ExecSQL;}
    end;
    qempleados.Refresh;
end;

procedure Tfempleados.qemp_historicoBeforeDelete(DataSet: TDataSet);
begin
 {  case dm.PedirConfirmacion('�Confirma que desea borrar esta l�nea del historico del empleado?',true,true,false) of
        mrno:Abort;
   end; }
end;

procedure Tfempleados.qemp_historicoBeforePost(DataSet: TDataSet);
var x:integer;
begin
    if qemp_historico.State in [dsinsert,dsedit] then
    begin
      qemp_historicoide.Value:=fempleados.qempleadoside.AsInteger;
      qemp_historicoidt.Value:=fempleados.qempleadosid.AsInteger;
      if (qemp_historicofecha_baja.AsString<>'') and (qemp_historicofecha_desconexion.AsString='') then
      begin
         qemp_historicofecha_desconexion.Value:=qemp_historicofecha_baja.AsDateTime;
      end;
    end;
   { if qemp_historico.state=dsinsert then x:=dm.PedirConfirmacion('�Confirma que desea dar de alta esta l�nea en el hist�rico del empleado?',true,true,true)
                                     else x:=dm.PedirConfirmacion('�Confirma que desea modificar esta l�nea en el hist�rico del empleado?',true,true,true);
    case x of
        mrno: begin
                 qemp_historico.cancel;
                 abort;
              end;
        mrcancel:BEGIN
                 abort;
                 END;
    end;        }
end;

procedure Tfempleados.qlistaempleadosAfterOpen(DataSet: TDataSet);
begin
  ltotalgrupo.Caption := 'Total grupo: ' + IntToStr(qlistaempleados.RecordCount);
  if qlistaempleados.RecordCount = 0 then
    CargarDatosEmpleadoActual(PageEmpleados.ActivePageIndex);
end;

procedure Tfempleados.FiltrarListaEmpleados;
var
  filtro: string;
begin
  filtrotrabajadores := Trim(tbuscar.Text);
  filtro := ' where t.ide=ep.ide and t.id=ep.idt ';

  if filtrotrabajadores <> '' then
  begin
     filtro := filtro + ' and (t.nombre like ' + QuotedStr('%' + filtrotrabajadores + '%') +
                        ' or t.nif like ' + QuotedStr('%' + filtrotrabajadores + '%');
     if StrToIntDef(filtrotrabajadores, -1) > 0 then
       filtro := filtro + ' or t.id = ' + filtrotrabajadores;
     filtro := filtro + ') ';
  end;

  if vtactivo <> 0 then
  begin
     filtro := filtro + ' and t.grupo = ' + IntToStr(vtactivo) + ' ';
  end;

  if not chktodosempleados.Checked then
  begin
     filtro := filtro + ' and t.activo = 1 ';
  end;

  if (cbsexo <> nil) and (cbsexo.ItemIndex > 0) and not SameText(cbsexo.Text, 'cualquiera') then
  begin
     filtro := filtro + ' and t.sexo = ' + QuotedStr(cbsexo.Text) + ' ';
  end;

  qlistaempleados.Close;
  qlistaempleados.SQL.Clear;
  qlistaempleados.SQL.Add('select t.ide,t.id,t.nombre,ep.vto_permisotrabajo from trabajadores t,empleados_planificacion ep ' + filtro +' order by t.nombre');
  qlistaempleados.Open;
end;

procedure Tfempleados.qlistaempleadosBeforeOpen(DataSet: TDataSet);
begin
  // Filtrado gestionado directamente en FiltrarListaEmpleados
end;

procedure Tfempleados.TanyoChange(Sender: TObject);
var
  anyo, mes: string;
  empresa, empleado: Integer;
begin
  if (qlistaempleados.Active) and (qlistaempleados.RecordCount > 0) then
  begin
    empleado := qlistaempleadosid.AsInteger;
    empresa := qlistaempleadoside.AsInteger;
  end
  else
    Exit;

  if tanyo.ItemIndex > 0 then anyo := tanyo.Text else anyo := '%';
  if tmes.ItemIndex > 0 then mes := IntToStr(tmes.ItemIndex) else mes := '%';

  qjornales.Close;
  qjornales.Prepare;
  qjornales.ParamByName('EMPLEADO').AsInteger := empleado;
  qjornales.ParamByName('EMPRESA').AsInteger := empresa;
  qjornales.ParamByName('ANYO').AsString := anyo;
  qjornales.ParamByName('MES').AsString := mes;
  qjornales.Open;
end;

procedure Tfempleados.tanyo2Change(Sender: TObject);
var
  anyo, mes: string;
  empresa, empleado: Integer;
begin
  if (qlistaempleados.Active) and (qlistaempleados.RecordCount > 0) then
  begin
    empleado := qlistaempleadosid.AsInteger;
    empresa := qlistaempleadoside.AsInteger;
  end
  else
    Exit;

  if tanyo2.ItemIndex > 0 then anyo := tanyo2.Text else anyo := '%';
  if tmes2.ItemIndex > 0 then mes := IntToStr(tmes2.ItemIndex) else mes := '%';

  qanticipos.Close;
  qanticipos.Prepare;
  qanticipos.ParamByName('EMPLEADO').AsInteger := empleado;
  qanticipos.ParamByName('EMPRESA').AsInteger := empresa;
  qanticipos.ParamByName('ANYO').AsString := anyo;
  qanticipos.ParamByName('MES').AsString := mes;
  qanticipos.Open;
end;

procedure Tfempleados.tbuscarKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if Key = VK_RETURN then
  begin
    Key := 0;
    FiltrarListaEmpleados;
  end;
end;

procedure Tfempleados.tbuscarKeyPress(Sender: TObject; var Key: Char);
begin
  if Key = #13 then
  begin
    Key := #0;
    FiltrarListaEmpleados;
  end;
end;

procedure Tfempleados.tbuscarExit(Sender: TObject);
begin
  if Trim(tbuscar.Text) <> filtrotrabajadores then
    FiltrarListaEmpleados
  else
    qlistaempleados.First;
end;

procedure Tfempleados.TESTADOChange(Sender: TObject);
var idt,filtrojornales:string;
begin
    idt:=qempleadosid.asstring;
    filtrojornales:='where idt='+idt;
    if tanyo.ItemIndex<>0 then filtrojornales:=filtrojornales+' and year(fecha)='+tanyo.Text ;
    if tmes.itemindex<>0 then filtrojornales:=filtrojornales+' and month(fecha)='+inttostr(tmes.itemindex);
    filtrojornales:=filtrojornales+' order by id desc';
    qjornales.Close;
    qjornales.SQL.Clear;
    qjornales.SQL.Add('select * from trabajo_diario '+filtrojornales);
    qjornales.Open;
end;

procedure Tfempleados.Vaciar2Click(Sender: TObject);
begin
    dbedit7.Text:='';
end;

procedure Tfempleados.VaciarClick(Sender: TObject);
begin
    dbedit3.Text:='';
end;
procedure Tfempleados.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 TfEmpleados.btnEnviarDocClick(Sender: TObject);
var
  sRutaDoc, nomarchivo: string;
begin
  if documentos.IsEmpty then 
  begin
    MessageDlg('No hay ningun documento seleccionado.', mtWarning, [mbOK], 0);
    Exit;
  end;

  try
    qtemp_doc.Close;
    qtemp_doc.ParamByName('EMPRESA').AsInteger := documentoside.asinteger;
    qtemp_doc.ParamByName('ID').AsInteger := documentosid.asinteger;
    qtemp_doc.Open;

    if qtemp_doc.IsEmpty then Exit;

    nomarchivo := qtemp_docnomarchivo.AsString;
    sRutaDoc := 'c:\agrigest\tmp\' + nomarchivo;
    
    // Guardar fisicamente el archivo
    qtemp_docarchivo.SaveToFile(sRutaDoc);

    // Abrir diálogo de envío
    with TfEnviarDocumento.Create(Self) do
    try
      RutaPDF := sRutaDoc;
      // Pasar teléfono, email y asunto predeterminado (desde qempleados)
      InitData(qempleadosTELEFONO1.AsString, qempleadosemail.AsString, '', 
        'Documento ' + nomarchivo, 'Reporte');
      ShowModal;
    finally
      Free;
    end;
  finally
    qtemp_doc.Close;
  end;
end;
end.


