======================================== FICHERO: calibrescalidad.pas ======================================== unit calibrescalidad; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,Vcl.StdCtrls, Vcl.DBCtrls, Vcl.Mask, Vcl.ComCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, datos, ZAbstractDataset, ZDataset, Data.DB, ZAbstractRODataset, ZAbstractTable; type Tfcalibrescalidad = class(TForm) Panel13: TPanel; Panel17: TPanel; DBGrid3: TDBGrid; Panel7: TPanel; btAcancelar: TButton; btAmodificar: TButton; btAborrar: TButton; btAnuevo: TButton; btAguardar: TButton; qaux: TZQuery; qcalibrescalidad: TZQuery; dscalibres: TDataSource; qcalibrescalidadid: TIntegerField; qcalibrescalidaddescripcion: TWideStringField; qcalibrescalidadvalor: TWideStringField; procedure btAnuevoClick(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure btAmodificarClick(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); procedure dscalibresStateChange(Sender: TObject); private { Private declarations } public { Public declarations } end; var fcalibrescalidad: Tfcalibrescalidad; implementation {$R *.dfm} procedure Tfcalibrescalidad.btAborrarClick(Sender: TObject); begin qcalibrescalidad.Delete; end; procedure Tfcalibrescalidad.btAcancelarClick(Sender: TObject); begin qcalibrescalidad.Cancel; dbgrid3.ReadOnly:=true; end; procedure Tfcalibrescalidad.btAguardarClick(Sender: TObject); begin qcalibrescalidad.Post; dbgrid3.ReadOnly:=true; end; procedure Tfcalibrescalidad.btAmodificarClick(Sender: TObject); begin dbgrid3.ReadOnly:=false; qcalibrescalidad.Edit; end; procedure Tfcalibrescalidad.btAnuevoClick(Sender: TObject); begin dbgrid3.ReadOnly:=false; qaux.sql.clear; qaux.SQL.Add('select max(id)+1 from calibrescalidad'); qaux.Open; qcalibrescalidad.append; dbgrid3.setfocus; qcalibrescalidadid.Value:=qaux.Fields[0].AsInteger; end; procedure Tfcalibrescalidad.dscalibresStateChange(Sender: TObject); begin if qcalibrescalidad.State in [dsedit,dsinsert] then begin btanuevo.Enabled:=false; btamodificar.Enabled:=false; btaborrar.Enabled:=false; btacancelar.Enabled:=true; btaguardar.Enabled:=true; end else begin btanuevo.Enabled:=true; btamodificar.Enabled:=true; btaborrar.Enabled:=true; btacancelar.Enabled:=false; btaguardar.Enabled:=false; end; end; procedure Tfcalibrescalidad.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tfcalibrescalidad.FormKeyPress(Sender: TObject; var Key: Char); begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tfcalibrescalidad.FormShow(Sender: TObject); begin qcalibrescalidad.Close; qcalibrescalidad.Open; end; end. ======================================== FICHERO: CertificateManager.pas ======================================== unit CertificateManager; interface uses System.Classes; // No usamos System.Generics.Collections type TCertificateInfo = class public FriendlyName: string; Context: Pointer; end; TCertificateLoader = class public class function GetPersonalCertificates: TList; // <-- USA TList end; implementation uses System.SysUtils, Winapi.Windows, Wincrypt; class function TCertificateLoader.GetPersonalCertificates: TList; // <-- USA TList var hStore: HCERTSTORE; pContext: PCCERT_CONTEXT; CertInfo: TCertificateInfo; ResultList: TList; // <-- USA TList FriendlyName: array[0..255] of WideChar; cbData: DWORD; begin ResultList := TList.Create; // <-- USA TList hStore := CertOpenSystemStore(0, 'MY'); if hStore = nil then begin Exit(ResultList); end; try pContext := nil; repeat pContext := CertFindCertificateInStore(hStore, X509_ASN_ENCODING or PKCS_7_ASN_ENCODING, 0, CERT_FIND_ANY, nil, pContext); if pContext <> nil then begin cbData := 0; if CertGetCertificateContextProperty(pContext, CERT_KEY_PROV_INFO_PROP_ID, nil, cbData) and (cbData > 0) then begin CertInfo := TCertificateInfo.Create; if CertGetNameString(pContext, CERT_NAME_FRIENDLY_DISPLAY_TYPE, 0, nil, FriendlyName, SizeOf(FriendlyName)) > 1 then CertInfo.FriendlyName := String(FriendlyName) else if CertGetNameString(pContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, nil, FriendlyName, SizeOf(FriendlyName)) > 1 then CertInfo.FriendlyName := String(FriendlyName) else CertInfo.FriendlyName := 'Certificado sin nombre'; CertInfo.Context := CertDuplicateCertificateContext(pContext); ResultList.Add(CertInfo); end; end; until pContext = nil; finally CertCloseStore(hStore, 0); end; Result := ResultList; end; end. ======================================== FICHERO: cuentasbancarias.pas ======================================== unit cuentasbancarias; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.ExtCtrls; type Tfcuentas_bancarias = class(TForm) Panel7: TPanel; btAcancelar: TButton; btAmodificar: TButton; btAborrar: TButton; btAnuevo: TButton; btAguardar: TButton; Panel1: TPanel; Panel2: TPanel; DBGrid1: TDBGrid; Panel3: TPanel; Panel4: TPanel; DBGrid2: TDBGrid; dsqcuentasbancarias: TDataSource; qaux: TZQuery; qcuentas_bancarias: TZQuery; qcuentas_bancariaside: TIntegerField; qcuentas_bancariasid: TIntegerField; qcuentas_bancariasbanco: TWideStringField; qcuentas_bancariascciban: TWideStringField; qcuentas_bancariasccentidad: TWideStringField; qcuentas_bancariasccoficina: TWideStringField; qcuentas_bancariasccdc: TWideStringField; qcuentas_bancariascccc: TWideStringField; qempresas: TZReadOnlyQuery; qempresasid: TIntegerField; qempresascif: TWideStringField; qempresasnombre: TWideStringField; qempresasdireccion: TWideStringField; qempresascodpost: TWideStringField; qempresaspoblacion: TWideStringField; qempresasprovincia: TWideStringField; qempresasemail: TWideStringField; qempresastelefono1: TWideStringField; qempresastelefono2: TWideStringField; qempresascontacto: TWideStringField; qempresascontingenciacomfij: TFloatField; qempresassalariobasedia: TFloatField; qempresascontingenciasdia: TFloatField; qempresasirpf: TFloatField; qempresasdesempleo: TFloatField; qempresasformacion: TFloatField; qempresascontingencias: TFloatField; qempresasirpf2: TFloatField; qempresasdesempleo2: TFloatField; qempresasformacion2: TFloatField; qempresascontingencias2: TFloatField; qempresascc_iban: TWideStringField; qempresascc_entidad: TWideStringField; qempresascc_oficina: TWideStringField; qempresascc_dc: TWideStringField; qempresascc_cc: TWideStringField; qempresasajusteentrada: TIntegerField; qempresasajustesalida: TIntegerField; qempresasporcbloqueo: TIntegerField; qempresasactive: TIntegerField; qempresasult_envio: TIntegerField; qempresasregistro_sanitario: TWideStringField; qempresascoste_kg_gen: TFloatField; qempresasporc_segsocial: TFloatField; qempresasprecio_venta_desperdicios: TFloatField; qempresasvercodtrazabilidad: TIntegerField; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure btAnuevoClick(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure btAmodificarClick(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure qcuentas_bancariasBeforePost(DataSet: TDataSet); procedure dsqcuentasbancariasStateChange(Sender: TObject); private { Private declarations } public { Public declarations } end; var fcuentas_bancarias: Tfcuentas_bancarias; implementation {$R *.dfm} procedure Tfcuentas_bancarias.btAborrarClick(Sender: TObject); begin qcuentas_bancarias.Delete; end; procedure Tfcuentas_bancarias.btAcancelarClick(Sender: TObject); begin qcuentas_bancarias.cancel; end; procedure Tfcuentas_bancarias.btAguardarClick(Sender: TObject); begin qcuentas_bancariaside.Value:=qempresasid.asinteger; qcuentas_bancarias.post; end; procedure Tfcuentas_bancarias.btAmodificarClick(Sender: TObject); begin qcuentas_bancarias.edit end; procedure Tfcuentas_bancarias.btAnuevoClick(Sender: TObject); begin qaux.Close; qaux.sql.clear; qaux.SQL.Add('select max(id)+1 from cuentas_bancarias'); qaux.Open; qcuentas_bancarias.append; if qaux.Fields[0].AsInteger<0 then qcuentas_bancariasid.Value:=0 else qcuentas_bancariasid.Value:=qaux.Fields[0].AsInteger; dbgrid1.setfocus; end; procedure Tfcuentas_bancarias.dsqcuentasbancariasStateChange(Sender: TObject); begin if qcuentas_bancarias.State in [dsedit,dsinsert] then begin btanuevo.Enabled:=false; btamodificar.Enabled:=false; btaborrar.Enabled:=false; btacancelar.Enabled:=true; btaguardar.Enabled:=true; end else begin btanuevo.Enabled:=true; btamodificar.Enabled:=true; btaborrar.Enabled:=true; btacancelar.Enabled:=false; btaguardar.Enabled:=false; end; end; procedure Tfcuentas_bancarias.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tfcuentas_bancarias.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tfcuentas_bancarias.FormShow(Sender: TObject); begin qcuentas_bancarias.Open; qempresas.open; end; procedure Tfcuentas_bancarias.qcuentas_bancariasBeforePost(DataSet: TDataSet); begin qcuentas_bancariaside.Value:=qempresasid.AsInteger; end; end. ======================================== FICHERO: datos.pas ======================================== unit datos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Menus, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, Vcl.Tabs, Vcl.ComCtrls, Vcl.Mask, Vcl.DBCtrls, ZAbstractConnection, ZConnection, ZAbstractTable, Vcl.ExtDlgs, Vcl.Imaging.jpeg, frxClass, frxDBSet, frxExportPDF, frxBarcode, Vcl.Buttons; type TDM = class(TDataModule) DBagrigest: TZConnection; dsqnominasdetalle: TDataSource; qnominasdetalle: TZReadOnlyQuery; qnominasdetalleid: TIntegerField; qnominasdetallefecha: TDateField; qnominasdetalleparcela: TWideStringField; qnominasdetalleidt: TIntegerField; qnominasdetalletrabajador: TWideStringField; qnominasdetalletypework: TWideStringField; qnominasdetallearticulo: TWideStringField; qnominasdetalleqhoras: TFloatField; qnominasdetalleprecio: TFloatField; qnominasdetalletotal: TFloatField; qnominasdetalleestado: TWideStringField; qnominasdetalleorigen: TWideStringField; dsqanticiposdetalle: TDataSource; qanticiposdetalle: TZReadOnlyQuery; qanticiposdetalleid: TIntegerField; qanticiposdetallefecha: TDateField; qanticiposdetalleimporte: TFloatField; qanticiposdetalleestado: TWideStringField; qanticiposdetalletrabajador: TWideStringField; qanticiposdetalleidt: TIntegerField; tnotas: TZTable; tcalendario_laboral: TZTable; dscalendario: TDataSource; dsnotas: TDataSource; qaux1: TZReadOnlyQuery; tempresa: TZTable; tcentro_coste: TZTable; dsempresa: TDataSource; tempresaid: TIntegerField; tempresacif: TWideStringField; tempresanombre: TWideStringField; tempresadireccion: TWideStringField; tempresacodpost: TWideStringField; tempresapoblacion: TWideStringField; tempresaprovincia: TWideStringField; tempresaemail: TWideStringField; tempresatelefono1: TWideStringField; tempresatelefono2: TWideStringField; tempresacontacto: TWideStringField; tempresacontingenciacomfij: TFloatField; tempresasalariobasedia: TFloatField; tempresacontingenciasdia: TFloatField; tempresairpf: TFloatField; tempresadesempleo: TFloatField; tempresaformacion: TFloatField; tempresacontingencias: TFloatField; tempresacc_iban: TWideStringField; tempresacc_entidad: TWideStringField; tempresacc_oficina: TWideStringField; tempresacc_dc: TWideStringField; tempresacc_cc: TWideStringField; tempresaactive: TIntegerField; tprenominas: TZTable; tprenominasId: TIntegerField; tprenominasIDT: TIntegerField; tprenominasANYO: TIntegerField; tprenominasMES: TWideStringField; tprenominasNIF: TWideStringField; tprenominasNOMBRE: TWideStringField; tprenominasDIRECCION: TWideStringField; tprenominasCP: TWideStringField; tprenominasPOBLACION: TWideStringField; tprenominasHORAS: TFloatField; tprenominasFECHAALTA: TDateField; tprenominasDIASTRABAJADOS: TIntegerField; tprenominasDIASMAXIMO: TIntegerField; tprenominasDIASCALCULO: TIntegerField; tprenominasTOTALBRUTO: TFloatField; tprenominasIRPF: TFloatField; tprenominasTOTALIRPF: TFloatField; tprenominasDESEMPLEO: TFloatField; tprenominasTOTALDESEMPLEO: TFloatField; tprenominasFORMACION: TFloatField; tprenominasTOTALFORMACION: TFloatField; tprenominasCONTINGENCIAS: TFloatField; tprenominasTOTALCONTINGENCIAS: TFloatField; tprenominasTOTALNETO: TFloatField; tprenominasANTICIPOS: TFloatField; tprenominasTOTALAPAGAR: TFloatField; tprenominasCUENTAPAGO: TWideStringField; tprenominasFECHAPAGO: TDateField; tprenominasESTADO: TWideStringField; tprenominasSALARIOBASE: TFloatField; tprenominasDIASLABORABLES: TIntegerField; tprenominasCORRECTO: TIntegerField; dsprenominas: TDataSource; qaux2: TZReadOnlyQuery; qaux3: TZReadOnlyQuery; ttrabajadores: TZTable; tprenominasFECHABAJA: TDateField; tproductos: TZTable; tproductoscodigo: TWideStringField; tproductosdescripcion: TWideStringField; tproductosimagen: TBlobField; tproductosalto: TIntegerField; tproductosancho: TIntegerField; tproductoslargo: TIntegerField; tproductostara: TFloatField; tproductospeso: TFloatField; tproductoserrorpeso: TFloatField; tproductospesadomanual: TIntegerField; tproductoscoste: TFloatField; tproductosactivo: TIntegerField; qproductos: TZReadOnlyQuery; dsqproductos: TDataSource; qproductoscodigo: TWideStringField; qproductosdescripcion: TWideStringField; qproductosimagen: TBlobField; qproductosalto: TIntegerField; qproductosancho: TIntegerField; qproductoslargo: TIntegerField; qproductostara: TFloatField; qproductospeso: TFloatField; qproductoserrorpeso: TFloatField; qproductospesadomanual: TIntegerField; qproductoscoste: TFloatField; qproductosactivo: TIntegerField; dsproductos: TDataSource; qproductosEANUPC: TLargeintField; tproductosEANUPC: TLargeintField; qmateriasprimas: TZReadOnlyQuery; dsqmateriasprimas: TDataSource; dsmateriasprimas: TDataSource; tmateriasprimas: TZTable; qmateriasprimasid: TWideStringField; qmateriasprimasdescripcion: TWideStringField; qmateriasprimasobservaciones: TWideStringField; qmateriasprimasimagen: TBlobField; qmateriasprimasEAN: TWideStringField; qmateriasprimasactivo: TIntegerField; tmateriasprimasid: TWideStringField; tmateriasprimasdescripcion: TWideStringField; tmateriasprimasobservaciones: TWideStringField; tmateriasprimasimagen: TBlobField; tmateriasprimasEAN: TWideStringField; tmateriasprimasactivo: TIntegerField; qtipohoras: TZReadOnlyQuery; dsqtipohoras: TDataSource; dstipohoras: TDataSource; ttipohoras: TZTable; ttipohorascodart: TWideStringField; ttipohorasdescrip: TWideStringField; ttipohorasprecio: TFloatField; ttipohorasactivo: TIntegerField; ttipohorasempresa: TIntegerField; ttipohorasfacturar: TIntegerField; qtipohorascodart: TWideStringField; qtipohorasdescrip: TWideStringField; qtipohorasprecio: TFloatField; qtipohorasactivo: TIntegerField; qtipohorasempresa: TIntegerField; qtipohorasfacturar: TIntegerField; qinftrabajadores: TZReadOnlyQuery; dsqinftrabajadores: TDataSource; qinftrabajadoresID: TSmallintField; qinftrabajadoresNIF: TWideStringField; qinftrabajadoresnombre: TWideStringField; qinftrabajadoresactivo: TIntegerField; 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; qinftrabajadoresTELEFONO4: TWideStringField; qinftrabajadoresREGIMEN_COT: TWideStringField; qinftrabajadoresNUMSEGSOCIAL: TWideStringField; qinftrabajadoresIRPF: TFloatField; qinftrabajadoresDESEMPLEO: TFloatField; qinftrabajadoresFORMACION: TFloatField; qinftrabajadoresOBSERVACIONES: TWideStringField; qinftrabajadoresFECHAALTA: TDateField; qinftrabajadoresFECHABAJA: TDateField; qinftrabajadoresFIJO: TSmallintField; qinftrabajadoresFIJODISCONTINUO: TSmallintField; qinftrabajadoresTEMPORAL: TSmallintField; qinftrabajadoresCONTINGENCIAS: TFloatField; qinftrabajadoresempresa: TIntegerField; qinfjornales: TZReadOnlyQuery; qinfjornalesid: TIntegerField; qinfjornalesfecha: TDateField; qinfjornalesparcela: TWideStringField; qinfjornalesidt: TIntegerField; qinfjornalestrabajador: TWideStringField; qinfjornalestypework: TWideStringField; qinfjornalesarticulo: TWideStringField; qinfjornalesqhoras: TFloatField; qinfjornalesestado: TWideStringField; qinfjornalesprecio: TFloatField; qinfjornalestotal: TFloatField; qinfjornalesorigen: TWideStringField; dsqinfjornales: TDataSource; dsqinfnominasdetalle: TDataSource; qinfnominasdetalle: TZReadOnlyQuery; IntegerField1: TIntegerField; DateField1: TDateField; WideStringField1: TWideStringField; IntegerField2: TIntegerField; WideStringField2: TWideStringField; WideStringField3: TWideStringField; WideStringField4: TWideStringField; FloatField1: TFloatField; FloatField2: TFloatField; FloatField3: TFloatField; WideStringField5: TWideStringField; WideStringField6: TWideStringField; dsqtrabajo: TDataSource; dsqparcela: TDataSource; qtrabajos: TZReadOnlyQuery; qtrabajosid: TWideStringField; qtrabajosnombre: TWideStringField; qtrabajosactivo: TIntegerField; qtrabajosempresa: TIntegerField; dstipotrabajo: TDataSource; ttipotrabajo: TZTable; ttipotrabajoid: TWideStringField; ttipotrabajonombre: TWideStringField; ttipotrabajoactivo: TIntegerField; ttipotrabajoempresa: TIntegerField; dsqtrabajosalmacen: TDataSource; qtrabajosalmacen: TZReadOnlyQuery; dstrabajosalmacen: TDataSource; ttrabajosalmacen: TZTable; ttrabajosalmacenid: TIntegerField; ttrabajosalmacenpuesto: TWideStringField; ttrabajosalmacentipo_trabajo: TWideStringField; ttrabajosalmacenarticulo: TWideStringField; ttrabajosalmacenparcela: TWideStringField; ttrabajosalmacenactivo: TIntegerField; qtrabajosalmacenid: TIntegerField; qtrabajosalmacenpuesto: TWideStringField; qtrabajosalmacentipo_trabajo: TWideStringField; qtrabajosalmacenarticulo: TWideStringField; qtrabajosalmacenparcela: TWideStringField; qtrabajosalmacenactivo: TIntegerField; dsqmovimientomesas: TDataSource; qmesas: TZReadOnlyQuery; qmesasmesa: TWideStringField; qproduccion: TZReadOnlyQuery; dsqproduccion: TDataSource; qproduccionmesa: TZReadOnlyQuery; dsqproduccionmesa: TDataSource; ttrabajadoresID: TSmallintField; ttrabajadoresNIF: TWideStringField; ttrabajadoresnombre: TWideStringField; ttrabajadoresactivo: TIntegerField; ttrabajadoresNOMBRECORTO: TWideStringField; ttrabajadoresAPELLIDOS: TWideStringField; ttrabajadoresDIRECCION: TWideStringField; ttrabajadoresCP: TWideStringField; ttrabajadoresPOBLACION: TWideStringField; ttrabajadoresPROVINCIA: TWideStringField; ttrabajadoresFECHANACIMIENTO: TDateField; ttrabajadoresPAISNAC: TWideStringField; ttrabajadoresNACIONALIDAD: TWideStringField; ttrabajadoresSEXO: TWideStringField; ttrabajadoresCBIBAN: TWideStringField; ttrabajadoresCBBANCO: TWideStringField; ttrabajadoresCBOFICINA: TWideStringField; ttrabajadoresCBDC: TWideStringField; ttrabajadoresCBCC: TWideStringField; ttrabajadoresPAGARPORBANCO: TIntegerField; ttrabajadoresTELEFONO1: TWideStringField; ttrabajadoresTELEFONO2: TWideStringField; ttrabajadoresTELEFONO3: TWideStringField; ttrabajadoresTELEFONO4: TWideStringField; ttrabajadoresREGIMEN_COT: TWideStringField; ttrabajadoresNUMSEGSOCIAL: TWideStringField; ttrabajadoresIRPF: TFloatField; ttrabajadoresDESEMPLEO: TFloatField; ttrabajadoresFORMACION: TFloatField; ttrabajadoresOBSERVACIONES: TWideStringField; ttrabajadoresFECHAALTA: TDateField; ttrabajadoresFECHABAJA: TDateField; ttrabajadoresCONTINGENCIAS: TFloatField; ttrabajadoresempresa: TIntegerField; dsqproduccionembasadora: TDataSource; qproduccionembasadora: TZReadOnlyQuery; WideStringField7: TWideStringField; WideStringField8: TWideStringField; LargeintField1: TLargeintField; WideStringField9: TWideStringField; FloatField4: TFloatField; IntegerField3: TIntegerField; WideStringField10: TWideStringField; dsqproduccionmesa2: TDataSource; qproduccionmesa2: TZReadOnlyQuery; dsqproduccionhora: TDataSource; qproduccionhora: TZReadOnlyQuery; dsqnominasproduccion: TDataSource; qnominasproduccion: TZQuery; qmovimientomesas: TZQuery; qmovimientomesasid: TLargeintField; qmovimientomesasfecha: TDateField; qmovimientomesasmesa: TWideStringField; qmovimientomesasidt: TIntegerField; qmovimientomesasTRABAJADOR: TWideStringField; qmovimientomesasENTRADA_REAL: TTimeField; qmovimientomesasSALIDA_REAL: TTimeField; qmovimientomesasENTRADA_AJUSTADA: TTimeField; qmovimientomesasSALIDA_AJUSTADA: TTimeField; qmovimientomesasHORASREALES: TTimeField; qmovimientomesasHORASAJUSTADAS: TTimeField; qmovimientomesasPUESTO: TWideStringField; qmovimientomesasTIPOTRABAJO: TWideStringField; qmovimientomesasARTICULO: TWideStringField; qmovimientomesasPARCELA: TWideStringField; ttrabajosalmacenmesas: TWideStringField; tprenominasFECHAINICIO: TDateField; tprenominasFECHAFIN: TDateField; tnominasdetalle: TZTable; tcalendario_laboralfecha: TDateField; tcalendario_laboralfestivo: TIntegerField; tcalendario_laboralalmuerzo: TIntegerField; tcalendario_laboralmerienda: TIntegerField; qanticipos: TZReadOnlyQuery; qanticiposid: TIntegerField; qanticiposidt: TIntegerField; qanticiposfecha: TDateField; qanticiposimporte: TFloatField; qanticiposestado: TWideStringField; dsqanticipos: TDataSource; tanticipos: TZTable; tanticiposid: TIntegerField; tanticiposidt: TIntegerField; tanticipostrabajador: TWideStringField; tanticiposfecha: TDateField; tanticiposimporte: TFloatField; tanticiposestado: TWideStringField; dsanticipos: TDataSource; qanticiposobservaciones: TWideStringField; tanticiposobservaciones: TWideStringField; qparcelas: TZQuery; dscontrolproduccion: TDataSource; qcontrolproduccion: TZQuery; qcontrolproduccionid: TIntegerField; qcontrolproduccionfecha: TDateField; qcontrolproduccionmateria_prima: TWideStringField; qcontrolproduccionproducto: TWideStringField; qcontrolproduccioncantidad_teorica: TIntegerField; qcontrolproduccioncantidad_real: TIntegerField; qcontrolproduccionobservaciones: TWideStringField; qcampanyas: TZQuery; dsqcampanyas: TDataSource; qlincampanyas: TZQuery; dsqlincampanyas: TDataSource; qcampanyasid: TIntegerField; qcampanyasdescripcion: TWideStringField; qcampanyasfechainicio: TDateField; qcampanyasfechafin: TDateField; tempresaajusteentrada: TIntegerField; tempresaajustesalida: TIntegerField; tempresaporcbloqueo: TIntegerField; qtipohorasequivalenciahoras: TFloatField; ttipohorasequivalenciahoras: TFloatField; dsqtipohoras2: TDataSource; qtipohoras2: TZQuery; qtipohoras2codart: TWideStringField; qtipohoras2seleccionado: TIntegerField; dsqtrabajadores2: TDataSource; qtrabajadores2: TZQuery; qtrabajadores2id: TSmallintField; qtrabajadores2nombre: TWideStringField; qtrabajadores2seleccionado: TIntegerField; dsqlistadohoras: TDataSource; qlistadohoras: TZReadOnlyQuery; qlistadohorasidt: TIntegerField; qlistadohorastrabajador: TWideStringField; qlistadohorasarticulo: TWideStringField; qlistadohorashoras: TFloatField; qlistadohorashoras2: TFloatField; qlistadohorastotal: TFloatField; qlistadohorastotal2: TFloatField; qtipotrabajo2: TZQuery; qtipotrabajo2id: TWideStringField; qtipotrabajo2seleccionado: TIntegerField; dsqtipotrabajo2: TDataSource; qlistadotrabajos: TZReadOnlyQuery; qlistadotrabajosidt: TIntegerField; qlistadotrabajostrabajador: TWideStringField; qlistadotrabajostypework: TWideStringField; qlistadotrabajoshoras: TFloatField; qlistadotrabajostotal: TFloatField; tanticipospenalizacion: TFloatField; tanticiposindemnizacion: TFloatField; dsqlistadotrabajos: TDataSource; qanticipospenalizacion: TFloatField; qanticiposindemnizacion: TFloatField; tprenominasINDEMNIZACION: TFloatField; tprenominasPENALIZACION: TFloatField; tnominasdetalleId: TIntegerField; tnominasdetalleIDNOMINA: TIntegerField; tnominasdetalleIDEMPRESA: TIntegerField; tnominasdetalleIDT: TIntegerField; tnominasdetalleANYO: TIntegerField; tnominasdetalleMES: TWideStringField; tnominasdetalleNIF: TWideStringField; tnominasdetalleNOMBRE: TWideStringField; tnominasdetalleDIRECCION: TWideStringField; tnominasdetalleCP: TWideStringField; tnominasdetallePOBLACION: TWideStringField; tnominasdetalleHORAS: TFloatField; tnominasdetalleFECHAALTA: TDateField; tnominasdetalleFECHABAJA: TDateField; tnominasdetalleDIASTRABAJADOS: TIntegerField; tnominasdetalleDIASMAXIMO: TIntegerField; tnominasdetalleDIASCALCULO: TIntegerField; tnominasdetalleTOTALBRUTO: TFloatField; tnominasdetalleIRPF: TFloatField; tnominasdetalleTOTALIRPF: TFloatField; tnominasdetalleDESEMPLEO: TFloatField; tnominasdetalleTOTALDESEMPLEO: TFloatField; tnominasdetalleFORMACION: TFloatField; tnominasdetalleTOTALFORMACION: TFloatField; tnominasdetalleCONTINGENCIAS: TFloatField; tnominasdetalleTOTALCONTINGENCIAS: TFloatField; tnominasdetalleTOTALNETO: TFloatField; tnominasdetalleANTICIPOS: TFloatField; tnominasdetalleINDEMNIZACION: TFloatField; tnominasdetallePENALIZACION: TFloatField; tnominasdetalleTOTALAPAGAR: TFloatField; tnominasdetalleCUENTAPAGO: TWideStringField; tnominasdetalleFECHAPAGO: TDateField; tnominasdetalleESTADO: TWideStringField; tnominasdetalleSALARIOBASE: TFloatField; tnominasdetalleDIASLABORABLES: TIntegerField; tnominasdetalleFECHAINICIO: TDateField; tnominasdetalleFECHAFIN: TDateField; tnominasdetalleCORRECTO: TIntegerField; dstnominas: TDataSource; dstnominasdetalle: TDataSource; qnominas: TZQuery; qnominasID: TIntegerField; qnominasIDEMPRESA: TIntegerField; qnominasNOMEMPRESA: TWideStringField; qnominasFECHA: TDateField; qnominasFECHAINICIO: TDateField; qnominasFECHAFIN: TDateField; qnominasPERIODO: TIntegerField; qnominasNOMPERIODO: TWideStringField; qnominasANYO: TIntegerField; qnominasFORMAPAGO: TWideStringField; qnominasACTIVO: TIntegerField; tempresairpf2: TFloatField; tempresadesempleo2: TFloatField; tempresaformacion2: TFloatField; tempresacontingencias2: TFloatField; qnominasCANT_LINEAS: TIntegerField; qnominasIMPORTETOTAL: TFloatField; qtrabajadores3: TZQuery; dsqtrabajadores3: TDataSource; qtrabajadores3id: TSmallintField; qtrabajadores3nombre: TWideStringField; qtrabajadores3seleccionado: TIntegerField; qparcela2: TZQuery; dsqparcela2: TDataSource; qparcela3: TZQuery; dsqparcela3: TDataSource; qparcela3codpar: TWideStringField; qparcela3empresa: TIntegerField; qparcela3nombre: TWideStringField; qparcela3variedad: TWideStringField; qparcela3num_plantas: TIntegerField; qparcela3fecha_plantacion: TDateField; qparcela3marco_plantacion: TWideStringField; qparcela3gastosgenerales: TIntegerField; qparcela3ref_catastro: TWideStringField; qparcela3sigpac_prov: TIntegerField; qparcela3sigpac_muni: TIntegerField; qparcela3sigpac_agre: TIntegerField; qparcela3sigpac_zona: TIntegerField; qparcela3sigpac_poli: TIntegerField; qparcela3sigpac_pacr: TIntegerField; qparcela3x: TWideStringField; qparcela3y: TWideStringField; qparcela3datum: TWideStringField; qparcela3huso: TIntegerField; qparcela3propiedad: TWideStringField; qparcela3activo: TIntegerField; qparcela2codpar: TWideStringField; qparcela2empresa: TIntegerField; qparcela2nombre: TWideStringField; qparcela2variedad: TWideStringField; qparcela2num_plantas: TIntegerField; qparcela2fecha_plantacion: TDateField; qparcela2marco_plantacion: TWideStringField; qparcela2gastosgenerales: TIntegerField; qparcela2ref_catastro: TWideStringField; qparcela2sigpac_prov: TIntegerField; qparcela2sigpac_muni: TIntegerField; qparcela2sigpac_agre: TIntegerField; qparcela2sigpac_zona: TIntegerField; qparcela2sigpac_poli: TIntegerField; qparcela2sigpac_pacr: TIntegerField; qparcela2x: TWideStringField; qparcela2y: TWideStringField; qparcela2datum: TWideStringField; qparcela2huso: TIntegerField; qparcela2propiedad: TWideStringField; qparcela2activo: TIntegerField; qparcela2seleccionado: TIntegerField; TFirmas: TZTable; dsfirmas: TDataSource; TFirmasid: TIntegerField; TFirmaside: TIntegerField; TFirmasidt: TIntegerField; TFirmasfirma: TBlobField; dspartes_diarios: TDataSource; qpartes_diarios: TZQuery; qpartes_diariosid: TIntegerField; qpartes_diarioside: TIntegerField; qpartes_diariosidt: TIntegerField; qpartes_diariostrabajador: TWideStringField; qpartes_diariosfecha: TDateField; qpartes_diarioshoras: TFloatField; qpartes_diariosfirma: TIntegerField; qpartes_diariosvalidado: TIntegerField; qfirmas: TZReadOnlyQuery; qfirmasid: TIntegerField; qfirmaside: TIntegerField; qfirmasidt: TIntegerField; qfirmasfirma: TBlobField; dsqfirmas: TDataSource; tmateriasprimasbasculas: TIntegerField; tempresault_envio: TIntegerField; tempresaregistro_sanitario: TWideStringField; ttipotrabajoseleccionado: TIntegerField; ttipotrabajocoste_elavoracion_campo: TIntegerField; dsqalmacenes: TDataSource; qalmacenes: TZReadOnlyQuery; qalmacenesid: TIntegerField; qalmacenesidempresa: TIntegerField; qalmacenesnombre: TWideStringField; qalmacenescapacidad: TIntegerField; qalmacenesstock_kg: TFloatField; qalmacenesstock_cajas: TIntegerField; qalmacenesstock_palets: TIntegerField; qalmacenesfinal: TIntegerField; qalmacenesactivo: TIntegerField; qalmacenescoste_kg_dia: TFloatField; tempresacoste_kg_gen: TFloatField; dstalmacenes: TDataSource; talmacenes: TZTable; talmacenesid: TIntegerField; talmacenesidempresa: TIntegerField; talmacenesnombre: TWideStringField; talmacenescapacidad: TIntegerField; talmacenesstock_kg: TFloatField; talmacenesstock_cajas: TIntegerField; talmacenesstock_palets: TIntegerField; talmacenesfinal: TIntegerField; talmacenesactivo: TIntegerField; talmacenescoste_kg_dia: TFloatField; talmacenespreguntar_generador: TIntegerField; dstarticulosalmacen: TDataSource; tarticulosalmacen: TZTable; dsqarticulosalmacen: TDataSource; qarticulosalmacen: TZReadOnlyQuery; tarticulosalmacenid: TIntegerField; tarticulosalmacenide: TIntegerField; tarticulosalmacencodigo: TWideStringField; tarticulosalmacencod_logi: TIntegerField; tarticulosalmacendescripcion: TWideStringField; tarticulosalmacenlargo: TFloatField; tarticulosalmacenalto: TFloatField; tarticulosalmacenancho: TFloatField; tarticulosalmacentara: TFloatField; tarticulosalmacentipo: TWideStringField; tarticulosalmacenpalet: TIntegerField; tarticulosalmacenenvase_trabajo: TIntegerField; tarticulosalmacenenvase_venta: TIntegerField; tarticulosalmacenactivo: TIntegerField; tarticulosalmacencosto: TFloatField; tarticulosalmacenobservaciones: TWideStringField; tarticulosalmacenpeso_venta: TFloatField; talmacenesmermas: TIntegerField; tmateriasprimasvariedad: TWideStringField; ttipotrabajocoste_elavoracion_almacen: TIntegerField; tempresaporc_segsocial: TFloatField; talmacenesproduccion: TIntegerField; dsqtrabajadores: TDataSource; qempleados: TZReadOnlyQuery; qempleadosidt: TIntegerField; qempleadostrabajador: TWideStringField; qtrabajo_diario: TZQuery; qtrabajo_diarioid: TIntegerField; qtrabajo_diarioempresa: TIntegerField; qtrabajo_diariofecha: TDateField; qtrabajo_diarioparcela: TWideStringField; qtrabajo_diarioidt: TIntegerField; qtrabajo_diariotrabajador: TWideStringField; qtrabajo_diariotypework: TWideStringField; qtrabajo_diarioarticulo: TWideStringField; qtrabajo_diarioqhoras: TFloatField; qtrabajo_diarioprecio: TFloatField; qtrabajo_diariototal: TFloatField; qtrabajo_diarioestado: TWideStringField; qtrabajo_diarioorigen: TWideStringField; qtrabajo_diariofechainsmod: TDateTimeField; qtrabajo_diariousuario: TIntegerField; qtrabajo_diariocontrol: TIntegerField; qtrabajo_diariohoras_nomina: TFloatField; qtrabajo_diariohoras_acumuladas: TFloatField; qtrabajo_diarioidparte1: TIntegerField; qtrabajo_diarioidparte2: TIntegerField; qpartes_diariosfestivo: TIntegerField; qproduccionid: TIntegerField; qproduccionidempresa: TIntegerField; qproduccionfecha: TDateField; qproduccionmateria_prima: TWideStringField; qproduccionproducto: TWideStringField; qproduccionpesadas: TIntegerField; qproduccionneto: TFloatField; qproduccionpeso_teorico: TFloatField; qproduccionpeso_real: TFloatField; qproducciondiferencia: TFloatField; qproduccionerror: TFloatField; qnominasproduccionidt: TIntegerField; qnominasproduccionfecha: TDateField; qnominasproduccionid: TIntegerField; qnominasproducciontrabajador: TWideStringField; qnominasproducciontypework: TWideStringField; qnominasproduccionarticulo: TWideStringField; qnominasproduccionqhoras: TFloatField; qnominasproduccionestado: TWideStringField; qnominasproduccionorigen: TWideStringField; tarticulosalmacenfacturar_pesofijo: TIntegerField; tmateriasprimasusar_precio_parcela: TIntegerField; tmateriasprimasdesechos: TIntegerField; tempresaprecio_venta_desperdicios: TFloatField; ttipotrabajoelavoracion_produccion: TIntegerField; ttipotrabajoenvasado_produccion: TIntegerField; ttipotrabajologistica_produccion: TIntegerField; talmacenestipo_trabajo: TWideStringField; talmacenescamara: TIntegerField; talmacenesalmacen_asociado: TIntegerField; qalmacenesaux: TZReadOnlyQuery; IntegerField4: TIntegerField; IntegerField5: TIntegerField; WideStringField11: TWideStringField; IntegerField6: TIntegerField; FloatField5: TFloatField; IntegerField7: TIntegerField; IntegerField8: TIntegerField; IntegerField9: TIntegerField; IntegerField10: TIntegerField; FloatField6: TFloatField; dsqalmacenesaux: TDataSource; tmateriasprimasidempresa: TIntegerField; tmateriasprimascompuesto: TIntegerField; qmprimascompuestas: TZQuery; dsmprimascompuestas: TDataSource; qmprimascompuestasidempresa: TIntegerField; qmprimascompuestasidmp: TWideStringField; qmprimascompuestasidmpc: TWideStringField; qmprimascompuestasvariedad: TWideStringField; qmprimascompuestasdescripcion: TWideStringField; qmprimascompuestasporcentaje: TFloatField; ttipotrabajoalmacen_trabajo: TIntegerField; talmacenescentrocoste_asociado: TWideStringField; tproductosunidades_caja: TIntegerField; tproductosobservaciones: TWideMemoField; qproductosunidades_caja: TIntegerField; qproductosobservaciones: TWideMemoField; qpartes_diarios2: TZQuery; qpersonasmesas: TZQuery; dsqpersonasmesas: TDataSource; qpartes_diarios2id: TIntegerField; qpartes_diarios2ide: TIntegerField; qpartes_diarios2idt: TIntegerField; qpartes_diarios2trabajador: TWideStringField; qpartes_diarios2fecha: TDateField; qpartes_diarios2horas: TFloatField; qpartes_diarios2firma: TIntegerField; qpartes_diarios2validado: TIntegerField; qpartes_diarios2festivo: TIntegerField; qpersonasmesasidt: TIntegerField; qpersonasmesastrabajador: TWideStringField; qpersonasmesasmesa: TWideStringField; dsqpartesdiarios2: TDataSource; tarticulosalmacenpreguntar_gen: TIntegerField; qmateriasprimas2: TZReadOnlyQuery; dsqmateriasprimas2: TDataSource; qmateriasprimas2idempresa: TIntegerField; qmateriasprimas2id: TWideStringField; qmateriasprimas2variedad: TWideStringField; qmateriasprimas2descripcion: TWideStringField; qmateriasprimas2observaciones: TWideStringField; qmateriasprimas2imagen: TBlobField; qmateriasprimas2EAN: TWideStringField; qmateriasprimas2basculas: TIntegerField; qmateriasprimas2activo: TIntegerField; qmateriasprimas2usar_precio_parcela: TIntegerField; qmateriasprimas2desechos: TIntegerField; qmateriasprimas2compuesto: TIntegerField; qmateriasprimasidempresa: TIntegerField; qmateriasprimasvariedad: TWideStringField; qmateriasprimasbasculas: TIntegerField; qmateriasprimasusar_precio_parcela: TIntegerField; qmateriasprimasdesechos: TIntegerField; qmateriasprimascompuesto: TIntegerField; tmateriasprimasmesas: TIntegerField; dtarticulosalmacen: TZQuery; dtarticulosalmacenid: TIntegerField; dtarticulosalmacenide: TIntegerField; dtarticulosalmacencodigo: TWideStringField; dtarticulosalmacencod_logi: TIntegerField; dtarticulosalmacendescripcion: TWideStringField; dtarticulosalmacenlargo: TFloatField; dtarticulosalmacenalto: TFloatField; dtarticulosalmacenancho: TFloatField; dtarticulosalmacentara: TFloatField; dtarticulosalmacenpeso_venta: TFloatField; dtarticulosalmacentipo: TWideStringField; dtarticulosalmacenpalet: TIntegerField; dtarticulosalmacenenvase_trabajo: TIntegerField; dtarticulosalmacenenvase_venta: TIntegerField; dtarticulosalmacencosto: TFloatField; dtarticulosalmacenactivo: TIntegerField; dtarticulosalmacenobservaciones: TWideStringField; dtarticulosalmacenfacturar_pesofijo: TIntegerField; dtarticulosalmacenpreguntar_gen: TIntegerField; dtarticulos_componentes: TZQuery; dsarticuloscomponentes: TDataSource; dtarticulos_componentesidempresa: TIntegerField; dtarticulos_componentesidarticuloalmacen: TIntegerField; dtarticulos_componentesidarticulof: TIntegerField; dtarticulos_componentespreciocoste: TFloatField; dtarticulos_componentesdescripcion: TWideStringField; qfirmas2: TZQuery; qfirmas2id: TIntegerField; qfirmas2ide: TIntegerField; qfirmas2idt: TIntegerField; qfirmas2firma: TBlobField; tproductosmostrar_boton: TIntegerField; dtarticulosalmacenunidades_venta: TIntegerField; qseries: TZQuery; qserieside: TIntegerField; qseriesid: TWideStringField; qseriesfechainicio: TDateField; qseriesfechafin: TDateField; qseriesnum_pedcliente: TIntegerField; qseriesnum_albaran: TIntegerField; qseriesnum_factura: TIntegerField; qseriesnum_expedicion: TIntegerField; qseriesnum_pedproveedor: TIntegerField; dsqseries: TDataSource; dtarticulos_componentescoste: TFloatField; dtarticulos_componentescantidad: TFloatField; qaux: TZReadOnlyQuery; qlincampanyaside: TIntegerField; qlincampanyasidc: TIntegerField; qlincampanyasidp: TWideStringField; qlincampanyasmateria_prima: TWideStringField; qlincampanyaskgestimados: TFloatField; qlincampanyaskgproducidos: TFloatField; qlincampanyaskgenvasados: TFloatField; qlincampanyaskgfacturados: TFloatField; qcampanyasidempresa: TIntegerField; qcampanyasid_anterior: TIntegerField; qcampanyasult_pesada: TIntegerField; qcampanyas_aux: TZQuery; IntegerField11: TIntegerField; IntegerField12: TIntegerField; IntegerField13: TIntegerField; WideStringField12: TWideStringField; DateField2: TDateField; DateField3: TDateField; IntegerField14: TIntegerField; dsqcampanyaaux: TDataSource; qcampanyasparcela: TZQuery; qcampanyasparcelaide: TIntegerField; qcampanyasparcelaidc: TIntegerField; qcampanyasparcelaidp: TWideStringField; qcampanyasparcelaparcela: TWideStringField; dsqcampanyasparcela: TDataSource; qparcela2num_goteros: TFloatField; qparcela2superficie: TFloatField; qparcela2est_meteo: TWideStringField; qparcela2coste_kg_ref: TFloatField; qparcela2activo_almacen: TIntegerField; qparcela2porc_desperdicio: TFloatField; qparcela2porc_merma: TFloatField; qparcela2es_centrotrabajo: TIntegerField; qparcela2sigpac_recinto: TIntegerField; qparcela2pie_planta: TWideStringField; qparcela2numero: TWideStringField; qparcela2tiene_gg: TIntegerField; qparcela2tiene_dop: TIntegerField; qparcela2c_calidad: TIntegerField; qparcela2c_espcliente: TIntegerField; qparcela2c_etiquetado: TIntegerField; qparcela2sello_gg: TWideStringField; qparcela2sello_dop: TWideStringField; qparcela2sello_igp: TWideStringField; qparcela2tiene_igp: TIntegerField; qparcela2tiene_ifs: TIntegerField; qparcela2sello_ifs: TWideStringField; qparcela3num_goteros: TFloatField; qparcela3seleccionado: TIntegerField; qparcela3superficie: TFloatField; qparcela3est_meteo: TWideStringField; qparcela3coste_kg_ref: TFloatField; qparcela3activo_almacen: TIntegerField; qparcela3porc_desperdicio: TFloatField; qparcela3porc_merma: TFloatField; qparcela3es_centrotrabajo: TIntegerField; qparcela3sigpac_recinto: TIntegerField; qparcela3pie_planta: TWideStringField; qparcela3numero: TWideStringField; qparcela3tiene_gg: TIntegerField; qparcela3tiene_dop: TIntegerField; qparcela3c_calidad: TIntegerField; qparcela3c_espcliente: TIntegerField; qparcela3c_etiquetado: TIntegerField; qparcela3sello_gg: TWideStringField; qparcela3sello_dop: TWideStringField; qparcela3sello_igp: TWideStringField; qparcela3tiene_igp: TIntegerField; qparcela3tiene_ifs: TIntegerField; qparcela3sello_ifs: TWideStringField; tempresavercodtrazabilidad: TIntegerField; qgenericas: TZReadOnlyQuery; qgenericaside: TIntegerField; qgenericasid: TIntegerField; qgenericasdescripcion: TWideStringField; dsgenericas: TDataSource; qmateriasprimasmesas: TIntegerField; qmateriasprimasidgenerico: TIntegerField; qmateriasprimas2mesas: TIntegerField; qmateriasprimas2idgenerico: TIntegerField; tmateriasprimasidgenerico: TIntegerField; qanticiposdetalleindemnizacion: TFloatField; qanticiposdetallepenalizacion: TFloatField; qanticiposdetalleobservaciones: TWideStringField; qanticiposdetalleformapago: TWideStringField; qanticiposdetalleimporteletras: TWideStringField; tanticiposformapago: TWideStringField; tanticiposimporteletras: TWideStringField; qseriesimp_albaran: TWideStringField; qseriesimp_factura: TWideStringField; tarticulosalmacenunidades_venta: TIntegerField; tarticulosalmacendescripcion2: TWideStringField; dtarticulosalmacendescripcion2: TWideStringField; qarticulosalmacenid: TIntegerField; qarticulosalmacenide: TIntegerField; qarticulosalmacencodigo: TWideStringField; qarticulosalmacendescripcion: TWideStringField; qarticulosalmacenactivo: TIntegerField; ttrabajadoreside: TIntegerField; ttrabajadoresIRPF2: TFloatField; ttrabajadoresDESEMPLEO2: TFloatField; ttrabajadoresFORMACION2: TFloatField; ttrabajadoresIMAGEN: TIntegerField; ttrabajadoresseleccionado: TIntegerField; ttrabajadorescodart: TWideStringField; ttrabajadoresmostrar: TIntegerField; tproductosdeshidratacion: TFloatField; tproductostara_envase: TFloatField; dtarticulos_componentespeso: TFloatField; tprenominasBASEDIA: TFloatField; tempresacodcomision: TWideStringField; tempresacodtransporte: TWideStringField; qseriesactivo: TIntegerField; qseriesnum_presupuesto: TIntegerField; qseriesseriecontable: TWideStringField; tempresacc_bic: TWideStringField; tempresacodotros: TWideStringField; tempresaavisarstock: TIntegerField; tproductoside: TIntegerField; tproductosid: TIntegerField; tempresahtlunes: TFloatField; tempresahtmartes: TFloatField; tempresahtmiercoles: TFloatField; tempresahtjueves: TFloatField; tempresahtviernes: TFloatField; tempresahtsabados: TFloatField; tempresahtdomingos: TFloatField; tempresatavisostock: TIntegerField; tempresaresponsable: TWideStringField; tempresanif_responsable: TWideStringField; tempresalogo: TBlobField; tempresafirmaresponsable: TBlobField; qmateriasprimasgenerico: TWideStringField; qmateriasprimasobtentor: TWideStringField; tmateriasprimasgenerico: TWideStringField; tmateriasprimasobtentor: TWideStringField; tempresatiempoalmuerzo: TIntegerField; tempresahorasminimas: TIntegerField; tempresaidfamilia: TIntegerField; ttrabajadoresFIJO: TIntegerField; ttrabajadoresFIJODISCONTINUO: TIntegerField; ttrabajadoresTEMPORAL: TIntegerField; tempresaajuste15: TIntegerField; tempresaajuste30: TIntegerField; tempresaseparartraza_e_s: TIntegerField; qmateriasprimaspesopieza: TFloatField; qmateriasprimas2generico: TWideStringField; qmateriasprimas2obtentor: TWideStringField; qmateriasprimas2pesopieza: TFloatField; tmateriasprimaspesopieza: TFloatField; qproduccionmesafecha: TDateField; qproduccionmesamesa: TWideStringField; qproduccionmesabascula: TWideStringField; qproduccionmesamateria_prima: TWideStringField; qproduccionmesaproducto: TWideStringField; qproduccionmesapesadas: TLargeintField; qproduccionmesacantidad: TFloatField; qproduccionhoradesde: TIntegerField; qproduccionhorahasta: TIntegerField; qproduccionhoracantidad: TFloatField; tcalendario_laboralinicio_almuerzo: TTimeField; tcalendario_laboralfin_almuerzo: TTimeField; tcalendario_laboralinicio_merienda: TTimeField; tcalendario_laboralfin_merienda: TTimeField; tempresaean: TWideStringField; qparcelascodpar: TWideStringField; qparcelasempresa: TIntegerField; qparcelasnombre: TWideStringField; qparcelasvariedad: TWideStringField; qparcelasnum_plantas: TIntegerField; qparcelasfecha_plantacion: TDateField; qparcelasmarco_plantacion: TWideStringField; qparcelasnum_goteros: TFloatField; qparcelasgastosgenerales: TIntegerField; qparcelasref_catastro: TWideStringField; qparcelassigpac_prov: TIntegerField; qparcelassigpac_muni: TIntegerField; qparcelassigpac_agre: TIntegerField; qparcelassigpac_zona: TIntegerField; qparcelassigpac_poli: TIntegerField; qparcelassigpac_pacr: TIntegerField; qparcelasx: TWideStringField; qparcelasy: TWideStringField; qparcelasdatum: TWideStringField; qparcelashuso: TIntegerField; qparcelaspropiedad: TWideStringField; qparcelasactivo: TIntegerField; qparcelasseleccionado: TIntegerField; qparcelassuperficie: TFloatField; qparcelasest_meteo: TWideStringField; qparcelascoste_kg_ref: TFloatField; qparcelasactivo_almacen: TIntegerField; qparcelasporc_desperdicio: TFloatField; qparcelasporc_merma: TFloatField; qparcelases_centrotrabajo: TIntegerField; qparcelassigpac_recinto: TIntegerField; qparcelaspie_planta: TWideStringField; qparcelasnumero: TWideStringField; qparcelastiene_gg: TIntegerField; qparcelastiene_dop: TIntegerField; qparcelasc_calidad: TIntegerField; qparcelasc_espcliente: TIntegerField; qparcelasc_etiquetado: TIntegerField; qparcelassello_gg: TWideStringField; qparcelassello_dop: TWideStringField; qparcelassello_igp: TWideStringField; qparcelastiene_igp: TIntegerField; qparcelastiene_ifs: TIntegerField; qparcelassello_ifs: TWideStringField; qparcelaspropietario: TIntegerField; qparcelastiene_brc: TIntegerField; qparcelassello_brc: TWideStringField; qnominasdetalleobservaciones: TWideStringField; qnominasdetalleempresa: TIntegerField; qproduccionmesa2mesa: TWideStringField; qproduccionmesa2cantidad: TFloatField; qproduccionmesa2horasmesa: TFloatField; qproduccionmesa2cantidadhora: TFloatField; qparcelasancho_calle: TFloatField; procedure DataModuleCreate(Sender: TObject); procedure dsqproductosDataChange(Sender: TObject; Field: TField); procedure dsqmateriasprimasDataChange(Sender: TObject; Field: TField); procedure dsqtipohorasDataChange(Sender: TObject; Field: TField); procedure DataModuleDestroy(Sender: TObject); procedure nomlhhastaChange(Sender: TObject; Field: TField); procedure dsqtrabajosalmacenDataChange(Sender: TObject; Field: TField); procedure dscontrolproduccionStateChange(Sender: TObject); procedure dsqparcelaStateChange(Sender: TObject); procedure dsqcampanyasStateChange(Sender: TObject); procedure dsempresaStateChange(Sender: TObject); procedure dsqtipohoras2DataChange(Sender: TObject; Field: TField); procedure dsqtrabajadores2DataChange(Sender: TObject; Field: TField); procedure dsqlistadotrabajosDataChange(Sender: TObject; Field: TField); procedure dsqtipotrabajo2DataChange(Sender: TObject; Field: TField); procedure dsqtrabajadores3DataChange(Sender: TObject; Field: TField); procedure dsqparcela2DataChange(Sender: TObject; Field: TField); procedure dspartes_diariosDataChange(Sender: TObject; Field: TField); procedure dstalmacenesStateChange(Sender: TObject); procedure dstarticulosalmacenStateChange(Sender: TObject); procedure dsqpartesdiarios2DataChange(Sender: TObject; Field: TField); procedure qarticulosalmacenAfterOpen(DataSet: TDataSet); procedure qarticulosalmacenBeforeOpen(DataSet: TDataSet); procedure dsqseriesStateChange(Sender: TObject); procedure qparcelasBeforeOpen(DataSet: TDataSet); procedure dtarticulos_componentesAfterPost(DataSet: TDataSet); procedure dtarticulos_componentesBeforePost(DataSet: TDataSet); procedure tprenominasCalcFields(DataSet: TDataSet); procedure qseriesAfterPost(DataSet: TDataSet); procedure dsempresaDataChange(Sender: TObject; Field: TField); procedure dsqparcelaDataChange(Sender: TObject; Field: TField); private { Private declarations } public { Public declarations } var filtro:string; vertodos:integer; function PedirConfirmacion(mensaje:string; si,no,cancelar:boolean):integer; end; var DM: TDM; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} uses principal, fenvases_almacen, datosclientes, fconfirmar, datosestadisticas; {$R *.dfm} function tdm.PedirConfirmacion(mensaje:string; si,no,cancelar:boolean):integer; begin confirmar:=tconfirmar.create(nil); with confirmar do begin LMensaje.caption:=mensaje; bsi.visible:=si; bno.visible:=no; bcancelar.visible:=cancelar; end; result:=Confirmar.Showmodal; confirmar.free; end; procedure TDM.DataModuleCreate(Sender: TObject); var F: TextFile; sLinea,thost,tuser,tpass,tbd: String; hora1,hora2,hora3:ttime; configuracion:array of string; linea,x:integer; begin inherited; AssignFile( F, ExtractFilePath( Application.ExeName ) + 'config.ini' ); Reset( F ); linea:=1; setlength (configuracion,5); for x:=1 to 5 do begin ReadLn( F, sLinea ); configuracion[linea]:=sLinea; linea:=linea+1; end; CloseFile( F ); thost:=configuracion[1]; tuser:=configuracion[2]; tpass:=configuracion[3]; tlimitado:=configuracion[4]; tbd:=configuracion[5]; DM.DBagrigest.Database:=tbd; DM.DBagrigest.Connected:=false; DM.DBagrigest.HostName:=thost; DM.DBagrigest.User:=tuser; DM.DBagrigest.Password:=tpass; DM.DBagrigest.connected:=true; end; procedure TDM.DataModuleDestroy(Sender: TObject); begin inherited; ExitProcess(0); end; procedure TDM.dscontrolproduccionStateChange(Sender: TObject); begin inherited; if qcontrolproduccion.State in [dsedit] then begin base.btcontrolproduccion.visible:=true; base.btcontrolprodcerrar.Visible:=false; end; if qcontrolproduccion.State in [dsbrowse] then begin base.btcontrolproduccion.visible:=false; base.btcontrolprodcerrar.Visible:=true; end; end; procedure TDM.dsempresaDataChange(Sender: TObject; Field: TField); begin If not DirectoryExists('c:\agrigest\tmp') then CreateDir('c:\agrigest\tmp'); Deletefile('c:\agrigest\tmp\empimg.*');//+temp_fotosextension.AsString); base.imgfotoe.Picture:=nil; if tempresalogo.AsString<>'' then begin tempresalogo.savetofile('c:\agrigest\tmp\empimg.jpg'); base.imgfotoe.Picture.LoadFromFile('c:\agrigest\tmp\empimg.jpg'); Deletefile('c:\agrigest\tmp\empimg.jpg'); end; end; procedure TDM.dsempresaStateChange(Sender: TObject); begin inherited; if tempresa.State in [dsedit] then begin base.bemodificar.Click; end; end; procedure TDM.dspartes_diariosDataChange(Sender: TObject; Field: TField); begin inherited; base.tfirmanominas.Picture:=nil; qfirmas.Close; if (qpartes_diariosfirma.asinteger<>0) then begin qfirmas.SQL.Clear; qfirmas.SQL.Add('select * from firmas where id='+dm.qpartes_diariosfirma.Asstring+' and ide='+dm.qpartes_diarioside.asstring); qfirmas.open; qfirmasfirma.SaveToFile('c:\agrigest\informes\firma.bmp'); base.tfirmanominas.Picture.LoadFromFile('c:\agrigest\informes\firma.bmp'); end else base.tfirmanominas.Picture:=nil; end; procedure TDM.dsqcampanyasStateChange(Sender: TObject); begin inherited; if qcampanyas.State in [dsedit,dsinsert] then begin base.bcanadir.Enabled:=false; base.bcmodificar.Enabled:=false; base.bcborrar.Enabled:=false; base.bccancelar.Enabled:=true; base.bcaceptar.Enabled:=true; end else begin base.bcanadir.Enabled:=true; base.bcmodificar.Enabled:=true; base.bcborrar.Enabled:=true; base.bccancelar.Enabled:=false; base.bcaceptar.Enabled:=false; end; end; procedure TDM.dsqlistadotrabajosDataChange(Sender: TObject; Field: TField); begin inherited; if dm.qlistadotrabajos.State in [dsbrowse] then dm.qlistadotrabajos.Refresh; if dm.qtrabajadores2.State in [dsbrowse] then dm.qtrabajadores2.Refresh; end; procedure TDM.dsqmateriasprimasDataChange(Sender: TObject; Field: TField); begin inherited; tmateriasprimas.Locate('id',qmateriasprimasid.AsString,[locaseinsensitive]) end; procedure TDM.dsqparcela2DataChange(Sender: TObject; Field: TField); begin inherited; // if dm.qlistadohoras.State in [dsbrowse] then dm.qlistadohoras.Refresh; if dm.qtipohoras2.State in [dsbrowse] then dm.qtipohoras2.Refresh; if dm.qtrabajadores2.State in [dsbrowse] then dm.qtrabajadores2.Refresh; end; procedure TDM.dsqparcelaDataChange(Sender: TObject; Field: TField); begin dmestadisticas.qcampanyas.open; dmestadisticas.qcampanyas.First; end; procedure TDM.dsqparcelaStateChange(Sender: TObject); begin inherited; if qparcelas.State in [dsedit,dsinsert] then begin base.bccanadir.Enabled:=false; base.bccmodificar.Enabled:=false; base.bccborrar.Enabled:=false; base.bcccancelar.Enabled:=true; base.bccaceptar.Enabled:=true; end else begin base.bccanadir.Enabled:=true; base.bccmodificar.Enabled:=true; base.bccborrar.Enabled:=true; base.bcccancelar.Enabled:=false; base.bccaceptar.Enabled:=false; end; end; procedure TDM.dsqpartesdiarios2DataChange(Sender: TObject; Field: TField); begin base.tfirmaproduccion.Picture:=nil; qfirmas.Close; if (qpartes_diarios2firma.asinteger<>0) then begin qfirmas.SQL.Clear; qfirmas.SQL.Add('select * from firmas where id='+dm.qpartes_diarios2firma.Asstring+' and ide='+dm.qpartes_diarios2ide.asstring); qfirmas.open; qfirmasfirma.SaveToFile('c:\agrigest\informes\firma.bmp'); base.tfirmaproduccion.Picture.LoadFromFile('c:\agrigest\informes\firma.bmp'); end else end; procedure TDM.dsqproductosDataChange(Sender: TObject; Field: TField); begin inherited; tproductos.Locate('codigo',qproductoscodigo.AsString,[locaseinsensitive]) end; procedure TDM.dsqseriesStateChange(Sender: TObject); begin if dm.qseries.State in [dsedit,dsinsert] then begin base.btsnnuevo.enabled:=false; base.btsnborrar.enabled:=false; base.btsnmodificar.enabled:=false; base.btsnguardar.enabled:=true; base.btsncancelar.enabled:=true; end; if dm.qseries.State in [dsbrowse] then begin base.btsnnuevo.enabled:=true; base.btsnborrar.enabled:=true; base.btsnmodificar.enabled:=true; base.btsnguardar.enabled:=false; base.btsncancelar.enabled:=false; end; end; procedure TDM.dsqtipohoras2DataChange(Sender: TObject; Field: TField); begin inherited; if dm.qlistadohoras.State in [dsbrowse] then dm.qlistadohoras.Refresh; if dm.qtrabajadores2.State in [dsbrowse] then dm.qtrabajadores2.Refresh; end; procedure TDM.dsqtipohorasDataChange(Sender: TObject; Field: TField); begin inherited; ttipohoras.Locate('codart',qtipohorascodart.AsString,[locaseinsensitive]) end; procedure TDM.dsqtipotrabajo2DataChange(Sender: TObject; Field: TField); begin inherited; if dm.qlistadotrabajos.State in [dsbrowse] then dm.qlistadotrabajos.Refresh; if dm.qtrabajadores3.State in [dsbrowse] then dm.qtrabajadores3.Refresh; end; procedure TDM.nomlhhastaChange(Sender: TObject; Field: TField); begin inherited; ttipotrabajo.locate('id',qtrabajosid.AsString,[locaseinsensitive]); end; procedure TDM.dsqtrabajadores2DataChange(Sender: TObject; Field: TField); begin inherited; if dm.qlistadohoras.State in [dsbrowse] then dm.qlistadohoras.Refresh; end; procedure TDM.dsqtrabajadores3DataChange(Sender: TObject; Field: TField); begin inherited; if dm.qlistadotrabajos.State in [dsbrowse] then dm.qlistadotrabajos.Refresh; end; procedure TDM.dsqtrabajosalmacenDataChange(Sender: TObject; Field: TField); begin inherited; ttrabajosalmacen.locate('id',qtrabajosalmacenid.AsString,[locaseinsensitive]); qtipohoras.locate('codart',qtrabajosalmacenarticulo.AsString,[locaseinsensitive]); qparcelas.locate('codpar',qtrabajosalmacenparcela.AsString,[locaseinsensitive]); qtrabajos.locate('id',qtrabajosalmacentipo_trabajo.AsString,[locaseinsensitive]); end; procedure TDM.dstalmacenesStateChange(Sender: TObject); begin if talmacenes.State in [dsedit,dsinsert] then begin base.Panel110.Enabled:=true; end; if talmacenes.State in [dsbrowse] then begin base.Panel110.Enabled:=false; end; end; procedure TDM.dstarticulosalmacenStateChange(Sender: TObject); begin if dm.dtarticulosalmacen.State in [dsedit,dsinsert] then begin envases_almacen.Panel14.Enabled:=true; envases_almacen.btEAnuevo.enabled:=false; envases_almacen.btEAborrar.enabled:=false; envases_almacen.btEAmodificar.enabled:=false; envases_almacen.btEAguardar.enabled:=true; envases_almacen.btEAcancelar.enabled:=true; end; if dm.dtarticulosalmacen.State in [dsbrowse] then begin envases_almacen.Panel14.Enabled:=false; envases_almacen.btEAnuevo.enabled:=true; envases_almacen.btEAborrar.enabled:=true; envases_almacen.btEAmodificar.enabled:=true; envases_almacen.btEAguardar.enabled:=false; envases_almacen.btEAcancelar.enabled:=false; end; end; procedure TDM.dtarticulos_componentesAfterPost(DataSet: TDataSet); var observaciones:string; begin dtarticulos_componentes.refresh; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('select * from articulos_componentes where idempresa='+dm.dtarticulosalmacenide.Asstring+' and idarticuloalmacen='+dm.dtarticulosalmacenid.Asstring); qaux.open; qaux.First; observaciones:='LLEVA '; while not qaux.eof do begin observaciones:=observaciones+qaux.fields[4].asstring+' X '+qaux.fields[3].asstring+','; qaux.next; end; observaciones:=observaciones+' REVISADO EL '+datetostr(date()); qaux.close; qaux.SQL.Clear; qaux.SQL.Add('select sum(peso),sum(coste) from articulos_componentes where idempresa='+dm.dtarticulosalmacenide.Asstring+' and idarticuloalmacen='+dm.dtarticulosalmacenid.Asstring); qaux.open; dtarticulosalmacen.Edit; dtarticulosalmacentara.Value:=qaux.Fields[0].AsFloat; dtarticulosalmacencosto.Value:=qaux.Fields[1].AsFloat; dtarticulosalmacenobservaciones.Value:=observaciones; dtarticulosalmacen.Refresh; dtarticulos_componentes.refresh; end; procedure TDM.dtarticulos_componentesBeforePost(DataSet: TDataSet); var ide,idaf:string; begin ide:=dtarticulos_componentesidempresa.asstring; idaf:=dtarticulos_componentesidarticulof.asstring; dmclientes.qarticulosfinal.Locate('idempresa;id',vararrayof([ide,idaf]),[locaseinsensitive]); dtarticulos_componentespreciocoste.Value:=dmclientes.qarticulosfinalult_preciocompra.AsFloat; dtarticulos_componentescoste.Value:=dtarticulos_componentescantidad.asfloat*dmclientes.qarticulosfinalult_preciocompra.AsFloat; dtarticulos_componentespeso.value:=dtarticulos_componentescantidad.AsFloat*dmclientes.qarticulosfinalpeso.AsFloat; end; procedure TDM.qarticulosalmacenAfterOpen(DataSet: TDataSet); begin if dtarticulosalmacen.Active then dtarticulosalmacen.Refresh else dtarticulosalmacen.Open; end; procedure TDM.qarticulosalmacenBeforeOpen(DataSet: TDataSet); var filtrolocal:string; begin if filtro<>'' then begin begin filtrolocal:=' where descripcion like('+''''+filtro+''''+') or codigo like('+''''+filtro+''''+') or id like('+''''+filtro+''''+')'; end; if vertodos=0 then begin begin filtrolocal:=' where (descripcion like('+''''+filtro+''''+') or codigo like('+''''+filtro+''''+') or id like('+''''+filtro+''''+')'; filtrolocal:=filtrolocal+') and activo=1 '; end; end; end; if filtro='' then begin filtrolocal:=''; if vertodos=0 then begin filtrolocal:=' where activo=1 '; end; end; qarticulosalmacen.SQL.Clear; qarticulosalmacen.SQL.Add('select id,ide,codigo,descripcion,activo from articulos_almacen ' + filtrolocal +' order by descripcion') end; procedure TDM.qparcelasBeforeOpen(DataSet: TDataSet); var filtro:string; begin if filtroparcelas<>'' then begin filtro:=filtro+ ' where nombre like('+''''+filtroparcelas+''''+')'; end; if filtroparcelas='' then begin filtro:=filtro+ ' where activo=1';//+inttostr(vtactivo); end; qparcelas.SQL.Clear; qparcelas.SQL.Add('select * from parcelas ' + filtro +' order by nombre') end; procedure TDM.qseriesAfterPost(DataSet: TDataSet); begin if qseriesactivo.AsInteger=1 then begin qaux.SQL.Clear; qaux.SQL.Add('update series_numericas set activo=0 where ide='+qserieside.AsString+' and id<>'+''''+qseriesid.AsString+''''); qaux.ExecSQL; end; qseries.Refresh; end; procedure TDM.tprenominasCalcFields(DataSet: TDataSet); begin if tprenominasdiascalculo.asinteger>0 then tprenominasbasedia.value:=tprenominastotalbruto.asfloat/tprenominasdiascalculo.asfloat; end; end. ======================================== FICHERO: datosclientes.pas ======================================== unit datosclientes; interface uses System.SysUtils, System.Classes,datos, Data.DB, ZDataset, ZAbstractRODataset, ZAbstractDataset; type Tdmclientes = class(TDataModule) dtclientes: TZQuery; qclientes: TZReadOnlyQuery; dtclientesid: TIntegerField; dtclientesIdempresa: TIntegerField; dtclientesnif: TWideStringField; dtclientesnombre: TWideStringField; dtclientesdireccion: TWideStringField; dtclientespoblacion: TWideStringField; dtclientescodpost: TWideStringField; dtclientesprovincia: TWideStringField; dtclientestelefono: TWideStringField; dtclientesemail: TWideStringField; dtclientespersonacontacto: TWideStringField; dtclientescodigomercado: TIntegerField; dtclientesactivo: TIntegerField; qclientesid: TIntegerField; qclientesnombre_corto: TWideStringField; dsqclientes: TDataSource; dsclientes: TDataSource; qclientesIdempresa: TIntegerField; dtdestinos: TZQuery; dsdestinos: TDataSource; dtarticulos: TZQuery; dsarticulos: TDataSource; dtdestinosidcliente: TIntegerField; dtdestinosidempresa: TIntegerField; dtdestinoscodigo: TWideStringField; dtdestinosdescripcion: TWideStringField; dtdestinosactivo: TIntegerField; dspedidos: TDataSource; dtlinpedidos: TZQuery; dspedidosdetalle: TDataSource; dtarticulosformato: TZQuery; dsarticulosformato: TDataSource; dtarticulosformatoid: TWideStringField; dtarticulosformatoidempresa: TIntegerField; dtarticulosformatoidcliente: TIntegerField; dtarticulosformatodes_envase: TWideStringField; dtarticulosformatodesc_cliente: TWideStringField; dtarticulosformatoactivo: TIntegerField; dtarticulosformatoean: TWideStringField; dtarticulosformatomarca: TWideStringField; dtarticulosidempresa: TIntegerField; dtarticulosidcliente: TIntegerField; dtarticulosid: TWideStringField; dtarticulosdesc_cliente: TWideStringField; dtarticulosactivo: TIntegerField; dtclientesobservaciones: TWideStringField; dtclientesccontable: TIntegerField; qdestinos: TZReadOnlyQuery; dsqdestinos: TDataSource; qarticulosx: TZReadOnlyQuery; dsqarticulosx: TDataSource; qdestinosidcliente: TIntegerField; qdestinosidempresa: TIntegerField; qdestinoscodigo: TWideStringField; qdestinosdescripcion: TWideStringField; qdestinosseleccionado: TIntegerField; qdestinosactivo: TIntegerField; qpedidos: TZReadOnlyQuery; dsqpedidos: TDataSource; qarticulosxidempresa: TIntegerField; qarticulosxidcliente: TIntegerField; qarticulosxid: TWideStringField; qarticulosxdesc_cliente: TWideStringField; qarticulosxactivo: TIntegerField; dtdestinosseleccionado: TIntegerField; dtdestinosdireccion: TWideStringField; dtdestinospoblacion: TWideStringField; dtdestinoscodpost: TWideStringField; dtdestinosprovincia: TWideStringField; dtarticulosformatoobservaciones: TWideStringField; dtarticulosformatoprecio_venta: TFloatField; dtclientesnombre_corto: TWideStringField; dtclientestelefono2: TWideStringField; dtclientesmovil: TWideStringField; dtclientesdescuento: TFloatField; qpresupuestos: TZReadOnlyQuery; IntegerField1: TIntegerField; IntegerField2: TIntegerField; IntegerField3: TIntegerField; WideStringField1: TWideStringField; DateField1: TDateField; DateField2: TDateField; DateField3: TDateField; WideStringField2: TWideStringField; WideStringField3: TWideStringField; IntegerField4: TIntegerField; WideStringField4: TWideStringField; dsqpresupuestos: TDataSource; qalbaranes: TZReadOnlyQuery; dsqalbaranes: TDataSource; qfacturas: TZReadOnlyQuery; dsqfacturas: TDataSource; qnotas: TZReadOnlyQuery; IntegerField17: TIntegerField; IntegerField18: TIntegerField; IntegerField19: TIntegerField; WideStringField17: TWideStringField; DateField13: TDateField; DateField14: TDateField; DateField15: TDateField; WideStringField18: TWideStringField; WideStringField19: TWideStringField; IntegerField20: TIntegerField; WideStringField20: TWideStringField; dsqnotas: TDataSource; dtpresupuestos: TZQuery; IntegerField21: TIntegerField; IntegerField22: TIntegerField; IntegerField23: TIntegerField; WideStringField21: TWideStringField; DateField16: TDateField; DateField17: TDateField; DateField18: TDateField; WideStringField22: TWideStringField; WideStringField23: TWideStringField; IntegerField24: TIntegerField; WideStringField24: TWideStringField; dtlinpresupuestos: TZQuery; IntegerField25: TIntegerField; IntegerField26: TIntegerField; IntegerField27: TIntegerField; FloatField1: TFloatField; WideStringField25: TWideStringField; WideStringField26: TWideStringField; WideStringField27: TWideStringField; WideStringField28: TWideStringField; FloatField2: TFloatField; WideStringField29: TWideStringField; IntegerField28: TIntegerField; IntegerField29: TIntegerField; WideStringField30: TWideStringField; WideStringField31: TWideStringField; WideStringField32: TWideStringField; IntegerField30: TIntegerField; dtalbaranes: TZQuery; IntegerField31: TIntegerField; IntegerField32: TIntegerField; IntegerField33: TIntegerField; WideStringField33: TWideStringField; DateField19: TDateField; DateField20: TDateField; DateField21: TDateField; WideStringField34: TWideStringField; WideStringField35: TWideStringField; IntegerField34: TIntegerField; WideStringField36: TWideStringField; dtlinalbaranes: TZQuery; IntegerField35: TIntegerField; IntegerField36: TIntegerField; IntegerField37: TIntegerField; FloatField3: TFloatField; WideStringField37: TWideStringField; WideStringField38: TWideStringField; WideStringField39: TWideStringField; WideStringField40: TWideStringField; FloatField4: TFloatField; WideStringField41: TWideStringField; IntegerField38: TIntegerField; IntegerField39: TIntegerField; WideStringField42: TWideStringField; WideStringField43: TWideStringField; WideStringField44: TWideStringField; IntegerField40: TIntegerField; dtfacturasproforma: TZQuery; IntegerField41: TIntegerField; IntegerField42: TIntegerField; IntegerField43: TIntegerField; WideStringField45: TWideStringField; DateField22: TDateField; DateField23: TDateField; DateField24: TDateField; WideStringField46: TWideStringField; WideStringField47: TWideStringField; IntegerField44: TIntegerField; WideStringField48: TWideStringField; dtlinfacturasproforma: TZQuery; IntegerField45: TIntegerField; IntegerField46: TIntegerField; IntegerField47: TIntegerField; FloatField5: TFloatField; WideStringField49: TWideStringField; WideStringField50: TWideStringField; WideStringField51: TWideStringField; WideStringField52: TWideStringField; FloatField6: TFloatField; WideStringField53: TWideStringField; IntegerField48: TIntegerField; IntegerField49: TIntegerField; WideStringField54: TWideStringField; WideStringField55: TWideStringField; WideStringField56: TWideStringField; IntegerField50: TIntegerField; dtlinfacturas: TZQuery; IntegerField55: TIntegerField; IntegerField56: TIntegerField; IntegerField57: TIntegerField; FloatField7: TFloatField; WideStringField61: TWideStringField; WideStringField62: TWideStringField; WideStringField63: TWideStringField; WideStringField64: TWideStringField; FloatField8: TFloatField; WideStringField65: TWideStringField; IntegerField58: TIntegerField; IntegerField59: TIntegerField; WideStringField66: TWideStringField; WideStringField67: TWideStringField; WideStringField68: TWideStringField; IntegerField60: TIntegerField; dtnotas: TZQuery; IntegerField61: TIntegerField; IntegerField62: TIntegerField; IntegerField63: TIntegerField; WideStringField69: TWideStringField; DateField28: TDateField; DateField29: TDateField; DateField30: TDateField; WideStringField70: TWideStringField; WideStringField71: TWideStringField; IntegerField64: TIntegerField; WideStringField72: TWideStringField; dtlinnotas: TZQuery; IntegerField65: TIntegerField; IntegerField66: TIntegerField; IntegerField67: TIntegerField; FloatField9: TFloatField; WideStringField73: TWideStringField; WideStringField74: TWideStringField; WideStringField75: TWideStringField; WideStringField76: TWideStringField; FloatField10: TFloatField; WideStringField77: TWideStringField; IntegerField68: TIntegerField; IntegerField69: TIntegerField; WideStringField78: TWideStringField; WideStringField79: TWideStringField; WideStringField80: TWideStringField; IntegerField70: TIntegerField; dstpresupuestos: TDataSource; dslinpresupuestos: TDataSource; dstalbaranes: TDataSource; dslinalbaranes: TDataSource; dstfacturasproforma: TDataSource; dslinfacturasproforma: TDataSource; dstfacturas: TDataSource; dslinfacturas: TDataSource; dstnotas: TDataSource; dslinnotas: TDataSource; dtarticulosformatoidformato: TIntegerField; dtarticulosformatounidades: TFloatField; qpedidosid: TIntegerField; qpedidoside: TIntegerField; qpedidosidcliente: TIntegerField; qpedidosiddestino: TWideStringField; qpedidosfecha_pedido: TDateField; qpedidosfecha_carga: TDateField; qpedidosfecha_entrega: TDateField; qpedidoshora_carga: TTimeField; qpedidospedidocliente: TWideStringField; qpedidosabierto: TIntegerField; qpedidosobservaciones: TWideStringField; dtpedidos: TZQuery; dtpedidosid: TIntegerField; dtpedidoside: TIntegerField; dtpedidosidcliente: TIntegerField; dtpedidosiddestino: TWideStringField; dtpedidosfecha_pedido: TDateField; dtpedidosfecha_carga: TDateField; dtpedidosfecha_entrega: TDateField; dtpedidoshora_carga: TTimeField; dtpedidospedidocliente: TWideStringField; dtpedidosabierto: TIntegerField; dtpedidosobservaciones: TWideStringField; qpedidosnombre: TWideStringField; qpedidosdescripcion: TWideStringField; dtlinpedidosid: TIntegerField; dtlinpedidoside: TIntegerField; dtlinpedidosidpedido: TIntegerField; dtlinpedidosidcliente: TIntegerField; dtlinpedidosidproductocli: TWideStringField; dtlinpedidosidenvase: TWideStringField; dtlinpedidosdesc_envase: TWideStringField; dtlinpedidosdesc_producto: TWideStringField; dtlinpedidoscantidad: TFloatField; dtlinpedidoscantidadservida: TFloatField; dtlinpedidospalets: TIntegerField; dtlinpedidosref: TWideStringField; dtlinpedidosean: TWideStringField; dtlinpedidosmarca: TWideStringField; dtlinpedidosobservaciones: TWideStringField; dtlinpedidosidcajapropia: TWideStringField; dtlinpedidos2: TZQuery; dtlinpedidos2id: TIntegerField; dtlinpedidos2ide: TIntegerField; dtlinpedidos2idpedido: TIntegerField; dtlinpedidos2idcliente: TIntegerField; dtlinpedidos2idproductocli: TWideStringField; dtlinpedidos2idenvase: TWideStringField; dtlinpedidos2desc_envase: TWideStringField; dtlinpedidos2desc_producto: TWideStringField; dtlinpedidos2cantidad: TFloatField; dtlinpedidos2cantidadservida: TFloatField; dtlinpedidos2palets: TIntegerField; dtlinpedidos2ref: TWideStringField; dtlinpedidos2ean: TWideStringField; dtlinpedidos2marca: TWideStringField; dtlinpedidos2observaciones: TWideStringField; dtlinpedidos2idcajapropia: TWideStringField; dspedidosdestalle2: TDataSource; dtpedidosfecha_elavoracion: TDateField; qarticulosfinal: TZReadOnlyQuery; qarticulosfinalidempresa: TIntegerField; qarticulosfinalid: TIntegerField; qarticulosfinalcodigo: TWideStringField; qarticulosfinaldescripcion: TWideStringField; qarticulosfinalactivo: TIntegerField; dsqarticulosfinal: TDataSource; dtclientespais: TWideStringField; dtdestinospais: TWideStringField; dtclientesidformapago: TIntegerField; qalbaranesserie: TWideStringField; qalbaranesid: TIntegerField; qalbaranesidempresa: TIntegerField; qalbaranesidcliente: TIntegerField; qalbaranesiddestino: TWideStringField; qalbaranesnif: TWideStringField; qalbaranesdireccion: TWideStringField; qalbaranespoblacion: TWideStringField; qalbaranesprovincia: TWideStringField; qalbaranescodpost: TWideStringField; qalbaranesfecha: TDateField; qalbaranesreferencia: TWideStringField; qalbaranestelefono: TWideStringField; qalbaranesnomcliente: TWideStringField; qalbaranespaiscliente: TWideStringField; qalbaranesnomdestino: TWideStringField; qalbaranesdirecciondestino: TWideStringField; qalbaranespoblaciondestino: TWideStringField; qalbaranescodpostdestino: TWideStringField; qalbaranesprovinciadestino: TWideStringField; qalbaranespaisdestino: TWideStringField; qalbaranesneto: TFloatField; qalbaranestotal: TFloatField; qalbaranesfacturado: TIntegerField; qalbaranesdocumento: TWideStringField; qalbaranesdescuento_lin: TFloatField; qalbaranesdescuento_com: TFloatField; qalbaranesdescuento_pp: TFloatField; qalbaranesdescuento_total: TFloatField; qalbaranestotaliva: TFloatField; qalbaranesobservaciones: TWideStringField; qalbaranesidfactura: TIntegerField; qalbaranesbultos: TFloatField; qalbaraneskilos: TFloatField; qalbaranesidformapago: TIntegerField; qfacturasserie: TWideStringField; qfacturasid: TIntegerField; qfacturasidempresa: TIntegerField; qfacturasidcliente: TIntegerField; qfacturasiddestino: TWideStringField; qfacturasnif: TWideStringField; qfacturasdireccion: TWideStringField; qfacturaspoblacion: TWideStringField; qfacturasprovincia: TWideStringField; qfacturascodpost: TWideStringField; qfacturasfecha: TDateField; qfacturasreferencia: TWideStringField; qfacturastelefono: TWideStringField; qfacturasnomcliente: TWideStringField; qfacturaspaiscliente: TWideStringField; qfacturasnomdestino: TWideStringField; qfacturasdirecciondestino: TWideStringField; qfacturaspoblaciondestino: TWideStringField; qfacturascodpostdestino: TWideStringField; qfacturasprovinciadestino: TWideStringField; qfacturaspaisdestino: TWideStringField; qfacturasneto: TFloatField; qfacturastotal: TFloatField; qfacturasdocumento: TWideStringField; qfacturasdescuento_lin: TFloatField; qfacturasdescuento_com: TFloatField; qfacturasdescuento_pp: TFloatField; qfacturasdescuento_total: TFloatField; qfacturastotaliva: TFloatField; qfacturasobservaciones: TWideStringField; qfacturasbultos: TFloatField; qfacturaskilos: TFloatField; qfacturasidformapago: TIntegerField; dtclientesexento_iva: TIntegerField; qfacturascobrado: TIntegerField; qarticulosfinalpeso: TFloatField; dtclientescomision: TFloatField; dtclientesidcp: TIntegerField; qarticulosfinalult_preciocompra: TFloatField; dtclientestipocliente: TWideStringField; dsqpedidosclientes: TDataSource; qpedidosclientes: TZReadOnlyQuery; qpedidosclientesid: TIntegerField; qpedidosclientesidcliente: TIntegerField; qpedidosclientesiddestino: TWideStringField; qpedidosclientesfecha_pedido: TDateField; qpedidosclientesfecha_carga: TDateField; qpedidosclientesidpedido: TIntegerField; qpedidosclientesid_1: TIntegerField; qpedidosclientesidalbaran: TWideStringField; qpedidosclientesidexpedicion: TWideStringField; qpedidosclientespedidocliente: TWideStringField; dsqclientescalidad: TDataSource; qclientescalidad: TZQuery; qclientescalidadid: TWideStringField; qclientescalidadidempresa: TIntegerField; qclientescalidadidcliente: TIntegerField; qclientescalidaddescripcion: TWideStringField; qclientescalidadactivo: TIntegerField; qarticulos: TZQuery; dsqclientesacabados: TDataSource; qclientesacabados: TZQuery; qclientesacabadosid: TWideStringField; qclientesacabadosidempresa: TIntegerField; qclientesacabadosidcliente: TIntegerField; qclientesacabadosdescripcion: TWideStringField; qclientesacabadosactivo: TIntegerField; qclientesacabadosean: TWideStringField; qclientesacabadosmarca: TWideStringField; qclientesacabadosobservaciones: TWideStringField; qarticulosidempresa: TIntegerField; qarticulosidcliente: TIntegerField; qarticulosid: TWideStringField; qarticulosdesc_cliente: TWideStringField; qarticulosactivo: TIntegerField; dsqarticulos: TDataSource; dtclientesusa_re: TIntegerField; dtclientesean: TWideStringField; dtdestinosean: TWideStringField; dtdestinosdep: TWideStringField; dtdestinosean2: TWideStringField; dtdestinoseanreceptor: TWideStringField; procedure dtclientesAfterPost(DataSet: TDataSet); procedure dtarticulosAfterOpen(DataSet: TDataSet); procedure dtarticulosAfterClose(DataSet: TDataSet); procedure dsclientesStateChange(Sender: TObject); procedure dsdestinosStateChange(Sender: TObject); procedure dsarticulosStateChange(Sender: TObject); procedure dsarticulosformatoStateChange(Sender: TObject); procedure qclientesBeforeOpen(DataSet: TDataSet); procedure qarticulosfinalBeforeOpen(DataSet: TDataSet); procedure dsarticulosfinalStateChange(Sender: TObject); procedure qpedidosAfterOpen(DataSet: TDataSet); procedure qpedidosAfterClose(DataSet: TDataSet); procedure dspedidosStateChange(Sender: TObject); procedure qpedidosBeforeOpen(DataSet: TDataSet); procedure dspedidosdetalleDataChange(Sender: TObject; Field: TField); procedure dspedidosdetalleStateChange(Sender: TObject); procedure dspedidosdestalle2StateChange(Sender: TObject); procedure dsqclientesDataChange(Sender: TObject; Field: TField); procedure dsqclientescalidadStateChange(Sender: TObject); procedure dsqarticulosStateChange(Sender: TObject); procedure dsqclientesacabadosStateChange(Sender: TObject); private { Private declarations } public { Public declarations } var filtro:string; vertodos,vertodosmateriales:integer; end; var dmclientes: Tdmclientes; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} uses fclientes,fpedidos; {$R *.dfm} procedure Tdmclientes.dsarticulosfinalStateChange(Sender: TObject); begin { if dmclientes.dtarticulosfinal.State in [dsedit,dsinsert] then begin articulos.Panel14.Enabled:=true; articulos.btAnuevo.enabled:=false; articulos.btAborrar.enabled:=false; articulos.btAmodificar.enabled:=false; articulos.btAguardar.enabled:=true; articulos.btAcancelar.enabled:=true; end; if dmclientes.dtarticulosfinal.State in [dsbrowse] then begin articulos.Panel14.Enabled:=false; articulos.btAnuevo.enabled:=true; articulos.btAborrar.enabled:=true; articulos.btAmodificar.enabled:=true; articulos.btAguardar.enabled:=false; articulos.btAcancelar.enabled:=false; end; } end; procedure Tdmclientes.dsarticulosformatoStateChange(Sender: TObject); begin if dmclientes.dtarticulosformato.State in [dsedit,dsinsert] then begin clientes.btADnuevo.enabled:=false; clientes.btADborrar.enabled:=false; clientes.btADmodificar.enabled:=false; clientes.btADguardar.enabled:=true; clientes.btADcancelar.enabled:=true; end; if dmclientes.dtarticulosformato.State in [dsbrowse] then begin clientes.btADnuevo.enabled:=true; clientes.btADborrar.enabled:=true; clientes.btADmodificar.enabled:=true; clientes.btADguardar.enabled:=false; clientes.btADcancelar.enabled:=false; end; end; procedure Tdmclientes.dsarticulosStateChange(Sender: TObject); begin if dmclientes.dtarticulos.State in [dsedit,dsinsert] then begin clientes.btAnuevo.enabled:=false; clientes.btAborrar.enabled:=false; clientes.btAmodificar.enabled:=false; clientes.btAguardar.enabled:=true; clientes.btAcancelar.enabled:=true; end; if dmclientes.dtarticulos.State in [dsbrowse] then begin clientes.btAnuevo.enabled:=true; clientes.btAborrar.enabled:=true; clientes.btAmodificar.enabled:=true; clientes.btAguardar.enabled:=false; clientes.btAcancelar.enabled:=false; end; end; procedure Tdmclientes.dsclientesStateChange(Sender: TObject); begin if dmclientes.dtclientes.State in [dsedit,dsinsert] then begin clientes.Panel14.Enabled:=true; clientes.btCnuevo.enabled:=false; clientes.btCborrar.enabled:=false; clientes.btCmodificar.enabled:=false; clientes.btCguardar.enabled:=true; clientes.btCcancelar.enabled:=true; end; if dmclientes.dtclientes.State in [dsbrowse] then begin clientes.Panel14.Enabled:=false; clientes.btCnuevo.enabled:=true; clientes.btCborrar.enabled:=true; clientes.btCmodificar.enabled:=true; clientes.btCguardar.enabled:=false; clientes.btCcancelar.enabled:=false; end; end; procedure Tdmclientes.dsdestinosStateChange(Sender: TObject); begin if dmclientes.dtdestinos.State in [dsedit,dsinsert] then begin clientes.Panel19.Enabled:=true; clientes.btDnuevo.enabled:=false; clientes.btDborrar.enabled:=false; clientes.btDmodificar.enabled:=false; clientes.btDguardar.enabled:=true; clientes.btDcancelar.enabled:=true; end; if dmclientes.dtdestinos.State in [dsbrowse] then begin clientes.Panel19.Enabled:=false; clientes.btDnuevo.enabled:=true; clientes.btDborrar.enabled:=true; clientes.btDmodificar.enabled:=true; clientes.btDguardar.enabled:=false; clientes.btDcancelar.enabled:=false; end; end; procedure Tdmclientes.dspedidosdestalle2StateChange(Sender: TObject); begin if dmclientes.dtlinpedidos2.State in [dsedit,dsinsert] then begin pedidos.btPdnuevo.enabled:=false; pedidos.btPdborrar.enabled:=false; pedidos.btPdmodificar.enabled:=false; // pedidos.btPdguardar.enabled:=true; // pedidos.btPdcancelar.enabled:=true; end; if dmclientes.dtlinpedidos2.State in [dsbrowse] then begin pedidos.btPdnuevo.enabled:=true; pedidos.btPdborrar.enabled:=true; pedidos.btPdmodificar.enabled:=true; // pedidos.btPdguardar.enabled:=false; // pedidos.btPdcancelar.enabled:=false; end; end; procedure Tdmclientes.dspedidosdetalleDataChange(Sender: TObject; Field: TField); begin if dmclientes.dtlinpedidosid.AsString<>'' then begin pedidos.qenvasados2.Close; pedidos.qenvasados2.SQL.Clear; pedidos.qenvasados2.SQL.Add('select * from ea_pesadas where iddestino in (select id from almacenes where final=1) and idpedido='+dmclientes.dtlinpedidosid.asstring+' ORDER BY `id` DESC'); pedidos.qenvasados2.open; end else begin pedidos.qenvasados2.SQL.Clear; pedidos.qenvasados2.SQL.Add('select * from ea_pesadas where iddestino in (select id from almacenes where final=1) and idpedido is not null ORDER BY `id` DESC'); pedidos.qenvasados2.open; end; end; procedure Tdmclientes.dspedidosdetalleStateChange(Sender: TObject); begin if dmclientes.dtlinpedidos.State in [dsedit,dsinsert] then begin pedidos.btPdnuevo.enabled:=false; pedidos.btPdborrar.enabled:=false; pedidos.btPdmodificar.enabled:=false; // pedidos.btPdguardar.enabled:=true; // pedidos.btPdcancelar.enabled:=true; end; if dmclientes.dtlinpedidos.State in [dsbrowse] then begin pedidos.btPdnuevo.enabled:=true; pedidos.btPdborrar.enabled:=true; pedidos.btPdmodificar.enabled:=true; // pedidos.btPdguardar.enabled:=false; // pedidos.btPdcancelar.enabled:=false; end; end; procedure Tdmclientes.dspedidosStateChange(Sender: TObject); begin pedidos := Tpedidos.Create(nil); if dmclientes.dtpedidos.State in [dsedit,dsinsert] then begin pedidos.Pdatospedidos.Enabled:=true; pedidos.btPnuevo.enabled:=false; pedidos.btPborrar.enabled:=false; pedidos.btPmodificar.enabled:=false; pedidos.btPguardar.enabled:=true; pedidos.btPcancelar.enabled:=true; end; if dmclientes.dtpedidos.State in [dsbrowse] then begin pedidos.Pdatospedidos.Enabled:=false; pedidos.btPnuevo.enabled:=true; pedidos.btPborrar.enabled:=true; pedidos.btPmodificar.enabled:=true; pedidos.btPguardar.enabled:=false; pedidos.btPcancelar.enabled:=false; end; end; procedure Tdmclientes.dsqarticulosStateChange(Sender: TObject); begin if dmclientes.qarticulos.State in [dsedit,dsinsert] then begin clientes.btAnuevo.enabled:=false; clientes.btAborrar.enabled:=false; clientes.btAmodificar.enabled:=false; clientes.btAguardar.enabled:=true; clientes.btAcancelar.enabled:=true; end; if dmclientes.qarticulos.State in [dsbrowse] then begin clientes.btAnuevo.enabled:=true; clientes.btAborrar.enabled:=true; clientes.btAmodificar.enabled:=true; clientes.btAguardar.enabled:=false; clientes.btAcancelar.enabled:=false; end; end; procedure Tdmclientes.dsqclientesacabadosStateChange(Sender: TObject); begin if dmclientes.qclientesacabados.State in [dsedit,dsinsert] then begin clientes.btCAnuevo.enabled:=false; clientes.btCAborrar.enabled:=false; clientes.btCAmodificar.enabled:=false; clientes.btCAguardar.enabled:=true; clientes.btCAcancelar.enabled:=true; end; if dmclientes.qclientesacabados.State in [dsbrowse] then begin clientes.btCAnuevo.enabled:=true; clientes.btCAborrar.enabled:=true; clientes.btCAmodificar.enabled:=true; clientes.btCAguardar.enabled:=false; clientes.btCAcancelar.enabled:=false; end; end; procedure Tdmclientes.dsqclientescalidadStateChange(Sender: TObject); begin if dmclientes.qclientescalidad.State in [dsedit,dsinsert] then begin clientes.btClnuevo.enabled:=false; clientes.btClborrar.enabled:=false; clientes.btClmodificar.enabled:=false; clientes.btClguardar.enabled:=true; clientes.btClcancelar.enabled:=true; end; if dmclientes.qclientescalidad.State in [dsbrowse] then begin clientes.btClnuevo.enabled:=true; clientes.btClborrar.enabled:=true; clientes.btClmodificar.enabled:=true; clientes.btClguardar.enabled:=false; clientes.btClcancelar.enabled:=false; end; end; procedure Tdmclientes.dsqclientesDataChange(Sender: TObject; Field: TField); begin if qclientes.RecordCount>0 then begin qpedidosclientes.Close; qpedidosclientes.SQL.clear; qpedidosclientes.SQL.Add('select p.pedidocliente,p.id,p.idcliente,p.iddestino,p.fecha_pedido,p.fecha_carga,pd.idpedido,pd.id,pd.idalbaran,pd.idexpedicion from pedidos p, pedidosdetalle pd where p.id=pd.idpedido and p.ide=pd.ide and p.ide='+qclientesidempresa.asstring+' and p.idcliente='+qclientesid.AsString); qpedidosclientes.SQL.Add('order by p.fecha_pedido desc,pd.id'); qpedidosclientes.Open; end; end; procedure Tdmclientes.dtarticulosAfterClose(DataSet: TDataSet); begin dtarticulosformato.Close; end; procedure Tdmclientes.dtarticulosAfterOpen(DataSet: TDataSet); begin if dtarticulosformato.Active then dtarticulosformato.Refresh else dtarticulosformato.Open; end; procedure Tdmclientes.dtclientesAfterPost(DataSet: TDataSet); begin qclientes.Refresh; end; procedure Tdmclientes.qarticulosfinalBeforeOpen(DataSet: TDataSet); var filtrolocal:string; begin if filtro<>'' then begin begin filtrolocal:=' where descripcion like('+''''+filtro+''''+') or codigo like('+''''+filtro+''''+') or id like('+''''+filtro+''''+')'; end; if vertodosmateriales=0 then begin begin filtrolocal:=' where (descripcion like('+''''+filtro+''''+') or codigo like('+''''+filtro+''''+') or id like('+''''+filtro+''''+')'; filtrolocal:=filtrolocal+') and activo=1 '; end; end; end; if filtro='' then begin filtrolocal:=''; if vertodosmateriales=0 then begin filtrolocal:=' where activo=1 '; end; end; qarticulosfinal.SQL.Clear; qarticulosfinal.SQL.Add('select idempresa,id,codigo,descripcion,activo,ult_preciocompra,peso from articulosf ' + filtrolocal +' order by descripcion') end; procedure Tdmclientes.qclientesBeforeOpen(DataSet: TDataSet); var filtrolocal:string; begin dm.tempresa.Open; if filtro<>'' then begin begin filtrolocal:=' where nombre like('+''''+filtro+''''+') or nombre_corto like('+''''+filtro+''''+') or id like('+''''+filtro+''''+')'; end; if vertodos=0 then begin begin filtrolocal:=' where (nombre like('+''''+filtro+''''+') or nombre_corto like('+''''+filtro+''''+') or id like('+''''+filtro+''''+')'; filtrolocal:=filtrolocal+') and activo=1 '; end; end; end; if filtro='' then begin filtrolocal:=''; if vertodos=0 then begin filtrolocal:=' where activo=1 '; end; end; qclientes.SQL.Clear; qclientes.SQL.Add('select id,nombre_corto,idempresa from clientes ' + filtrolocal +' order by nombre_corto') end; procedure Tdmclientes.qpedidosAfterClose(DataSet: TDataSet); begin dtpedidos.close; dtlinpedidos.Close; end; procedure Tdmclientes.qpedidosAfterOpen(DataSet: TDataSet); begin dtpedidos.Open; dtlinpedidos.Open; end; procedure Tdmclientes.qpedidosBeforeOpen(DataSet: TDataSet); var filtrolocal:string; begin if filtro<>'' then begin qpedidos.SQL.Clear; qpedidos.SQL.Add('select p.*,c.nombre,d.descripcion from pedidos p,clientes c,clientes_destinos d where (c.nombre like('+filtro+') or p.pedidocliente like ('+filtro+')) and p.idcliente=c.id and p.iddestino=d.codigo and c.id=d.idcliente order by fecha_pedido desc, id desc'); end else begin qpedidos.SQL.Clear; qpedidos.SQL.Add('select p.*,c.nombre,d.descripcion from pedidos p,clientes c,clientes_destinos d where p.idcliente=c.id and p.iddestino=d.codigo and c.id=d.idcliente order by fecha_pedido desc, id desc'); end; end; end. ======================================== FICHERO: datosclientesUnit1.pas ======================================== unit datosclientesUnit1; interface uses System.SysUtils, System.Classes; type Tdmclientes = class(TDataModule) private { Private declarations } public { Public declarations } end; var dmclientes: Tdmclientes; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} end. ======================================== FICHERO: datosestadisticas.pas ======================================== unit datosestadisticas; interface uses System.SysUtils, System.Classes, Data.DB, ZAbstractRODataset, ZDataset,datos, ZAbstractDataset; type TDMEstadisticas = class(TDataModule) dsqcampanyas: TDataSource; qcampanyas: TZReadOnlyQuery; qproduccion: TZReadOnlyQuery; dsqproduccion: TDataSource; dsqproducciondetallexx: TDataSource; qproduccionmprima: TWideStringField; qproduccionsumpeso_neto: TFloatField; qproduccion_almacen: TZReadOnlyQuery; dsqproduccionalmacen: TDataSource; qcontenido: TZReadOnlyQuery; dsqcontenido: TDataSource; qcontenidodestino: TWideStringField; qcontenidoenvases: TLargeintField; qcontenidopesoneto: TFloatField; qcontenidoid_envase: TWideStringField; qcontenidomprima: TWideStringField; dsqproduccionimpresion: TDataSource; qcontenidopesonetoteorico: TFloatField; qproduccionimpresion: TZReadOnlyQuery; qproduccionparcela: TWideStringField; ZReadOnlyQuery1: TZReadOnlyQuery; WideStringField4: TWideStringField; LargeintField1: TLargeintField; FloatField8: TFloatField; FloatField9: TFloatField; WideStringField6: TWideStringField; WideStringField7: TWideStringField; DataSource1: TDataSource; ZReadOnlyQuery2: TZReadOnlyQuery; WideStringField8: TWideStringField; LargeintField2: TLargeintField; FloatField10: TFloatField; FloatField11: TFloatField; WideStringField9: TWideStringField; WideStringField10: TWideStringField; DataSource2: TDataSource; qproduccionimpresionid: TIntegerField; qproduccionimpresionidempresa: TIntegerField; qproduccionimpresionidea: TIntegerField; qproduccionimpresionid_palet: TWideStringField; qproduccionimpresionnum_palets: TIntegerField; qproduccionimpresionid_palet2: TWideStringField; qproduccionimpresionnum_palets2: TIntegerField; qproduccionimpresionid_envase: TWideStringField; qproduccionimpresionnum_envases: TIntegerField; qproduccionimpresioniddestino: TIntegerField; qproduccionimpresiondestino: TWideStringField; qproduccionimpresionpeso_bruto: TFloatField; qproduccionimpresiontara: TFloatField; qproduccionimpresionpeso_neto: TFloatField; qproduccionimpresionpeso_neto_teorico: TFloatField; qproduccionimpresionpeso_medio: TFloatField; qproduccionimpresiontemperatura: TFloatField; qproduccionimpresionfecha: TDateField; qproduccionimpresionfechatrabajo: TDateField; qproduccionimpresionhora: TTimeField; qproduccionimpresionCEA: TWideStringField; qproduccionimpresionresto_cajas: TFloatField; qproduccionimpresionresto_pesoneto: TFloatField; qproduccionimpresionlote: TIntegerField; qproduccionimpresionorigen: TWideStringField; qproduccionimpresionidorigen: TIntegerField; qproduccionimpresionmprima: TWideStringField; qproduccionimpresiongen_caja: TIntegerField; qproduccionimpresioncosto: TFloatField; qproduccionimpresioncoste_manipulacion: TFloatField; qproduccionimpresiondias_camara: TIntegerField; qproduccionimpresioncosto_camara: TFloatField; qproduccionimpresioncodigoR: TWideStringField; qproduccionimpresionparcela: TWideStringField; qproduccionimpresionfecha_cierre: TDateField; qproduccionimpresioncosto_materiales: TFloatField; qproduccionimpresioncosto_cosechar: TFloatField; qproduccionimpresionborrado: TIntegerField; qproduccionimpresionseleccionado: TIntegerField; qproduccionimpresionobservaciones: TWideStringField; qproduccionimpresiontipo_trabajo: TWideStringField; qproduccionimpresiontipo_generador: TWideStringField; qproduccionimpresionremanipulado: TIntegerField; qproduccionimpresionfecha_envasado: TDateField; qproduccionimpresioncodean: TWideStringField; qproduccionimpresioncodssc: TWideStringField; qproduccionimpresionpedidocliente: TIntegerField; qproduccionimpresioncosto_sinmt: TFloatField; qproduccion_almacenid: TIntegerField; qproduccion_almacenidempresa: TIntegerField; qproduccion_almacenidea: TIntegerField; qproduccion_almacenid_palet: TWideStringField; qproduccion_almacennum_palets: TIntegerField; qproduccion_almacenid_palet2: TWideStringField; qproduccion_almacennum_palets2: TIntegerField; qproduccion_almacenid_envase: TWideStringField; qproduccion_almacennum_envases: TIntegerField; qproduccion_almaceniddestino: TIntegerField; qproduccion_almacendestino: TWideStringField; qproduccion_almacenpeso_bruto: TFloatField; qproduccion_almacentara: TFloatField; qproduccion_almacenpeso_neto: TFloatField; qproduccion_almacenpeso_neto_teorico: TFloatField; qproduccion_almacenpeso_medio: TFloatField; qproduccion_almacentemperatura: TFloatField; qproduccion_almacenfecha: TDateField; qproduccion_almacenfechatrabajo: TDateField; qproduccion_almacenhora: TTimeField; qproduccion_almacenCEA: TWideStringField; qproduccion_almacenresto_cajas: TFloatField; qproduccion_almacenresto_pesoneto: TFloatField; qproduccion_almacenlote: TIntegerField; qproduccion_almacenorigen: TWideStringField; qproduccion_almacenidorigen: TIntegerField; qproduccion_almacenmprima: TWideStringField; qproduccion_almacengen_caja: TIntegerField; qproduccion_almacencosto: TFloatField; qproduccion_almacencoste_manipulacion: TFloatField; qproduccion_almacendias_camara: TIntegerField; qproduccion_almacencosto_camara: TFloatField; qproduccion_almacencodigoR: TWideStringField; qproduccion_almacenparcela: TWideStringField; qproduccion_almacenfecha_cierre: TDateField; qproduccion_almacencosto_materiales: TFloatField; qproduccion_almacencosto_cosechar: TFloatField; qproduccion_almacenborrado: TIntegerField; qproduccion_almacenseleccionado: TIntegerField; qproduccion_almacenobservaciones: TWideStringField; qproduccion_almacentipo_trabajo: TWideStringField; qproduccion_almacentipo_generador: TWideStringField; qproduccion_almacenremanipulado: TIntegerField; qproduccion_almacenfecha_envasado: TDateField; qproduccion_almacencodean: TWideStringField; qproduccion_almacencodssc: TWideStringField; qproduccion_almacenpedidocliente: TIntegerField; qproduccion_almacencosto_sinmt: TFloatField; qsalidas: TZReadOnlyQuery; WideStringField1: TWideStringField; WideStringField2: TWideStringField; FloatField2: TFloatField; qsalidasdetalles: TZReadOnlyQuery; dsqsalidas: TDataSource; dsqsalidasdetalles: TDataSource; qsalidasdetallesid: TIntegerField; qsalidasdetallesidempresa: TIntegerField; qsalidasdetallesidea: TIntegerField; qsalidasdetallesid_palet: TWideStringField; qsalidasdetallesnum_palets: TIntegerField; qsalidasdetallesid_palet2: TWideStringField; qsalidasdetallesnum_palets2: TIntegerField; qsalidasdetallesid_envase: TWideStringField; qsalidasdetallesnum_envases: TIntegerField; qsalidasdetallesiddestino: TIntegerField; qsalidasdetallesdestino: TWideStringField; qsalidasdetallespeso_bruto: TFloatField; qsalidasdetallestara: TFloatField; qsalidasdetallespeso_neto: TFloatField; qsalidasdetallespeso_neto_teorico: TFloatField; qsalidasdetallespeso_medio: TFloatField; qsalidasdetallestemperatura: TFloatField; qsalidasdetallesfecha: TDateField; qsalidasdetallesfechatrabajo: TDateField; qsalidasdetalleshora: TTimeField; qsalidasdetallesCEA: TWideStringField; qsalidasdetallesresto_cajas: TFloatField; qsalidasdetallesresto_pesoneto: TFloatField; qsalidasdetalleslote: TIntegerField; qsalidasdetallesorigen: TWideStringField; qsalidasdetallesidorigen: TIntegerField; qsalidasdetallesmprima: TWideStringField; qsalidasdetallesmprima_p: TWideStringField; qsalidasdetallesgen_caja: TIntegerField; qsalidasdetallescosto: TFloatField; qsalidasdetallescoste_manipulacion: TFloatField; qsalidasdetallesdias_camara: TIntegerField; qsalidasdetallescosto_camara: TFloatField; qsalidasdetallescodigoR: TWideStringField; qsalidasdetallesparcela: TWideStringField; qsalidasdetallesfecha_cierre: TDateField; qsalidasdetallescosto_materiales: TFloatField; qsalidasdetallescosto_cosechar: TFloatField; qsalidasdetallesborrado: TIntegerField; qsalidasdetallesseleccionado: TIntegerField; qsalidasdetallesobservaciones: TWideStringField; qsalidasdetallestipo_trabajo: TWideStringField; qsalidasdetallestipo_generador: TWideStringField; qsalidasdetallesremanipulado: TIntegerField; qsalidasdetallesfecha_envasado: TDateField; qsalidasdetallescodean: TWideStringField; qsalidasdetallescodssc: TWideStringField; qsalidasdetallespedidocliente: TIntegerField; qsalidasdetallescosto_sinmt: TFloatField; qsalidasdetallesrecuperar_envases: TIntegerField; dsqinfsalidas: TDataSource; qinfsalidas: TZQuery; dsqinfentradas: TDataSource; qinfentradas: TZQuery; qinfentradasid: TIntegerField; qinfentradasfecha: TDateField; qinfentradasfechatrabajo: TDateField; qinfentradasparcela: TWideStringField; qinfentradasmprima: TWideStringField; qinfentradasid_envase: TWideStringField; qinfentradasnum_envases: TIntegerField; qinfentradascliente: TWideStringField; qinfentradasciudad: TWideStringField; qinfentradaspeso_neto: TFloatField; qinfentradaspeso_neto_teorico: TFloatField; qinfentradaspeso_medio: TFloatField; qinfentradastemperatura: TFloatField; qinfentradaslote: TIntegerField; qinfsalidasid: TIntegerField; qinfsalidasfecha: TDateField; qinfsalidasfechatrabajo: TDateField; qinfsalidasparcela: TWideStringField; qinfsalidasmprima: TWideStringField; qinfsalidasid_envase: TWideStringField; qinfsalidasnum_envases: TIntegerField; qinfsalidascliente: TWideStringField; qinfsalidasciudad: TWideStringField; qinfsalidaspeso_neto: TFloatField; qinfsalidaspeso_neto_teorico: TFloatField; qinfsalidaspeso_medio: TFloatField; qinfsalidastemperatura: TFloatField; qinfsalidaslote: TIntegerField; qinfsalidasmprima_p: TWideStringField; qinfentradasmprima_p: TWideStringField; qinfentradasidalbaran: TWideStringField; qinfsalidasidalbaran: TWideStringField; qproduccionimpresionmprima_p: TWideStringField; qproduccionimpresionrecuperar_envases: TIntegerField; qproduccionimpresionidalbaran: TWideStringField; qproduccionimpresiones_entrada: TIntegerField; qproduccionimpresiondesc_calibre: TWideStringField; qproduccionimpresiondesc_formato: TWideStringField; qcontenidodesc_formato: TWideStringField; qproduccion_almacenmprima_p: TWideStringField; qproduccion_almacenrecuperar_envases: TIntegerField; qproduccion_almacenidalbaran: TWideStringField; qproduccion_almacenes_entrada: TIntegerField; qproduccion_almacendesc_calibre: TWideStringField; qproduccion_almacendesc_formato: TWideStringField; qproduccion_almacendesc_envase: TWideStringField; qproduccion_almacenidfactura: TWideStringField; dsqdesechos: TDataSource; qdesechos: TZReadOnlyQuery; dsqdesechosdetalles: TDataSource; qdesechosdetalles: TZReadOnlyQuery; qproduccionsumpeso_neto_teorico: TFloatField; qsalidassumpeso_neto_teorico: TFloatField; dsqinfdesechos: TDataSource; qinfdesechos: TZQuery; qinfdesechosid: TIntegerField; qinfdesechosfecha: TDateField; qinfdesechosfechatrabajo: TDateField; qinfdesechosparcela: TWideStringField; qinfdesechosmprima: TWideStringField; qinfdesechosmprima_p: TWideStringField; qinfdesechosid_envase: TWideStringField; qinfdesechosnum_envases: TIntegerField; qinfdesechoscliente: TWideStringField; qinfdesechosciudad: TWideStringField; qinfdesechospeso_neto: TFloatField; qinfdesechospeso_neto_teorico: TFloatField; qinfdesechospeso_medio: TFloatField; qinfdesechostemperatura: TFloatField; qinfdesechoslote: TIntegerField; qinfdesechosidalbaran: TWideStringField; qdesechosparcela: TWideStringField; qdesechosmprima: TWideStringField; qdesechossumpeso_neto_teorico: TFloatField; qdesechossumpeso_neto: TFloatField; qdesechosdetallesid: TIntegerField; qdesechosdetallesidempresa: TIntegerField; qdesechosdetallesidea: TIntegerField; qdesechosdetallesid_palet: TWideStringField; qdesechosdetallesnum_palets: TIntegerField; qdesechosdetallesid_palet2: TWideStringField; qdesechosdetallesnum_palets2: TIntegerField; qdesechosdetallesid_envase: TWideStringField; qdesechosdetallesnum_envases: TIntegerField; qdesechosdetallesiddestino: TIntegerField; qdesechosdetallesdestino: TWideStringField; qdesechosdetallespeso_bruto: TFloatField; qdesechosdetallestara: TFloatField; qdesechosdetallespeso_neto: TFloatField; qdesechosdetallespeso_neto_teorico: TFloatField; qdesechosdetallespeso_medio: TFloatField; qdesechosdetallestemperatura: TFloatField; qdesechosdetallesfecha: TDateField; qdesechosdetallesfechatrabajo: TDateField; qdesechosdetalleshora: TTimeField; qdesechosdetallesCEA: TWideStringField; qdesechosdetallesresto_cajas: TFloatField; qdesechosdetallesresto_pesoneto: TFloatField; qdesechosdetalleslote: TIntegerField; qdesechosdetallesorigen: TWideStringField; qdesechosdetallesidorigen: TIntegerField; qdesechosdetallesmprima: TWideStringField; qdesechosdetallesmprima_p: TWideStringField; qdesechosdetallesgen_caja: TIntegerField; qdesechosdetallescosto: TFloatField; qdesechosdetallescoste_manipulacion: TFloatField; qdesechosdetallesdias_camara: TIntegerField; qdesechosdetallescosto_camara: TFloatField; qdesechosdetallescodigoR: TWideStringField; qdesechosdetallesparcela: TWideStringField; qdesechosdetallesfecha_cierre: TDateField; qdesechosdetallescosto_materiales: TFloatField; qdesechosdetallescosto_cosechar: TFloatField; qdesechosdetallesborrado: TIntegerField; qdesechosdetallesseleccionado: TIntegerField; qdesechosdetallesobservaciones: TWideStringField; qdesechosdetallestipo_trabajo: TWideStringField; qdesechosdetallestipo_generador: TWideStringField; qdesechosdetallesremanipulado: TIntegerField; qdesechosdetallesfecha_envasado: TDateField; qdesechosdetallescodean: TWideStringField; qdesechosdetallescodssc: TWideStringField; qdesechosdetallespedidocliente: TIntegerField; qdesechosdetallescosto_sinmt: TFloatField; qdesechosdetallesrecuperar_envases: TIntegerField; qdesechosdetallesidalbaran: TWideStringField; qdesechosdetalleses_entrada: TIntegerField; qdesechosdetallesdesc_calibre: TWideStringField; qdesechosdetallesdesc_formato: TWideStringField; qdesechosdetallesdesc_envase: TWideStringField; qdesechosdetallesidfactura: TWideStringField; qcampanyasid: TIntegerField; qcampanyasidempresa: TIntegerField; qcampanyasid_anterior: TIntegerField; qcampanyasdescripcion: TWideStringField; qcampanyasfechainicio: TDateField; qcampanyasfechafin: TDateField; qcampanyasult_pesada: TIntegerField; qproduccion_detallesxx: TZReadOnlyQuery; qproduccion_detallesxxid: TIntegerField; qproduccion_detallesxxidempresa: TIntegerField; qproduccion_detallesxxidea: TIntegerField; qproduccion_detallesxxid_palet: TWideStringField; qproduccion_detallesxxnum_palets: TIntegerField; qproduccion_detallesxxid_palet2: TWideStringField; qproduccion_detallesxxnum_palets2: TIntegerField; qproduccion_detallesxxid_envase: TWideStringField; qproduccion_detallesxxnum_envases: TIntegerField; qproduccion_detallesxxiddestino: TIntegerField; qproduccion_detallesxxdestino: TWideStringField; qproduccion_detallesxxpeso_bruto: TFloatField; qproduccion_detallesxxtara: TFloatField; qproduccion_detallesxxpeso_neto: TFloatField; qproduccion_detallesxxpeso_neto_teorico: TFloatField; qproduccion_detallesxxpeso_medio: TFloatField; qproduccion_detallesxxtemperatura: TFloatField; qproduccion_detallesxxfecha: TDateField; qproduccion_detallesxxfechatrabajo: TDateField; qproduccion_detallesxxhora: TTimeField; qproduccion_detallesxxCEA: TWideStringField; qproduccion_detallesxxresto_cajas: TFloatField; qproduccion_detallesxxresto_pesoneto: TFloatField; qproduccion_detallesxxlote: TIntegerField; qproduccion_detallesxxorigen: TWideStringField; qproduccion_detallesxxidorigen: TIntegerField; qproduccion_detallesxxmprima: TWideStringField; qproduccion_detallesxxmprima_p: TWideStringField; qproduccion_detallesxxgen_caja: TIntegerField; qproduccion_detallesxxcosto: TFloatField; qproduccion_detallesxxcoste_manipulacion: TFloatField; qproduccion_detallesxxdias_camara: TIntegerField; qproduccion_detallesxxcosto_camara: TFloatField; qproduccion_detallesxxcodigoR: TWideStringField; qproduccion_detallesxxparcela: TWideStringField; qproduccion_detallesxxfecha_cierre: TDateField; qproduccion_detallesxxcosto_materiales: TFloatField; qproduccion_detallesxxcosto_cosechar: TFloatField; qproduccion_detallesxxborrado: TIntegerField; qproduccion_detallesxxseleccionado: TIntegerField; qproduccion_detallesxxobservaciones: TWideStringField; qproduccion_detallesxxtipo_trabajo: TWideStringField; qproduccion_detallesxxtipo_generador: TWideStringField; qproduccion_detallesxxremanipulado: TIntegerField; qproduccion_detallesxxfecha_envasado: TDateField; qproduccion_detallesxxcodean: TWideStringField; qproduccion_detallesxxcodssc: TWideStringField; qproduccion_detallesxxpedidocliente: TIntegerField; qproduccion_detallesxxcosto_sinmt: TFloatField; qproduccion_detallesxxrecuperar_envases: TIntegerField; qproduccion_detallesxxidalbaran: TWideStringField; qproduccion_detallesxxes_entrada: TIntegerField; qproduccion_detallesxxdesc_calibre: TWideStringField; qproduccion_detallesxxdesc_formato: TWideStringField; qproduccion_detallesxxdesc_envase: TWideStringField; qproduccion_detallesxxidfactura: TWideStringField; qinfsalidascosto_materiales: TFloatField; qinfsalidascoste_manipulacion: TFloatField; qinfdesechoscosto_materiales: TFloatField; qinfdesechoscoste_manipulacion: TFloatField; qinfentradascosto_materiales: TFloatField; qinfentradascoste_manipulacion: TFloatField; procedure dsqcampanyasDataChange(Sender: TObject; Field: TField); private { Private declarations } public { Public declarations } end; var DMEstadisticas: TDMEstadisticas; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} uses datosproduccion; {$R *.dfm} procedure TDMEstadisticas.dsqcampanyasDataChange(Sender: TObject; Field: TField); begin qproduccion.close; qproduccion.prepare; qproduccion.ParamByName('FINICIO').AsDate:=qcampanyasfechainicio.AsDateTime;//('SELECT parcela,mprima_p as mprima,sum(peso_bruto),sum(peso_neto) FROM v_ea_pesadaslotes'); qproduccion.ParamByName('FFIN').AsDate:=qcampanyasfechaFIN.AsDateTime;//dmestadisticas.qproduccion.sql.Add(' where idea>0 and fecha>='+''''+vfechainicio+''''+' and fecha<='+''''+vfechafin+''''+' group by parcela,mprima_p'); qproduccion.ParamByName('PARCELA').AsString:=dm.qparcelascodpar.AsString; qproduccion.open;//dmestadisticas.qproduccion.Open; dmproduccion.qproduccion_detalles.close; dmproduccion.qproduccion_detalles.prepare; dmproduccion.qproduccion_detalles.ParamByName('FINICIO').AsDate:=qcampanyasfechainicio.AsDateTime;//('SELECT parcela,mprima_p as mprima,sum(peso_bruto),sum(peso_neto) FROM v_ea_pesadaslotes'); dmproduccion.qproduccion_detalles.ParamByName('FFIN').AsDate:=qcampanyasfechaFIN.AsDateTime;//dmestadisticas.qproduccion.sql.Add(' where idea>0 and fecha>='+''''+vfechainicio+''''+' and fecha<='+''''+vfechafin+''''+' group by parcela,mprima_p'); dmproduccion.qproduccion_detalles.ParamByName('PARCELA').AsString:=dm.qparcelascodpar.AsString; dmproduccion.qproduccion_detalles.open; qsalidas.close; qsalidas.prepare; qsalidas.ParamByName('FINICIO').AsDate:=qcampanyasfechainicio.AsDateTime;//('SELECT parcela,mprima_p as mprima,sum(peso_bruto),sum(peso_neto) FROM v_ea_pesadaslotes'); qsalidas.ParamByName('FFIN').AsDate:=qcampanyasfechaFIN.AsDateTime;//dmestadisticas.qsalidas.sql.Add(' where idea>0 and fecha>='+''''+vfechainicio+''''+' and fecha<='+''''+vfechafin+''''+' group by parcela,mprima_p'); qsalidas.ParamByName('PARCELA').AsString:=dm.qparcelascodpar.AsString; qsalidas.open; qsalidasdetalles.close; qsalidasdetalles.prepare; qsalidasdetalles.ParamByName('FINICIO').AsDate:=qcampanyasfechainicio.AsDateTime;//('SELECT parcela,mprima_p as mprima,sum(peso_bruto),sum(peso_neto) FROM v_ea_pesadaslotes'); qsalidasdetalles.ParamByName('FFIN').AsDate:=qcampanyasfechaFIN.AsDateTime;//dmestadisticas.qproduccion.sql.Add(' where idea>0 and fecha>='+''''+vfechainicio+''''+' and fecha<='+''''+vfechafin+''''+' group by parcela,mprima_p'); qsalidasdetalles.ParamByName('PARCELA').AsString:=dm.qparcelascodpar.AsString; qsalidasdetalles.open; qdesechos.close; qdesechos.prepare; qdesechos.ParamByName('FINICIO').AsDate:=qcampanyasfechainicio.AsDateTime;//('SELECT parcela,mprima_p as mprima,sum(peso_bruto),sum(peso_neto) FROM v_ea_pesadaslotes'); qdesechos.ParamByName('FFIN').AsDate:=qcampanyasfechaFIN.AsDateTime;//dmestadisticas.qdesechos.sql.Add(' where idea>0 and fecha>='+''''+vfechainicio+''''+' and fecha<='+''''+vfechafin+''''+' group by parcela,mprima_p'); qdesechos.ParamByName('PARCELA').AsString:=dm.qparcelascodpar.AsString; qdesechos.open; qdesechosdetalles.close; qdesechosdetalles.prepare; qdesechosdetalles.ParamByName('FINICIO').AsDate:=qcampanyasfechainicio.AsDateTime;//('SELECT parcela,mprima_p as mprima,sum(peso_bruto),sum(peso_neto) FROM v_ea_pesadaslotes'); qdesechosdetalles.ParamByName('FFIN').AsDate:=qcampanyasfechaFIN.AsDateTime;//dmestadisticas.qproduccion.sql.Add(' where idea>0 and fecha>='+''''+vfechainicio+''''+' and fecha<='+''''+vfechafin+''''+' group by parcela,mprima_p'); qdesechosdetalles.ParamByName('PARCELA').AsString:=dm.qparcelascodpar.AsString; qdesechosdetalles.open; end; end. ======================================== FICHERO: datosnominas.pas ======================================== unit datosnominas; interface uses System.SysUtils, System.Classes, Data.DB, ZAbstractRODataset, ZDataset, Bde.DBTables; type TDMNominas = class(TDataModule) qempleados: TZReadOnlyQuery; qempleadosid: TSmallintField; qempleadosnombre: TWideStringField; dsqtrabajadores: TDataSource; Query1: TQuery; private { Private declarations } public { Public declarations } end; var DMNominas: TDMNominas; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} end. ======================================== FICHERO: datosproduccion.pas ======================================== unit datosproduccion; interface uses System.SysUtils, System.Classes, Data.DB, ZAbstractRODataset, ZDataset,datos, ZAbstractDataset, ZAbstractTable; type Tdmproduccion = class(TDataModule) dsqcampanyas: TDataSource; qcampanyas: TZReadOnlyQuery; qcampanyasid: TIntegerField; qcampanyasidempresa: TIntegerField; qcampanyasdescripcion: TWideStringField; qcampanyasfechainicio: TDateField; qcampanyasfechafin: TDateField; qclientes: TZReadOnlyQuery; tclientes: TZTable; dsqclientes: TDataSource; dstclientes: TDataSource; dspartesdiarios: TDataSource; dsqsalidas: TDataSource; DataSource5: TDataSource; dsqentradas: TDataSource; qclientesnombre_corto: TWideStringField; tclientesid: TIntegerField; tclientesIdempresa: TIntegerField; tclientesnif: TWideStringField; tclientesnombre: TWideStringField; tclientesnombre_corto: TWideStringField; tclientesdireccion: TWideStringField; tclientespoblacion: TWideStringField; tclientescodpost: TWideStringField; tclientesprovincia: TWideStringField; tclientestelefono: TWideStringField; tclientesemail: TWideStringField; tclientespersonacontacto: TWideStringField; tclientescodigomercado: TIntegerField; tclientesactivo: TIntegerField; qsalidas2: TZReadOnlyQuery; qpartesdiarios: TZQuery; qpartesdiariosid: TIntegerField; qpartesdiariosidempresa: TIntegerField; qpartesdiariosfecha: TDateField; qpartesdiariosalmacen: TIntegerField; qpartesdiariosnombre_almacen: TWideStringField; qpartesdiariosentran_cajas: TIntegerField; qpartesdiariosentran_kg: TFloatField; qpartesdiariosentran_pesomedio: TFloatField; qpartesdiariossalen_cajas: TIntegerField; qpartesdiariossalen_kg: TFloatField; qpartesdiariosstock_cajas: TIntegerField; qpartesdiariosstock_kg: TFloatField; qpartesdiarioshoras_jornales: TFloatField; qpartesdiarioscosto_jornales: TFloatField; qpartesdiarioshoras_jornales_campo: TFloatField; qpartesdiarioscosto_jornales_campo: TFloatField; qpartesdiarioscosto_materiales: TFloatField; qpartesdiarioscoste_kg: TFloatField; qpartesdiarioscosto_kg_mprima: TFloatField; qpartesdiarioscosto_gen_camara: TFloatField; qpartesdiarioscosto_acumulado: TFloatField; qpartesdiariosmermas: TFloatField; qpartesdiarioskg_desperdicios: TFloatField; qpartesdiarioscajas_cierre: TIntegerField; qpartesdiariospeso_cierre: TFloatField; qpartesdiariosestado: TIntegerField; qentradas: TZQuery; qactualizar: TZReadOnlyQuery; dscontrolalmacen: TDataSource; qcontrolalmacen: TZQuery; qcontrolalmacenid: TIntegerField; qcontrolalmacenempresa: TIntegerField; qcontrolalmacenfecha: TDateField; qcontrolalmacenorigen: TWideStringField; qcontrolalmacenlote: TWideStringField; qcontrolalmacenproducto: TWideStringField; qcontrolalmacencantidad_teorica: TIntegerField; qcontrolalmacencantidad_real: TIntegerField; qcontrolalmacenobservaciones: TWideStringField; qpartesdiarioskg_producidos: TFloatField; qsalidas: TZQuery; dsqsalidas2: TDataSource; qentradas2: TZReadOnlyQuery; dsqentradas2: TDataSource; qpartesdiarioscoste_acum_manipulacion: TFloatField; qpartesdiarioskilos_remanipulacion: TFloatField; qpartesdiariosobservaciones: TWideStringField; qpartesdiariossalen_cajas_venta: TIntegerField; qpartesdiarioskg_producidos_venta: TFloatField; qpartesdiariostotal_horas_jornales: TFloatField; qpartesdiarioscoste_ss: TFloatField; qpartesdiariosfecha_traspaso: TDateField; qpartesdiarioscostes_totales: TFloatField; qpartesdiariosrendimiento: TFloatField; qpartesdiarioscostekg_final: TFloatField; qpartesdiariosentran_cajas_remani: TIntegerField; qpartesdiariossalen_envases_desp: TIntegerField; qpartesdiariosentran_peso_medio_remani: TFloatField; qpartesdiariossalen_peso_medio: TFloatField; qpartesdiariossalen_peso_medio_fact: TFloatField; qpartesdiariossalen_pesomedio_desp: TFloatField; qpartesdiarioscosto_kg_mprima_remanip: TFloatField; qpartesdiarioshoras_remanipulacion: TFloatField; qpartesdiarioscoste_corte_remanipu: TFloatField; qpartesdiariostotal_costes_jornales: TFloatField; tdestinos: TZTable; dstdestinos: TDataSource; tdestinosidcliente: TIntegerField; tdestinosidempresa: TIntegerField; tdestinoscodigo: TWideStringField; tdestinosdescripcion: TWideStringField; tdestinosseleccionado: TIntegerField; tdestinosactivo: TIntegerField; tarticulos_clientes: TZTable; dstarticulos_clientes: TDataSource; tarticulos_clientesidempresa: TIntegerField; tarticulos_clientesidcliente: TIntegerField; tarticulos_clientesid: TWideStringField; tarticulos_clientesean: TWideStringField; tarticulos_clientesdesc_cliente: TWideStringField; tarticulos_clientescod_propio: TWideStringField; tarticulos_clientesactivo: TIntegerField; tpedidosclientes: TZTable; IntegerField1: TIntegerField; IntegerField2: TIntegerField; WideStringField1: TWideStringField; WideStringField2: TWideStringField; WideStringField3: TWideStringField; WideStringField4: TWideStringField; IntegerField3: TIntegerField; DataSource1: TDataSource; qpartesdiarioscajas_apertura: TIntegerField; qpartesdiariospeso_apertura: TFloatField; qpartesdiarioscoste_apertura: TFloatField; qpartesdiarioscoste_cierre: TFloatField; qpartesdiariosporc_mermas: TFloatField; qpartesdiarioscoste_limpieza: TFloatField; qpartesdiarioscoste_envasado: TFloatField; qpartesdiarioscoste_apoyo: TFloatField; qpartesdiariosventa_desperdicios: TFloatField; qpartesdiarioscosto_medio_mprima: TFloatField; qpartesdiarioskg_utilizados: TFloatField; qrestos_dia: TZQuery; dsrestos_dia: TDataSource; qrestos_diaid: TIntegerField; qrestos_diaide: TIntegerField; qrestos_diaidalmacen: TIntegerField; qrestos_dialote: TIntegerField; qrestos_diaparcela: TWideStringField; qrestos_diamprima: TWideStringField; qrestos_diafecha: TDateField; qrestos_diacant_inicial: TFloatField; qrestos_diacant_final: TFloatField; qpartesdiarioscostekgfinal_sinmt: TFloatField; dsqsalidaslotes: TDataSource; qsalidaslotes: TZQuery; qpartesdiarioscoste_env_rec: TFloatField; qcalendario_laboral: TZQuery; dscalendario_laboral: TDataSource; qsalidasid: TIntegerField; qsalidasidempresa: TIntegerField; qsalidasidEA: TIntegerField; qsalidasid_palet: TWideStringField; qsalidasnum_palets: TIntegerField; qsalidasid_palet2: TWideStringField; qsalidasnum_palets2: TIntegerField; qsalidasid_envase: TWideStringField; qsalidasnum_envases: TIntegerField; qsalidasiddestino: TIntegerField; qsalidasdestino: TWideStringField; qsalidaspeso_bruto: TFloatField; qsalidastara: TFloatField; qsalidaspeso_neto: TFloatField; qsalidaspeso_neto_teorico: TFloatField; qsalidaspeso_medio: TFloatField; qsalidastemperatura: TFloatField; qsalidasfecha: TDateField; qsalidasfechatrabajo: TDateField; qsalidashora: TTimeField; qsalidasCEA: TWideStringField; qsalidasresto_cajas: TFloatField; qsalidasresto_pesoneto: TFloatField; qsalidaslote: TIntegerField; qsalidasORIGEN: TWideStringField; qsalidasidorigen: TIntegerField; qsalidasmprima: TWideStringField; qsalidasgen_caja: TIntegerField; qsalidascosto: TFloatField; qsalidascoste_manipulacion: TFloatField; qsalidasdias_camara: TIntegerField; qsalidascosto_camara: TFloatField; qsalidascodigoR: TWideStringField; qsalidasparcela: TWideStringField; qsalidasfecha_cierre: TDateField; qsalidascosto_materiales: TFloatField; qsalidascosto_cosechar: TFloatField; qsalidasborrado: TIntegerField; qsalidasseleccionado: TIntegerField; qsalidasOBSERVACIONES: TWideStringField; qsalidastipo_trabajo: TWideStringField; qsalidastipo_generador: TWideStringField; qsalidasremanipulado: TIntegerField; qsalidasfecha_envasado: TDateField; qsalidascodean: TWideStringField; qsalidascodssc: TWideStringField; qsalidaspedidocliente: TIntegerField; qsalidascosto_sinmt: TFloatField; qsalidastara0: TFloatField; qsalidaslotes_detalle: TWideStringField; qsalidasidpedido: TIntegerField; qsalidasidalbaran: TWideStringField; qsalidasrecuperar_envases: TIntegerField; qsalidascalibre: TFloatField; qsalidasprov_albaran: TWideStringField; qsalidasprov_fecha: TDateField; qsalidasprov_ggn: TWideStringField; qsalidasprov_lote: TWideStringField; qsalidasprov_grower: TWideStringField; qsalidasprov_puk: TWideStringField; qsalidasprov_otros: TWideStringField; qsalidasidfactura: TWideStringField; qcalendario_laboralfecha: TDateField; qcalendario_laboralfestivo: TIntegerField; qcalendario_laboralalmuerzo: TIntegerField; qcalendario_laboralmerienda: TIntegerField; qentradas2fechatrabajo: TDateField; qentradas2lote: TIntegerField; qentradas2origen: TWideStringField; qentradas2mprima: TWideStringField; qentradas2num_palets: TLargeintField; qentradas2envases: TLargeintField; qentradas2pesoneto: TFloatField; qentradas2peso_neto_venta: TFloatField; qentradas2iddestino: TIntegerField; qsalidaslotesidorigen: TIntegerField; qsalidaslotesidempresa: TIntegerField; qsalidasloteshora: TTimeField; qsalidaslotesid: TIntegerField; qsalidaslotesidea: TIntegerField; qsalidaslotesid_envase: TWideStringField; qsalidaslotesmprima: TWideStringField; qsalidaslotesnum_envases: TIntegerField; qsalidaslotespeso_neto: TFloatField; qsalidaslotespeso_neto_teorico: TFloatField; qsalidaslotespeso_medio: TFloatField; qsalidaslotesfecha: TDateField; qsalidaslotesdestino: TWideStringField; qsalidasloteslote: TIntegerField; qsalidaslotescodigoR: TWideStringField; qsalidas2fecha: TDateField; qsalidas2lote: TIntegerField; qsalidas2id_envase: TWideStringField; qsalidas2num_palets: TLargeintField; qsalidas2num_envases: TLargeintField; qsalidas2peso_neto: TFloatField; qsalidas2peso_neto_venta: TFloatField; qsalidas2idorigen: TIntegerField; qentradasid: TIntegerField; qentradasidempresa: TIntegerField; qentradasidea: TIntegerField; qentradasid_palet: TWideStringField; qentradasnum_palets: TIntegerField; qentradasid_palet2: TWideStringField; qentradasnum_palets2: TIntegerField; qentradasid_envase: TWideStringField; qentradasnum_envases: TIntegerField; qentradasiddestino: TIntegerField; qentradasdestino: TWideStringField; qentradaspeso_bruto: TFloatField; qentradastara: TFloatField; qentradaspeso_neto: TFloatField; qentradaspeso_neto_teorico: TFloatField; qentradaspeso_medio: TFloatField; qentradastemperatura: TFloatField; qentradasfecha: TDateField; qentradasfechatrabajo: TDateField; qentradashora: TTimeField; qentradasCEA: TWideStringField; qentradasresto_cajas: TFloatField; qentradasresto_pesoneto: TFloatField; qentradaslote: TIntegerField; qentradasorigen: TWideStringField; qentradasidorigen: TIntegerField; qentradasmprima: TWideStringField; qentradasmprima_p: TWideStringField; qentradasgen_caja: TIntegerField; qentradascosto: TFloatField; qentradascoste_manipulacion: TFloatField; qentradasdias_camara: TIntegerField; qentradascosto_camara: TFloatField; qentradascodigoR: TWideStringField; qentradasparcela: TWideStringField; qentradasfecha_cierre: TDateField; qentradascosto_materiales: TFloatField; qentradascosto_cosechar: TFloatField; qentradasborrado: TIntegerField; qentradasseleccionado: TIntegerField; qentradasobservaciones: TWideStringField; qentradastipo_trabajo: TWideStringField; qentradastipo_generador: TWideStringField; qentradasremanipulado: TIntegerField; qentradasfecha_envasado: TDateField; qentradascodean: TWideStringField; qentradascodssc: TWideStringField; qentradaspedidocliente: TIntegerField; qentradascosto_sinmt: TFloatField; qentradasrecuperar_envases: TIntegerField; qentradasidalbaran: TWideStringField; qentradases_entrada: TIntegerField; qentradasdesc_calibre: TWideStringField; qentradasdesc_formato: TWideStringField; qentradasdesc_envase: TWideStringField; qentradasidfactura: TWideStringField; qsalen: TZReadOnlyQuery; qsalennum_envases: TLargeintField; qsalenpeso_neto: TFloatField; qsalenpeso_neto_venta: TFloatField; qdesperdicios: TZReadOnlyQuery; qdesperdiciosnum_envases: TLargeintField; qdesperdiciospeso_neto: TFloatField; qdesperdiciospeso_neto_venta: TFloatField; qentran: TZReadOnlyQuery; qentrannum_envases: TLargeintField; qentranpeso_neto: TFloatField; qentranpeso_neto_venta: TFloatField; qcalendario_laboralinicio_almuerzo: TTimeField; qcalendario_laboralfin_almuerzo: TTimeField; qcalendario_laboralinicio_merienda: TTimeField; qcalendario_laboralfin_merienda: TTimeField; qproduccion_detalles: TZReadOnlyQuery; dsqproducciondetalle: TDataSource; qproduccion_detallesid: TIntegerField; qproduccion_detallesidempresa: TIntegerField; qproduccion_detallesidea: TIntegerField; qproduccion_detallesid_palet: TWideStringField; qproduccion_detallesnum_palets: TIntegerField; qproduccion_detallesid_palet2: TWideStringField; qproduccion_detallesnum_palets2: TIntegerField; qproduccion_detallesid_envase: TWideStringField; qproduccion_detallesnum_envases: TIntegerField; qproduccion_detallesiddestino: TIntegerField; qproduccion_detallesdestino: TWideStringField; qproduccion_detallespeso_bruto: TFloatField; qproduccion_detallestara: TFloatField; qproduccion_detallespeso_neto: TFloatField; qproduccion_detallespeso_neto_teorico: TFloatField; qproduccion_detallespeso_medio: TFloatField; qproduccion_detallestemperatura: TFloatField; qproduccion_detallesfecha: TDateField; qproduccion_detallesfechatrabajo: TDateField; qproduccion_detalleshora: TTimeField; qproduccion_detallesCEA: TWideStringField; qproduccion_detallesresto_cajas: TFloatField; qproduccion_detallesresto_pesoneto: TFloatField; qproduccion_detalleslote: TIntegerField; qproduccion_detallesorigen: TWideStringField; qproduccion_detallesidorigen: TIntegerField; qproduccion_detallesmprima: TWideStringField; qproduccion_detallesmprima_p: TWideStringField; qproduccion_detallesgen_caja: TIntegerField; qproduccion_detallescosto: TFloatField; qproduccion_detallescoste_manipulacion: TFloatField; qproduccion_detallesdias_camara: TIntegerField; qproduccion_detallescosto_camara: TFloatField; qproduccion_detallescodigoR: TWideStringField; qproduccion_detallesparcela: TWideStringField; qproduccion_detallesfecha_cierre: TDateField; qproduccion_detallescosto_materiales: TFloatField; qproduccion_detallescosto_cosechar: TFloatField; qproduccion_detallesborrado: TIntegerField; qproduccion_detallesseleccionado: TIntegerField; qproduccion_detallesobservaciones: TWideStringField; qproduccion_detallestipo_trabajo: TWideStringField; qproduccion_detallestipo_generador: TWideStringField; qproduccion_detallesremanipulado: TIntegerField; qproduccion_detallesfecha_envasado: TDateField; qproduccion_detallescodean: TWideStringField; qproduccion_detallescodssc: TWideStringField; qproduccion_detallespedidocliente: TIntegerField; qproduccion_detallescosto_sinmt: TFloatField; qproduccion_detallesrecuperar_envases: TIntegerField; qproduccion_detallesidalbaran: TWideStringField; qproduccion_detalleses_entrada: TIntegerField; qproduccion_detallesdesc_calibre: TWideStringField; qproduccion_detallesdesc_formato: TWideStringField; qproduccion_detallesdesc_envase: TWideStringField; qproduccion_detallesidfactura: TWideStringField; procedure dsqcampanyasDataChange(Sender: TObject; Field: TField); procedure dspartesdiariosDataChange(Sender: TObject; Field: TField); procedure qrestos_diaAfterPost(DataSet: TDataSet); private { Private declarations } public { Public declarations } end; var dmproduccion: Tdmproduccion; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} uses principal,fechacierre; {$R *.dfm} procedure Tdmproduccion.dspartesdiariosDataChange(Sender: TObject; Field: TField); var diasemana,tdia,tmes,tanyo,fecha,fecha2:string; diasem,valmacen,vempresa:integer; dia,mes,anyo:word; vfecha:tdatetime; begin vfecha:=qpartesdiariosfecha.AsDateTime; valmacen:=qpartesdiariosalmacen.AsInteger; vempresa:=qpartesdiariosidempresa.asinteger; decodedate(qpartesdiariosfecha.AsDateTime,anyo,mes,dia); fecha:=''''+inttostr(anyo)+'-'+inttostr(mes)+'-'+inttostr(dia)+''''; fecha2:=inttostr(anyo)+'-'+inttostr(mes)+'-'+inttostr(dia); if qpartesdiariosestado.AsInteger=1 then begin base.btcerrar.Visible:=false; base.bticierre.Visible:=true; base.dbfechatraspaso.Visible:=true; base.ffechatraspaso.Visible:=false; end else begin base.btcerrar.Visible:=true; base.bticierre.Visible:=false; base.dbfechatraspaso.Visible:=false; base.ffechatraspaso.Visible:=true; base.ffechatraspaso.date:=qpartesdiariosfecha.asdatetime+1; end; diasem:=dayofweek(qpartesdiariosfecha.AsDateTime); case diasem of 1 : diasemana:='DOMINGO'; 2 : diasemana:='LUNES'; 3 : diasemana:='MARTES'; 4 : diasemana:='MIERCOLES'; 5 : diasemana:='JUEVES'; 6 : diasemana:='VIERNES'; 7 : diasemana:='SABADO'; end; base.Panel100.Caption:='Control de producción del '+diasemana+' '+qpartesdiariosfecha.AsString; qentradas2.Close; qentradas2.Prepare; qentradas2.ParamByName('ALMACEN').AsInteger:=valmacen;//qpartesdiariosalmacen.asinteger; qentradas2.ParamByName('FECHA').AsDate:=vfecha;//qpartesdiariosfecha.asdatetime; // qentradas2.SQL.Clear; // qentradas2.SQL.Add('SELECT fechatrabajo,ea.lote,origen,ea.mprima,sum(num_palets) as num_palets,sum(ea.num_envases) as envases,sum(ea.pesoneto),sum(ea.peso_neto_venta),iddestino FROM v_ea_pesadaslotes ea '); // qentradas2.SQL.add(' ea.iddestino<>0 and ea.idorigen<>ea.iddestino and ea.idorigen=4 and (ea.fecha='2022-12-27' or ea.fechatrabajo='2022-12-27') and ea.idea<=0 order by id desc; qentradas2.Open; qentradas.Close; qentradas.Prepare; qentradas.ParamByName('ALMACEN').AsInteger:=valmacen;//qpartesdiariosalmacen.asinteger; qentradas.ParamByName('FECHA').AsDate:=vfecha;//qpartesdiariosfecha.asdatetime; // qentradas.SQL.Clear; // qentradas.SQL.Add('select * from v_ea_pesadaslotes ea where ea.iddestino='+qpartesdiariosalmacen.AsString+' and ea.fechatrabajo='+fecha+' order by id desc'); qentradas.Open; qsalidas2.Close; qsalidas2.Prepare; qsalidas2.ParamByName('ALMACEN').AsInteger:=valmacen;//qpartesdiariosalmacen.asinteger; qsalidas2.ParamByName('FECHA').AsDate:=vfecha;//qpartesdiariosfecha.asdatetime; // qsalidas2.SQL.Clear; // qsalidas2.SQL.Add('select fecha,lp.lote,ea.id_envase,sum(num_palets) as num_palets,sum(lp.cajas) as num_envases,sum(lp.pesoneto_real) as peso_neto,sum(lp.pesoneto_teorico) as peso_neto_venta,idorigen from ea_pesadas ea,lotes_pesadas lp '); // qsalidas2.SQL.Add(' where ea.iddestino<>0 and ea.idorigen<>ea.iddestino and ea.idorigen='+qpartesdiariosalmacen.AsString+' and (ea.fecha='+fecha+' or ea.fechatrabajo='+fecha+') and lp.idea2=ea.idea and ea.idempresa=lp.ide and ea.id=lp.idea and ea.idea<=0 group by fecha, idorigen,id_envase,lote order by fecha desc,lote,id_envase desc');//(ea.fecha='+fecha+' or ea.fechatrabajo='+fecha+') qsalidas2.Open; qsalidaslotes.Close; qsalidaslotes.Prepare; qsalidaslotes.ParamByName('ALMACEN').AsInteger:=valmacen;//qpartesdiariosalmacen.asinteger; qsalidaslotes.ParamByName('FECHA').AsDate:=vfecha;//qpartesdiariosfecha.asdatetime; // qsalidaslotes.SQL.Clear; // qsalidaslotes.SQL.Add('select ea.idorigen,ea.idempresa,ea.hora,ea.id,ea.id_envase,lp.mprima,lp.cajas as num_envases,lp.pesoneto_real as peso_neto,lp.pesoneto_teorico as peso_neto_teorico,ea.peso_medio,ea.fecha,ea.destino,lp.lote,ea.codigoR '); // qsalidaslotes.sql.Add(' from ea_pesadas ea,lotes_pesadas lp where ea.iddestino<>0 and ea.idorigen<>ea.iddestino and ea.idorigen='+qpartesdiariosalmacen.AsString+' and (ea.fecha='+fecha+' or ea.fechatrabajo='+fecha+') and ea.idempresa=lp.ide and ea.id=lp.idea and ea.idea=lp.idea2 and ea.idea<=0 order by id desc');//(ea.fecha='+fecha+' or ea.fechatrabajo='+fecha+') qsalidaslotes.Open; decodedate(qpartesdiariosfecha.AsDateTime,anyo,mes,dia); qrestos_dia.close; qrestos_dia.Prepare; qrestos_dia.ParamByName('EMPRESA').AsInteger:=vempresa; qrestos_dia.ParamByName('ALMACEN').AsInteger:=valmacen; qrestos_dia.ParamByName('FECHA').Asdate:=vfecha; // qrestos_dia.sql.Clear; // qrestos_dia.SQL.Add('select * from restos_dia where ide='+qpartesdiariosidempresa.AsString+' and fecha='+fecha+' and idalmacen='+qpartesdiariosalmacen.AsString+' order by lote'); qrestos_dia.Open; qcalendario_laboral.close; qcalendario_laboral.ParamByName('FECHA').Asdate:=vfecha; qcalendario_laboral.Prepare; qcalendario_laboral.Open; end; procedure Tdmproduccion.dsqcampanyasDataChange(Sender: TObject; Field: TField); var anyo,mes,dia:word; vfechainicio,vfechafin,vanyo,vanyosig,vmes,vmessig,vdia:string; begin decodedate(dmproduccion.qcampanyasfechainicio.AsDateTime,anyo,mes,dia); vanyo:=floattostr(anyo); vanyosig:=floattostr(anyo); vmes:=floattostr(mes); vdia:=floattostr(dia); if length(vmes)=1 then vmes:='0'+vmes; if length(vdia)=1 then vdia:='0'+vdia; vfechainicio:=floattostr(anyo)+'-'+vmes+'-'+vdia; decodedate(dmproduccion.qcampanyasfechafin.AsDateTime,anyo,mes,dia); vanyo:=floattostr(anyo); vanyosig:=floattostr(anyo); vmes:=floattostr(mes); vdia:=floattostr(dia); if length(vmes)=1 then vmes:='0'+vmes; if length(vdia)=1 then vdia:='0'+vdia; vfechafin:=floattostr(anyo)+'-'+vmes+'-'+vdia; { dmproduccion.qproduccion.Close; dmproduccion.qproduccion.sql.Clear; dmproduccion.qproduccion.sql.Add('SELECT idorigen,origen,mprima,sum(peso_bruto),sum(peso_neto) FROM ea_pesadas'); dmproduccion.qproduccion.sql.Add(' where fecha>='+''''+vfechainicio+''''+' and fecha<='+''''+vfechafin+''''+' group by origen,mprima'); dmproduccion.qproduccion.Open; dmproduccion.qproduccion_detalle.Close; dmproduccion.qproduccion_detalle.sql.Clear; dmproduccion.qproduccion_detalle.sql.Add('SELECT * FROM ea_pesadas'); dmproduccion.qproduccion_detalle.sql.Add(' where fecha>='+''''+vfechainicio+''''+' and fecha<='+''''+vfechafin+''''+' order by id'); dmproduccion.qproduccion_detalle.Open;} end; procedure Tdmproduccion.qrestos_diaAfterPost(DataSet: TDataSet); var observaciones:string; cajas,idpartediario,idrestodia:integer; kilos,coste:real; anyo,mes,dia:word; vanyo,vmes,vdia,vmessig,vfecha,tcajas,tkilos,tcoste:string; begin decodedate(dmproduccion.qrestos_diafecha.asdatetime,anyo,mes,dia); vanyo:=floattostr(anyo); vmes:=floattostr(mes); vmessig:=floattostr(mes+1); vmes:=floattostr(mes); vmessig:=floattostr(mes+1); vdia:=floattostr(dia); vfecha:=vanyo+'-'+vmes+'-'+vdia; observaciones:=''; cajas:=0; kilos:=0; { if dmproduccion.qrestos_diacant_final.AsInteger=0 then begin dmproduccion.qactualizar.sql.clear; dmproduccion.qactualizar.sql.add('select * from restos_dia where lote='+dmproduccion.qrestos_dialote.asstring+' and fecha>'+''''+vfecha+''''); dmproduccion.qactualizar.open; if dmproduccion.qactualizar.RecordCount>0 then begin dmproduccion.qactualizar.sql.clear; dmproduccion.qactualizar.sql.add('delete from restos_dia where lote='+dmproduccion.qrestos_dialote.AsString+' and fecha>'+''''+vfecha+''''); dmproduccion.qactualizar.ExecSQL; end; end; } if dmproduccion.qrestos_diacant_final.AsInteger>0 then begin { dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add('select sum(peso_neto)/sum(num_envases) as media from ea_pesadas where idea>0 and lote='+dmproduccion.qrestos_dialote.AsString); dm.qaux1.Open;} preguntarfecha := Tpreguntarfecha.Create(nil); try preguntarfecha.showmodal; finally preguntarfecha.Free; end; end; dmproduccion.qrestos_dia.First; while not dmproduccion.qrestos_dia.Eof do begin if dmproduccion.qrestos_diacant_final.AsInteger>0 then begin observaciones:=observaciones+dmproduccion.qrestos_diacant_final.AsString+' lote:'+dmproduccion.qrestos_dialote.AsString+' '+dmproduccion.qrestos_diamprima.AsString+'-'; end; dmproduccion.qrestos_dia.Next; end; dm.qaux.sql.clear; dm.qaux.sql.add('select sum(bultos),sum(peso_mprima),sum(costetotal) from v_costesrestosdia where fecha=:FECHA and idalmacen=:ALMACEN'); dm.qaux.Prepare; dm.qaux.ParamByName('FECHA').AsDateTime:=dmproduccion.qrestos_diafecha.asdatetime; dm.qaux.ParamByName('ALMACEN').AsInteger:=dmproduccion.qrestos_diaidalmacen.AsInteger; dm.qaux.Open; cajas:=dm.qaux.Fields[0].AsInteger; coste:=dm.qaux.Fields[2].Asfloat; kilos:=dm.qaux.Fields[1].Asfloat; tcajas:=inttostr(cajas); tcoste:=floattostr(coste); tcoste:=StringReplace(tcoste, ',', '.',[rfReplaceAll, rfIgnoreCase]); tkilos:=floattostr(kilos); tkilos:=StringReplace(tkilos, ',', '.',[rfReplaceAll, rfIgnoreCase]); idpartediario:=dmproduccion.qpartesdiariosid.AsInteger; dm.qaux.sql.clear; dm.qaux.sql.add('update almacenes_partesdiarios set observaciones='+''''+observaciones+''''+',cajas_cierre='+tcajas+',peso_cierre='+tkilos+',coste_cierre='+tcoste+' where id='+inttostr(idpartediario)); dm.qaux.execsql; { dmproduccion.qpartesdiarios.Edit; dmproduccion.qpartesdiarioscajas_cierre.Value:=cajas; dmproduccion.qpartesdiariospeso_cierre.Value:=kilos; dmproduccion.qpartesdiarioscoste_cierre.Value:=coste; dmproduccion.qpartesdiariosobservaciones.Value:=observaciones; dmproduccion.qpartesdiarios.Post;} dmproduccion.qpartesdiarios.Refresh; dmproduccion.qpartesdiarios.Locate('id',idpartediario,[locaseinsensitive]); end; end. ======================================== FICHERO: datostrazabilidad.pas ======================================== unit datostrazabilidad; interface uses System.SysUtils, System.Classes,datos, Data.DB, ZAbstractRODataset, ZAbstractDataset, ZAbstractTable, ZDataset; type TDMTr2 = class(TDataModule) procedure dsqcampanyasDataChange(Sender: TObject; Field: TField); procedure documentos_tmpBeforePost(DataSet: TDataSet); procedure documentos_tmpAfterPost(DataSet: TDataSet); procedure dsqlotesDataChange(Sender: TObject; Field: TField); private { Private declarations } public { Public declarations } end; var DMTr2: TDMTr2; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} uses principal; {$R *.dfm} procedure TDMTr2.documentos_tmpAfterPost(DataSet: TDataSet); begin // base.btdnuevo.SetFocus; end; procedure TDMTr2.documentos_tmpBeforePost(DataSet: TDataSet); var archivo:TMemorystream; ext,nomarchivo: string; begin // archivo.loadFromFile(dialoglotes.FileName); // dmtr.documentos.Post; end; procedure TDMTr2.dsqcampanyasDataChange(Sender: TObject; Field: TField); begin { qlotes.close; qlotes.Open; base.combocampanyas.KeyValue:=qcampanyasdescripcion.asstring;} end; procedure TDMTr2.dsqlotesDataChange(Sender: TObject; Field: TField); begin // base.Paneldocumentos.Visible:=false; end; end. ======================================== FICHERO: datostrazabilidad2.pas ======================================== unit datostrazabilidad2; interface uses System.SysUtils, System.Classes, Data.DB, ZAbstractTable, ZDataset, ZAbstractDataset, ZAbstractRODataset; type Tdmtr = class(TDataModule) dsqcampanyas: TDataSource; qcampanyas: TZReadOnlyQuery; dsqlotes: TDataSource; qlotes: TZQuery; qpartidas: TZReadOnlyQuery; qentradas: TZReadOnlyQuery; qpedidos: TZReadOnlyQuery; qtratamientos2: TZReadOnlyQuery; dsqpartidas: TDataSource; dsqentradas: TDataSource; dsqea_pesadas: TDataSource; dsqsalidas: TDataSource; dsqpedidos: TDataSource; dsqtratamientos: TDataSource; qea_pesadas: TZQuery; qsalidas: TZQuery; qaux: TZReadOnlyQuery; qtiposgenerador: TZReadOnlyQuery; qtiposgeneradoridempresa: TIntegerField; qtiposgeneradorid: TIntegerField; qtiposgeneradorcodigo: TWideStringField; qtiposgeneradordescripcion: TWideStringField; qtiposgeneradorfamilia: TIntegerField; dsqtiposgenerador: TDataSource; dsqsalidas_sd: TDataSource; qsalidas_sd: TZQuery; dsqsalidas_ds: TDataSource; qsalidas_ds: TZQuery; dsqinfentradas: TDataSource; qinfentradas: TZQuery; documentos_tmp: TZTable; qdocumentos: TZQuery; qcampanyasid: TIntegerField; qcampanyasidempresa: TIntegerField; qcampanyasid_anterior: TIntegerField; qcampanyasdescripcion: TWideStringField; qcampanyasfechainicio: TDateField; qcampanyasfechafin: TDateField; qcampanyasult_pesada: TIntegerField; qlotesid: TIntegerField; qlotesidempresa: TIntegerField; qlotescodigo: TIntegerField; qlotesfechaini_trabajo: TDateField; qlotesfechafin_trabajo: TDateField; qlotesfecha: TDateField; qlotesfecha_caducidad: TDateField; qlotesPARCELA: TWideStringField; qlotesPRODUCTOR: TWideStringField; qlotesPAISORIGEN: TWideStringField; qlotesMPRIMA: TWideStringField; qlotesnum_generadores: TIntegerField; qlotestipo_generador: TWideStringField; qlotesdesc_generador: TWideStringField; qloteslote_proveedor: TWideStringField; qlotesentran_teoricos: TFloatField; qlotesentran_reales: TFloatField; qlotessalen_teoricos: TFloatField; qlotessalen_reales: TFloatField; qlotesmerma: TFloatField; qlotesporc_merma: TFloatField; qlotesdesperdicios: TFloatField; qlotestrazabilidad: TWideStringField; qlotesobservaciones: TWideStringField; qlotespropietario: TIntegerField; qlotesresultado: TFloatField; qpartidasid: TIntegerField; qpartidaside: TIntegerField; qpartidasfecha: TDateField; qpartidasid_parcela: TWideStringField; qpartidasid_mprimas: TWideStringField; qpartidaslote: TIntegerField; qentradasid: TIntegerField; qentradaside: TIntegerField; qentradasfecha: TDateField; qentradashora: TTimeField; qentradaspartida: TIntegerField; qentradasnum_palets: TIntegerField; qentradasnum_cajas: TIntegerField; qentradaspeso_bruto: TFloatField; qentradaspeso_neto: TFloatField; qentradaspeso_medio: TFloatField; qentradasmatricula: TWideStringField; qentradasmprima: TWideStringField; qea_pesadasid: TIntegerField; qea_pesadasidempresa: TIntegerField; qea_pesadasidea: TIntegerField; qea_pesadasid_palet: TWideStringField; qea_pesadasnum_palets: TIntegerField; qea_pesadasid_palet2: TWideStringField; qea_pesadasnum_palets2: TIntegerField; qea_pesadasid_envase: TWideStringField; qea_pesadasnum_envases: TIntegerField; qea_pesadasiddestino: TIntegerField; qea_pesadasdestino: TWideStringField; qea_pesadaspeso_bruto: TFloatField; qea_pesadastara: TFloatField; qea_pesadaspeso_neto: TFloatField; qea_pesadaspeso_neto_teorico: TFloatField; qea_pesadaspeso_medio: TFloatField; qea_pesadastemperatura: TFloatField; qea_pesadasfecha: TDateField; qea_pesadasfechatrabajo: TDateField; qea_pesadashora: TTimeField; qea_pesadasCEA: TWideStringField; qea_pesadasresto_cajas: TFloatField; qea_pesadasresto_pesoneto: TFloatField; qea_pesadaslote: TIntegerField; qea_pesadasorigen: TWideStringField; qea_pesadasidorigen: TIntegerField; qea_pesadasmprima: TWideStringField; qea_pesadasmprima_p: TWideStringField; qea_pesadasgen_caja: TIntegerField; qea_pesadascosto: TFloatField; qea_pesadascoste_manipulacion: TFloatField; qea_pesadasdias_camara: TIntegerField; qea_pesadascosto_camara: TFloatField; qea_pesadascodigoR: TWideStringField; qea_pesadasparcela: TWideStringField; qea_pesadasfecha_cierre: TDateField; qea_pesadascosto_materiales: TFloatField; qea_pesadascosto_cosechar: TFloatField; qea_pesadasborrado: TIntegerField; qea_pesadasseleccionado: TIntegerField; qea_pesadasobservaciones: TWideStringField; qea_pesadastipo_trabajo: TWideStringField; qea_pesadastipo_generador: TWideStringField; qea_pesadasremanipulado: TIntegerField; qea_pesadasfecha_envasado: TDateField; qea_pesadascodean: TWideStringField; qea_pesadascodssc: TWideStringField; qea_pesadaspedidocliente: TIntegerField; qea_pesadascosto_sinmt: TFloatField; qea_pesadasrecuperar_envases: TIntegerField; qea_pesadasidalbaran: TWideStringField; qea_pesadases_entrada: TIntegerField; qea_pesadasdesc_calibre: TWideStringField; qea_pesadasdesc_formato: TWideStringField; qea_pesadasdesc_envase: TWideStringField; qea_pesadasidfactura: TWideStringField; qsalidasid: TIntegerField; qsalidasfecha: TDateField; qsalidasfechatrabajo: TDateField; qsalidasorigen: TWideStringField; qsalidasparcela: TWideStringField; qsalidasdestino: TWideStringField; qsalidasmprima: TWideStringField; qsalidasmprima_p: TWideStringField; qsalidascosto: TFloatField; qsalidasid_palet: TWideStringField; qsalidasnum_palets: TIntegerField; qsalidasid_envase: TWideStringField; qsalidasnum_envases: TIntegerField; qsalidasgen_caja: TIntegerField; qsalidastipo_generador: TWideStringField; qsalidaspedidocliente: TIntegerField; qsalidascliente: TWideStringField; qsalidasciudad: TWideStringField; qsalidaspeso_bruto: TFloatField; qsalidaspeso_neto: TFloatField; qsalidaspeso_neto_teorico: TFloatField; qsalidaspeso_medio: TFloatField; qsalidastemperatura: TFloatField; qsalidaslote: TIntegerField; qsalidasidalbaran: TWideStringField; qsalidasidfactura: TWideStringField; qinfentradasid: TIntegerField; qinfentradasfecha: TDateField; qinfentradasfechatrabajo: TDateField; qinfentradasparcela: TWideStringField; qinfentradasmprima: TWideStringField; qinfentradasid_envase: TWideStringField; qinfentradasnum_envases: TIntegerField; qinfentradascliente: TWideStringField; qinfentradasciudad: TWideStringField; qinfentradaspeso_bruto: TFloatField; qinfentradaspeso_neto: TFloatField; qinfentradaspeso_neto_teorico: TFloatField; qinfentradaspeso_medio: TFloatField; qinfentradastemperatura: TFloatField; qinfentradaslote: TIntegerField; qinfentradasidalbaran: TWideStringField; qinfentradaspedidocliente: TIntegerField; qinfentradasdesc_calibre: TWideStringField; qinfentradasdesc_formato: TWideStringField; qinfentradasidfactura: TWideStringField; qsalidas_sdid: TIntegerField; qsalidas_sdfecha: TDateField; qsalidas_sdfechatrabajo: TDateField; qsalidas_sdparcela: TWideStringField; qsalidas_sdmprima: TWideStringField; qsalidas_sdid_envase: TWideStringField; qsalidas_sdnum_envases: TIntegerField; qsalidas_sdcliente: TWideStringField; qsalidas_sdciudad: TWideStringField; qsalidas_sdpeso_neto: TFloatField; qsalidas_sdpeso_neto_teorico: TFloatField; qsalidas_sdpeso_medio: TFloatField; qsalidas_sdtemperatura: TFloatField; qsalidas_sdlote: TIntegerField; qsalidas_sdidalbaran: TWideStringField; qsalidas_sdpedidocliente: TIntegerField; qsalidas_sddesc_calibre: TWideStringField; qsalidas_sddesc_formato: TWideStringField; qsalidas_sdidfactura: TWideStringField; qsalidas_dsid: TIntegerField; qsalidas_dsfecha: TDateField; qsalidas_dsfechatrabajo: TDateField; qsalidas_dsparcela: TWideStringField; qsalidas_dsmprima: TWideStringField; qsalidas_dsid_envase: TWideStringField; qsalidas_dsnum_envases: TIntegerField; qsalidas_dscliente: TWideStringField; qsalidas_dsciudad: TWideStringField; qsalidas_dspeso_neto: TFloatField; qsalidas_dspeso_neto_teorico: TFloatField; qsalidas_dspeso_medio: TFloatField; qsalidas_dstemperatura: TFloatField; qsalidas_dslote: TIntegerField; qsalidas_dsidalbaran: TWideStringField; qsalidas_dspedidocliente: TIntegerField; qsalidas_dsdesc_calibre: TWideStringField; qsalidas_dsdesc_formato: TWideStringField; qsalidas_dsidfactura: TWideStringField; 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; documentos_tmpidaf: TIntegerField; qdocumentosid: TIntegerField; qdocumentoside: TIntegerField; qdocumentosfecha: TDateField; qdocumentosdescripcion: TWideStringField; qdocumentosarchivo: TBlobField; qdocumentosnomarchivo: TWideStringField; qdocumentosextension: TWideStringField; qdocumentosidlote: TIntegerField; qdocumentoscodpar: TWideStringField; qdocumentosidea: TIntegerField; qdocumentosidt: TIntegerField; qdocumentosidaf: TIntegerField; qsalidascoste_manipulacion: TFloatField; qsalidascosto_materiales: TFloatField; qsalidas_sdcoste_manipulacion: TFloatField; qsalidas_sdcosto_materiales: TFloatField; qlotessgg: TWideStringField; qlotessdop: TWideStringField; qlotessigp: TWideStringField; qlotessifs: TWideStringField; qlotessbrc: TWideStringField; procedure dsqlotesDataChange(Sender: TObject; Field: TField); procedure qlotesBeforeOpen(DataSet: TDataSet); procedure dsqcampanyasDataChange(Sender: TObject; Field: TField); private { Private declarations } public { Public declarations } end; var dmtr: Tdmtr; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} uses principal; {$R *.dfm} procedure Tdmtr.dsqcampanyasDataChange(Sender: TObject; Field: TField); begin qlotes.close; qlotes.Open; base.combocampanyas.KeyValue:=qcampanyasdescripcion.asstring; end; procedure Tdmtr.dsqlotesDataChange(Sender: TObject; Field: TField); begin if qlotes.State in [dsedit,dsbrowse] then begin qsalidas.Close; qsalidas.ParamByName('LOTE').AsString:=qlotescodigo.AsString; qsalidas.Prepare; qsalidas.Open; qea_pesadas.Close; qea_pesadas.ParamByName('LOTE').AsString:=qlotescodigo.AsString; qea_pesadas.Prepare; qea_pesadas.Open; qdocumentos.Close; qdocumentos.SQL.Clear; qdocumentos.sql.Add('select * from documentos where ide='+qlotesidempresa.asstring+' and idlote='+qlotescodigo.AsString+' order by fecha desc'); qdocumentos.open; end; end; procedure Tdmtr.qlotesBeforeOpen(DataSet: TDataSet); var filtro:string; anyo,mes,dia:word; fechainicio,fechafin,parcela:string; begin decodedate(qcampanyasfechainicio.AsDateTime,anyo,mes,dia); fechainicio:=''''+floattostr(anyo)+'-'+floattostr(mes)+'-'+floattostr(dia)+''''; decodedate(qcampanyasfechafin.AsDateTime,anyo,mes,dia); fechafin:=''''+floattostr(anyo)+'-'+floattostr(mes)+'-'+floattostr(dia)+''''; { if filtrolotes<>'' then begin filtro:=filtro+ ' where fecha>='+fechainicio+' and fecha<='+fechafin+' and parcela like('+''''+filtrolotes+''''+') or trazabilidad like('+''''+filtrolotes+''''+')'; end; if filtrolotes='' then begin filtro:=' where fecha>='+fechainicio+' and fecha<='+fechafin; end; qlotes.SQL.Clear; qlotes.SQL.Add('select * from lotes ' + filtro +' order by codigo desc') } qlotes.Prepare; qlotes.ParamByName('DESDE').AsDate:=qcampanyasfechainicio.asdatetime; qlotes.ParamByName('HASTA').AsDate:=qcampanyasfechafin.asdatetime; if filtrolotes='' then parcela:='%' else parcela:=filtrolotes; qlotes.ParamByName('PARCELA').Asstring:=parcela; end; end. ======================================== FICHERO: DemoButtonsForm.pas ======================================== { DemoButtonsForm.pas Controlling program for the DemoButtons program which allow user to input a signature on an STU and reproduces it on a Window on the PC. Allows signature to be saved to file on disk Copyright (c) 2015 Wacom GmbH. All rights reserved. } unit DemoButtonsForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, wgssSTU_TLB, SignatureForm; type TForm1 = class(TForm) Button1: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1 : TForm1; implementation {$R *.dfm} procedure TForm1.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 Form2.connect(usbDevice); Form2.ShowModal(); end; except on e : Exception do ShowMessage(e.Message); end; end else begin ShowMessage('No STU devices attached'); end; end; end. ======================================== FICHERO: dlgduplicar.pas ======================================== unit dlgduplicar; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, Vcl.StdCtrls, Vcl.Mask, Vcl.DBCtrls; type Tfdlgduplicar = class(TForm) comboserie: TDBLookupComboBox; Label1: TLabel; Label4: TLabel; Label5: TLabel; Label2: TLabel; Button1: TButton; dsqseries: TDataSource; qseries: TZQuery; qaux: TZQuery; qserieside: TIntegerField; qseriesid: TWideStringField; qseriesfechainicio: TDateField; qseriesfechafin: TDateField; qseriesnum_pedcliente: TIntegerField; qseriesnum_albaran: TIntegerField; qseriesnum_factura: TIntegerField; qseriesnum_expedicion: TIntegerField; qseriesnum_pedproveedor: TIntegerField; qseriesimp_albaran: TWideStringField; qseriesimp_factura: TWideStringField; qseriesactivo: TIntegerField; qseriesnum_presupuesto: TIntegerField; Edit1: TEdit; qseriesseriecontable: TWideStringField; MaskEdit1: TMaskEdit; procedure Button1Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure dsqseriesDataChange(Sender: TObject; Field: TField); private { Private declarations } public { Public declarations } end; var fdlgduplicar: Tfdlgduplicar; idserie,idalbaran,fecha,idempresa:string; desdepedidos:integer; implementation {$R *.dfm} uses falbaranes; procedure Tfdlgduplicar.Button1Click(Sender: TObject); var newserie,newnumalbaran,newfecha:string; anyo,mes,dia:word; begin if desdepedidos=1 then begin end else begin decodedate(strtodate(maskedit1.Text),anyo,mes,dia); newfecha:=inttostr(anyo)+'-'+inttostr(mes)+'-'+inttostr(dia); qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('delete from albaranes_tmp'); qaux.ExecSQL; qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('delete from albaranes_detalles_tmp'); qaux.ExecSQL; qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('insert into albaranes_tmp (select * from albaranes where id='+idalbaran+' and serie='+''''+idserie+''''+' and idempresa='+idempresa+')'); qaux.ExecSQL; qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('insert into albaranes_detalles_tmp (select * from albaranes_detalles where idalbaran='+idalbaran+' and serie='+''''+idserie+''''+' and idempresa='+idempresa+')'); qaux.ExecSQL; newserie:=qseriesid.AsString; newnumalbaran:=qseriesnum_albaran.AsString; qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('update albaranes_tmp set facturado=0,idfactura=null,observaciones=null,id='+newnumalbaran+',serie='+''''+newserie+''''+',fecha='+''''+newfecha+''''); qaux.ExecSQL; qaux.SQL.Clear; qaux.SQL.Add('update albaranes_detalles_tmp set idalbaran='+newnumalbaran+',serie='+''''+newserie+'''');; qaux.ExecSQL; qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('insert into albaranes (select * from albaranes_tmp)'); qaux.ExecSQL; qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('insert into albaranes_detalles (select * from albaranes_detalles_tmp)'); qaux.ExecSQL; end; qseries.edit; qseriesnum_albaran.Value:=qseriesnum_albaran.AsInteger+1; qseries.Post; idserie:=newserie; idalbaran:=newnumalbaran; close; end; procedure Tfdlgduplicar.dsqseriesDataChange(Sender: TObject; Field: TField); begin edit1.Text:=qseriesnum_albaran.AsString; end; procedure Tfdlgduplicar.FormShow(Sender: TObject); begin qseries.Open; maskedit1.Text:=datetostr(date()); end; end. ======================================== FICHERO: dm3.pas ======================================== unit dm3; interface uses System.SysUtils, System.Classes; type Tdm2 = class(TDataModule) private { Private declarations } public { Public declarations } end; var dm2: Tdm2; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} end. ======================================== FICHERO: empleados.pas ======================================== 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.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, frxExportBaseDialog; type Tfempleados = class(TForm) Panel2: TPanel; Panel1: TPanel; Label1: TLabel; Label28: TLabel; ltotalgrupo: TLabel; tbuscar: TEdit; chktodosempleados: TCheckBox; checktodos2: TCheckBox; listagrupos2: TDBLookupComboBox; 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; 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; qempleadosactivo: TIntegerField; 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; qempleadosmostrar: TIntegerField; 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; qinftrabajadoresactivo: TIntegerField; 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; qinftrabajadoresmostrar: TIntegerField; 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; procedure FormShow(Sender: TObject); procedure dsqlistaempleadosDataChange(Sender: TObject; Field: TField); procedure tbuscarChange(Sender: TObject); 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 checktodos2Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure chktodosempleadosClick(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 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); private { Private declarations } hWndC,hWndC2 : THandle; procedure SetResolution(Width, Height: integer); 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; 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; panel33.Enabled:=true; panel9.Enabled:=true; 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-FORMACIÓN.xlsx',dbgrid75); finally showmessage('Los datos han sido exportados correctamente a '+archivo); end; end; procedure Tfempleados.bteimprimirClick(Sender: TObject); var i,diacomunicacion,mescomunicacion,anyocomunicacion:integer; actual : TBookMarkStr; archivo,fecha,fecha2,fechamenos3,fechamenos3texto,fechamenos15,fechamenos15texto,textmes,llamamiento:string; dia,mes,anyo:word; sfecha:tdate; shora,sfecha2: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); 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); qaux.close; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=0 where seleccionado=1'); qaux.Execsql; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=1 where id=:ID'); qaux.Prepare; if dbgrid1.SelectedRows.Count>0 then for i := 0 to dbgrid1.Selectedrows.Count - 1 do begin qlistaempleados.GotoBookmark ((dbgrid1.selectedrows[i])); qaux.ParamByName('ID').AsInteger:=qlistaempleadosid.asinteger; qaux.Execsql; end else begin qlistaempleados.First; while not qlistaempleados.Eof do begin qaux.ParamByName('ID').AsInteger:=qlistaempleadosid.asinteger; qaux.Execsql; qlistaempleados.Next; end 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 t.seleccionado=1 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+' and t.seleccionado=1 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 seleccionado=1 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 seleccionado=1 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 seleccionado=1 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 seleccionado=1 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 seleccionado=1 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 seleccionado=1 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 seleccionado=1 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 seleccionado=1 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 seleccionado=1 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 seleccionado=1 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 seleccionado=1 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 qaux.close; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=0 where seleccionado=1'); qaux.Execsql; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=1 where id=:ID'); qaux.Prepare; if dbgrid1.SelectedRows.Count>0 then for i := 0 to dbgrid1.Selectedrows.Count - 1 do begin qlistaempleados.GotoBookmark ((dbgrid1.selectedrows[i])); qaux.ParamByName('ID').AsInteger:=qlistaempleadosid.asinteger; qaux.Execsql; end else begin qaux.close; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=1 where convocatoria=:LLAMAMIENTO '); qaux.Prepare; qaux.parambyname('LLAMAMIENTO').asstring:=llamamiento; qaux.execsql; end; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('select * from trabajadores where seleccionado=1 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 seleccionado=1 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 seleccionado=1 and activo='+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; 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: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); case listadocsfirma.ItemIndex of 0:begin qaux.close; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=0 where seleccionado=1'); qaux.Execsql; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=1 where id=:ID'); qaux.Prepare; for i := 0 to dbgrid1.Selectedrows.Count - 1 do begin qlistaempleados.GotoBookmark ((dbgrid1.selectedrows[i])); qaux.ParamByName('ID').AsInteger:=qlistaempleadosid.asinteger; qaux.Execsql; end; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('select * from trabajadores where seleccionado=1 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('update trabajadores set seleccionado=0 where seleccionado=1'); qaux.Execsql; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=1 where id=:ID'); qaux.Prepare; for i := 0 to dbgrid1.Selectedrows.Count - 1 do begin qlistaempleados.GotoBookmark ((dbgrid1.selectedrows[i])); qaux.ParamByName('ID').AsInteger:=qlistaempleadosid.asinteger; qaux.Execsql; end; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('select * from trabajadores where seleccionado=1 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('update trabajadores set seleccionado=0 where seleccionado=1'); qaux.Execsql; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=1 where id=:ID'); qaux.Prepare; for i := 0 to dbgrid1.Selectedrows.Count - 1 do begin qlistaempleados.GotoBookmark ((dbgrid1.selectedrows[i])); qaux.ParamByName('ID').AsInteger:=qlistaempleadosid.asinteger; qaux.Execsql; end; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('select * from trabajadores where seleccionado=1 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('update trabajadores set seleccionado=0 where seleccionado=1'); qaux.Execsql; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=1 where id=:ID'); qaux.Prepare; for i := 0 to dbgrid1.Selectedrows.Count - 1 do begin qlistaempleados.GotoBookmark ( (dbgrid1.selectedrows[i])); qaux.ParamByName('ID').AsInteger:=qlistaempleadosid.asinteger; qaux.Execsql; end; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('select * from trabajadores where seleccionado=1 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('update trabajadores set seleccionado=0 where seleccionado=1'); qaux.Execsql; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=1 where id=:ID'); qaux.Prepare; for i := 0 to dbgrid1.Selectedrows.Count - 1 do begin qlistaempleados.GotoBookmark ( (dbgrid1.selectedrows[i])); qaux.ParamByName('ID').AsInteger:=qlistaempleadosid.asinteger; qaux.Execsql; end; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('select * from trabajadores where seleccionado=1 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('update trabajadores set seleccionado=0 where seleccionado=1'); qaux.Execsql; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=1 where id=:ID'); qaux.Prepare; for i := 0 to dbgrid1.Selectedrows.Count - 1 do begin qlistaempleados.GotoBookmark ( (dbgrid1.selectedrows[i])); qaux.ParamByName('ID').AsInteger:=qlistaempleadosid.asinteger; qaux.Execsql; end; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('select * from trabajadores where seleccionado=1 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: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]); qaux.close; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=0 where seleccionado=1'); qaux.Execsql; for i := 0 to dbgrid1.Selectedrows.Count - 1 do begin qlistaempleados.GotoBookmark ((dbgrid1.selectedrows[i])); qaux.close; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=1 where id='+qempleadosid.asstring); qaux.Execsql; 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 seleccionado=1)' ); qaux.Execsql; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=0 where seleccionado=1'); 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; // qempleadosplanificacion.Edit; panel33.Enabled:=true; panel9.Enabled:=true; end; procedure Tfempleados.btEnuevoClick(Sender: TObject); begin qempleados.Append; 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.btplaceptarClick(Sender: TObject); var idt,ide:string; begin qempleadosplanificacion.post; qlistadoplanificacion.Refresh; idt:=qempleadosplanificacionidt.AsString; ide:=qempleadosplanificacionide.AsString; qlistaempleados.Refresh; qlistaempleados.Locate('id',idt,[locaseinsensitive]); end; procedure Tfempleados.btplcancelarClick(Sender: TObject); begin 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; begin tid:=qempleadosid.AsString; if qempleados.State in [dsedit,dsinsert] then qempleados.Post; if qempleadosplanificacion.State in [dsedit] then qempleadosplanificacion.Post; qlistaempleados.Refresh; qlistaempleados.Locate('id',tid,[locaseinsensitive]); panel33.Enabled:=false; panel9.Enabled:=false; qconvocatorias.Refresh; 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 qlistaempleados.Close; qlistaempleados.Open; end; procedure Tfempleados.DBEdit10Exit(Sender: TObject); begin qempleadosplanificacionfecha_carnetmanipulador.editmask := '!99/99/9900;1;_'; qempleadosplanificacionfecha_carnetmanipulador.OnValidate := qempleadosplanificacionfecha_carnetmanipuladorvalidate; end; procedure Tfempleados.DBEdit10KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_DELETE then If DBEdit10.Text = ' / / ' then begin qempleadosplanificacionfecha_carnetmanipulador.EditMask := ''; qempleadosplanificacionfecha_carnetmanipulador.OnValidate := nil; DBEdit10.Text := ''; end; end; procedure Tfempleados.DBEdit13Exit(Sender: TObject); begin qempleadosplanificacionfecha_testcovid19.editmask := '!99/99/9900;1;_'; qempleadosplanificacionfecha_testcovid19.OnValidate := qempleadosplanificacionfecha_testcovid19validate; end; procedure Tfempleados.DBEdit13KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_DELETE then If DBEdit13.Text = ' / / ' then begin qempleadosplanificacionfecha_testcovid19.EditMask := ''; qempleadosplanificacionfecha_testcovid19.OnValidate := nil; DBEdit13.Text := ''; end; end; procedure Tfempleados.DBEdit21Exit(Sender: TObject); begin qempleadosplanificacionfecha_recmedico.editmask := '!99/99/9900;1;_'; qempleadosplanificacionfecha_recmedico.OnValidate := qempleadosplanificacionfecha_recmedicovalidate; end; procedure Tfempleados.DBEdit21KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_DELETE then If DBEdit21.Text = ' / / ' then begin qempleadosplanificacionfecha_recmedico.EditMask := ''; qempleadosplanificacionfecha_recmedico.OnValidate := nil; DBEdit21.Text := ''; end; end; procedure Tfempleados.DBEdit26Exit(Sender: TObject); begin qempleadosplanificacionfecha_ren_recmedico.editmask := '!99/99/9900;1;_'; qempleadosplanificacionfecha_ren_recmedico.OnValidate := qempleadosplanificacionfecha_ren_recmedicovalidate; end; procedure Tfempleados.DBEdit26KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_DELETE then If DBEdit26.Text = ' / / ' then begin qempleadosplanificacionfecha_ren_recmedico.EditMask := ''; qempleadosplanificacionfecha_ren_recmedico.OnValidate := nil; DBEdit26.Text := ''; end; end; procedure Tfempleados.DBEdit27Change(Sender: TObject); begin DBEDIT2.Text:=DBEDIT8.Text+' '+DBEDIT27.Text; end; procedure Tfempleados.DBEdit40Exit(Sender: TObject); begin qempleadosplanificacionvto_permisotrabajo.editmask := '!99/99/9900;1;_'; qempleadosplanificacionvto_permisotrabajo.OnValidate := qempleadosplanificacionvto_permisotrabajovalidate; end; procedure Tfempleados.DBEdit40KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_DELETE then If DBEdit40.Text = ' / / ' then begin qempleadosplanificacionvto_permisotrabajo.EditMask := ''; qempleadosplanificacionvto_permisotrabajo.OnValidate := nil; DBEdit40.Text := ''; end; 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 qconvocatorias.Refresh; 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.dsqlistaempleadosDataChange(Sender: TObject; Field: TField); var empleado,empresa:integer; anyo,mes,mostrar:string; begin documentos.Close; empleado:=qlistaempleadosid.AsInteger; empresa:=qlistaempleadoside.AsInteger; if pageempleados.ActivePageIndex=1 then begin qempleados.Close; qempleados.Prepare; qempleados.ParamByName('EMPLEADO').AsInteger:=empleado; qempleados.ParamByName('EMPRESA').AsInteger:=empresa; qempleados.Open; qempleadosplanificacion.Close; qempleadosplanificacion.Prepare; qempleadosplanificacion.parambyname('EMPRESA').AsInteger:=empresa; qempleadosplanificacion.parambyname('EMPLEADO').AsInteger:=empleado; qempleadosplanificacion.Open; documentos.Close; documentos.Prepare; documentos.ParamByName('EMPLEADO').AsInteger:=qlistaempleadosid.AsInteger; documentos.ParamByName('EMPRESA').AsInteger:=qlistaempleadoside.AsInteger; documentos.open; end; if pageempleados.ActivePageIndex=2 then begin qempleados.Close; qempleados.Prepare; qempleados.ParamByName('EMPLEADO').AsInteger:=empleado; qempleados.ParamByName('EMPRESA').AsInteger:=empresa; qempleados.Open; qentregasmaterial.Close; qentregasmaterial.Prepare; qentregasmaterial.ParamByName('EMPLEADO').AsInteger:=empleado; qentregasmaterial.ParamByName('EMPRESA').AsInteger:=empresa; qentregasmaterial.open; qlistadoentregasmaterial.Close; qlistadoentregasmaterial.Prepare; qlistadoentregasmaterial.ParamByName('EMPRESA').AsInteger:=empresa; qlistadoentregasmaterial.ParamByName('EMPLEADO').AsInteger:=empleado; qlistadoentregasmaterial.open; end; if pageempleados.ActivePageIndex=3 then begin qempleados.Close; qempleados.Prepare; qempleados.ParamByName('EMPLEADO').AsInteger:=empleado; qempleados.ParamByName('EMPRESA').AsInteger:=empresa; qempleados.Open; if (qlistaempleados.RecordCount>0) and (pageempleados.ActivePageIndex=3) then begin 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.Prepare; qjornales.ParamByName('EMPLEADO').AsInteger:=empleado; qjornales.ParamByName('EMPRESA').AsInteger:=empresa; qjornales.ParamByName('ANYO').Asstring:=anyo; qjornales.ParamByName('MES').Asstring:=mes; qjornales.Open; end; end; if pageempleados.ActivePageIndex=4 then begin if (qlistaempleados.RecordCount>0) and (pageempleados.ActivePageIndex=4) 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.Prepare; qanticipos.ParamByName('EMPLEADO').AsInteger:=empleado; qanticipos.ParamByName('EMPRESA').AsInteger:=empresa; qanticipos.ParamByName('ANYO').Asstring:=anyo; qanticipos.ParamByName('MES').Asstring:=mes; qanticipos.Open; end; end; if pageempleados.ActivePageIndex=5 then begin qlistadoplanificacion.Close; qlistadoplanificacion.Prepare; qlistadoplanificacion.ParamByName('EMPRESA').AsInteger:=EMPRESA; qlistadoplanificacion.open; end; if pageempleados.ActivePageIndex=0 then begin if qlistaempleados.RecordCount>0 then begin qempleados.Close; qempleados.Prepare; qempleados.ParamByName('EMPLEADO').AsInteger:=empleado; qempleados.ParamByName('EMPRESA').AsInteger:=empresa; qempleados.Open; 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 not DirectoryExists('c:\agrigest\tmp') then CreateDir('c:\agrigest\tmp'); Deletefile('c:\agrigest\tmp\empimg.*');//+temp_fotosextension.AsString); image2.Picture:=nil; if qemp_fotos.RecordCount>0 then begin qemp_fotosimagen.savetofile('c:\agrigest\tmp\empimg'+qemp_fotosextension.asstring); image2.Picture.LoadFromFile('c:\agrigest\tmp\empimg'+qemp_fotosextension.AsString); end; qemp_firmas.Close; qemp_firmas.ParamByName('EMPLEADO').AsInteger:=empleado; qemp_firmas.ParamByName('EMPRESA').AsInteger:=empresa; qemp_firmas.open; If not DirectoryExists('c:\agrigest\tmp') then CreateDir('c:\agrigest\tmp'); Deletefile('c:\agrigest\tmp\empimg.bmp');//+temp_fotosextension.AsString); tfirmas.Picture:=nil; if qemp_firmas.RecordCount>0 then begin qemp_firmasfirma.savetofile('c:\agrigest\tmp\empimg.bmp'); tfirmas.Picture.LoadFromFile('c:\agrigest\tmp\empimg.bmp'); Deletefile('c:\agrigest\tmp\empimg.bmp'); end; if qempleados.State in [dsedit,dsinsert] then qempleados.Post; if qempleadosplanificacion.State in [dsedit] then qempleadosplanificacion.Post; qempleadosplanificacion.Close; qempleadosplanificacion.Prepare; qempleadosplanificacion.parambyname('EMPRESA').AsInteger:=empresa; qempleadosplanificacion.parambyname('EMPLEADO').AsInteger:=empleado; qempleadosplanificacion.Open; documentos.Close; documentos.Prepare; documentos.ParamByName('EMPLEADO').AsInteger:=qlistaempleadosid.AsInteger; documentos.ParamByName('EMPRESA').AsInteger:=qlistaempleadoside.AsInteger; documentos.open; end; end; end; 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 (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 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); begin dm.tempresa.Open; pageempleados.ActivePageIndex:=0; qempresaformularios.CLOSE; qgrupos.Open; qgrupos2.open; qtipohora.Open; qregimencotizacion.Open; listagrupos2.KeyValue:=0; qtareas.Open; qparcelas.Open; qpuestostrabajo.Open; qlistaempleados.Open; qconvocatorias.Open; qemp_historico.Open; qempresaformularios.Open; seleccionando:=0; end; procedure Tfempleados.Image2DblClick(Sender: TObject); var nomarchivo:string; begin nomarchivo:='empimg'+qemp_fotosextension.AsString; ShellExecute(Handle,nil,PChar('c:\agrigest\tmp\'+nomarchivo),'','',SW_SHOWNORMAL); 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; qlistaempleados.Close; qlistaempleados.Open; end; procedure Tfempleados.ltipohoraCloseUp(Sender: TObject); begin lprecio.Text:=qtipohoraprecio.AsString; end; procedure Tfempleados.PageEmpleadosChange(Sender: TObject); var empresa,empleado:integer; anyo,mes:string; vanyo,vmes,vdia:word; begin decodedate(date(),vanyo,vmes,vdia); tanyo.ItemIndex:=vanyo-2014; tmes.ItemIndex:=vmes; tanyo2.ItemIndex:=vanyo-2014; tmes2.ItemIndex:=vmes; empleado:=qlistaempleadosid.asinteger; empresa:=qlistaempleadoside.asinteger; if pageempleados.ActivePageIndex=0 then begin if qlistaempleados.RecordCount>0 then begin qempleados.Close; qempleados.Prepare; qempleados.ParamByName('EMPLEADO').AsInteger:=empleado; qempleados.ParamByName('EMPRESA').AsInteger:=empresa; qempleados.Open; 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 not DirectoryExists('c:\agrigest\tmp') then CreateDir('c:\agrigest\tmp'); Deletefile('c:\agrigest\tmp\empimg.*');//+temp_fotosextension.AsString); image2.Picture:=nil; if qemp_fotos.RecordCount>0 then begin qemp_fotosimagen.savetofile('c:\agrigest\tmp\empimg'+qemp_fotosextension.asstring); image2.Picture.LoadFromFile('c:\agrigest\tmp\empimg'+qemp_fotosextension.AsString); end; qemp_firmas.Close; qemp_firmas.ParamByName('EMPLEADO').AsInteger:=empleado; qemp_firmas.ParamByName('EMPRESA').AsInteger:=empresa; qemp_firmas.open; If not DirectoryExists('c:\agrigest\tmp') then CreateDir('c:\agrigest\tmp'); Deletefile('c:\agrigest\tmp\empimg.bmp');//+temp_fotosextension.AsString); tfirmas.Picture:=nil; if qemp_firmas.RecordCount>0 then begin qemp_firmasfirma.savetofile('c:\agrigest\tmp\empimg.bmp'); tfirmas.Picture.LoadFromFile('c:\agrigest\tmp\empimg.bmp'); Deletefile('c:\agrigest\tmp\empimg.bmp'); end; if qempleados.State in [dsedit,dsinsert] then qempleados.Post; if qempleadosplanificacion.State in [dsedit] then qempleadosplanificacion.Post; qempleadosplanificacion.Close; qempleadosplanificacion.Prepare; qempleadosplanificacion.parambyname('EMPRESA').AsInteger:=empresa; qempleadosplanificacion.parambyname('EMPLEADO').AsInteger:=empleado; qempleadosplanificacion.Open; end; end; end; if (qlistaempleados.RecordCount>0) and (pageempleados.ActivePageIndex=1) then begin qempleadosplanificacion.Close; qempleadosplanificacion.Prepare; qempleadosplanificacion.parambyname('EMPRESA').AsInteger:=empresa; qempleadosplanificacion.parambyname('EMPLEADO').AsInteger:=empleado; qempleadosplanificacion.Open; end; if (qlistaempleados.RecordCount>0) and (pageempleados.ActivePageIndex=2) then begin // panel30.Visible:=false; btEMaceptar.Enabled:=false; btEMcancelar.Enabled:=false; btEMnuevo.Enabled:=true; btEMmodificar.Enabled:=true; btEMborrar.Enabled:=true; qentregasmaterial.Close; qentregasmaterial.Prepare; qentregasmaterial.ParamByName('EMPLEADO').AsInteger:=empleado; qentregasmaterial.ParamByName('EMPRESA').AsInteger:=empresa; qentregasmaterial.open; qlistadoentregasmaterial.Close; qlistadoentregasmaterial.Prepare; qlistadoentregasmaterial.ParamByName('EMPRESA').AsInteger:=empresa; qlistadoentregasmaterial.ParamByName('EMPLEADO').AsInteger:=empleado; qlistadoentregasmaterial.open; qepis.Close; qepis.Prepare; qepis.ParamByName('EMPRESA').AsInteger:=EMPRESA; qepis.open; fentregamaterial.Date:=date(); end; if (qlistaempleados.RecordCount>0) and (pageempleados.ActivePageIndex=3) then begin 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; qparcelas.Open; qtareas.open; end; if (qlistaempleados.RecordCount>0) and (pageempleados.ActivePageIndex=4) then begin fechaanticipo.date:=date(); if (qlistaempleados.RecordCount>0) and (pageempleados.ActivePageIndex=4) then begin if tanyo.ItemIndex<>0 then anyo:=tanyo.Text else anyo:='%'; if tmes.itemindex<>0 then mes:=inttostr(tmes.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; end; if (pageempleados.ActivePageIndex=5) then begin qlistadoplanificacion.Close; qlistadoplanificacion.Prepare; qlistadoplanificacion.ParamByName('EMPRESA').AsInteger:=EMPRESA; qlistadoplanificacion.open; end; if (pageempleados.ActivePageIndex=2) then begin end; 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 qempleadosmostrar.Value:=1 else qempleadosmostrar.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 if qempleadosplanificacionfecha_carnetmanipulador.asstring=' / / ' then begin qempleadosplanificacionfecha_carnetmanipulador.value := null; end; end; procedure Tfempleados.qempleadosplanificacionfecha_recmedicoValidate( Sender: TField); begin if qempleadosplanificacionfecha_recmedico.asstring=' / / ' then begin qempleadosplanificacionfecha_recmedico.value := null; end; end; procedure Tfempleados.qempleadosplanificacionfecha_ren_recmedicoValidate( Sender: TField); begin if qempleadosplanificacionfecha_ren_recmedico.asstring=' / / ' then begin qempleadosplanificacionfecha_ren_recmedico.value := null; end; end; procedure Tfempleados.qempleadosplanificacionfecha_testcovid19Validate( Sender: TField); begin if qempleadosplanificacionfecha_testcovid19.asstring=' / / ' then begin qempleadosplanificacionfecha_testcovid19.value := null; end; end; procedure Tfempleados.qempleadosplanificacionvto_permisotrabajoValidate( Sender: TField); begin if qempleadosplanificacionvto_permisotrabajo.asstring=' / / ' then begin qempleadosplanificacionvto_permisotrabajo.value := null; end; 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); end; procedure Tfempleados.qlistaempleadosBeforeOpen(DataSet: TDataSet); var filtro:string; begin if filtrotrabajadores<>'' then begin if vtactivo<>0 then begin filtro:=filtro+ ' where t.ide=ep.ide and t.id=ep.idt and (nombre like('+''''+'%'+filtrotrabajadores+'%'+''''+') or (id='+''''+filtrotrabajadores+''''+')) and activo='+inttostr(vtactivo) end else begin filtro:=filtro+ ' where t.ide=ep.ide and t.id=ep.idt and (nombre like('+''''+'%'+filtrotrabajadores+'%'+''''+') or (id='+''''+filtrotrabajadores+''''+'))'; end; if chktodosempleados.Checked then begin //filtro:=filtro+' and mostrar=1 '; end else begin filtro:=filtro+' and mostrar=1 '; end; end; if filtrotrabajadores='' then begin if vtactivo<>0 then begin filtro:=filtro+ ' where t.ide=ep.ide and t.id=ep.idt and activo='+inttostr(vtactivo); if chktodosempleados.Checked then begin // filtro:=filtro+' and mostrar=1 '; end else begin filtro:=filtro+' and t.ide=ep.ide and t.id=ep.idt and mostrar=1 '; end; end else begin filtro:=''; if chktodosempleados.Checked then begin filtro:=' where t.ide=ep.ide and t.id=ep.idt '; end else begin filtro:=' where t.ide=ep.ide and t.id=ep.idt and mostrar=1 '; end; end; end; 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 nombre') end; procedure Tfempleados.TanyoChange(Sender: TObject); var anyo,mes:string; empresa,empleado:integer; begin 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.tbuscarChange(Sender: TObject); begin seleccionando:=1; filtrotrabajadores:=tbuscar.Text; qlistaempleados.Close; qlistaempleados.open; seleccionando:=0; end; procedure Tfempleados.tbuscarExit(Sender: TObject); begin 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; end. ======================================== FICHERO: falbaranes.pas ======================================== unit falbaranes; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, Vcl.DBCtrls,datos, Vcl.Mask, Vcl.Grids, Vcl.DBGrids, Vcl.ComCtrls, frxClass, frxDBSet, ComObj, Excel2000, frxExportPDF, frxExportBaseDialog; type Talbaranes = class(TForm) Panel1: TPanel; Panel4: TPanel; btAcancelar: TButton; btAmodificar: TButton; btAborrar: TButton; btAnuevo: TButton; btAguardar: TButton; Panel2: TPanel; dsalbaranes: TDataSource; dsalbaranesdetalle: TDataSource; albaranes: TZQuery; albaranesdetalle: TZQuery; Panel3: TPanel; comboserie: TDBLookupComboBox; qseries: TZQuery; dsqseries: TDataSource; qserieside: TIntegerField; qseriesid: TWideStringField; qseriesfechainicio: TDateField; qseriesfechafin: TDateField; qseriesnum_pedcliente: TIntegerField; qseriesnum_albaran: TIntegerField; qseriesnum_factura: TIntegerField; qseriesnum_expedicion: TIntegerField; qseriesnum_pedproveedor: TIntegerField; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; DBEdit1: TDBEdit; comboclientes: TDBLookupComboBox; combodestinos: TDBLookupComboBox; Label5: TLabel; DBEdit2: TDBEdit; dsqclientes: TDataSource; qclientes: TZQuery; qclientesid: TIntegerField; qclientesIdempresa: TIntegerField; qclientesnif: TWideStringField; qclientesnombre: TWideStringField; qclientesnombre_corto: TWideStringField; qclientesdireccion: TWideStringField; qclientespoblacion: TWideStringField; qclientescodpost: TWideStringField; qclientesprovincia: TWideStringField; qclientestelefono: TWideStringField; qclientestelefono2: TWideStringField; qclientesmovil: TWideStringField; qclientesemail: TWideStringField; qclientespersonacontacto: TWideStringField; qclientescodigomercado: TIntegerField; qclientesactivo: TIntegerField; qclientesobservaciones: TWideStringField; qclientesccontable: TIntegerField; qclientesdescuento: TFloatField; dsqdestinos: TDataSource; qdestinos: TZQuery; qdestinoscodigo: TWideStringField; qdestinosidcliente: TIntegerField; qdestinosidempresa: TIntegerField; qdestinosdescripcion: TWideStringField; qdestinosseleccionado: TIntegerField; qdestinosactivo: TIntegerField; qdestinosdireccion: TWideStringField; qdestinospoblacion: TWideStringField; qdestinoscodpost: TWideStringField; qdestinosprovincia: TWideStringField; Label6: TLabel; Label7: TLabel; DBText3: TDBText; DBText4: TDBText; DBText5: TDBText; DBText6: TDBText; DBText7: TDBText; DBText8: TDBText; DBText9: TDBText; DBText10: TDBText; qclientespais: TWideStringField; qdestinospais: TWideStringField; DBText11: TDBText; DBText12: TDBText; DBText13: TDBText; DBText14: TDBText; DBText15: TDBText; dsqpedidos: TDataSource; qpedidos: TZQuery; dsqpedidosdetalle: TDataSource; qpedidosdetalle: TZQuery; qpedidosdetalleid: TIntegerField; qpedidosdetalleide: TIntegerField; qpedidosdetalleidpedido: TIntegerField; qpedidosdetalleidcliente: TIntegerField; qpedidosdetalleidproductocli: TWideStringField; qpedidosdetalleidenvase: TWideStringField; qpedidosdetalledesc_envase: TWideStringField; qpedidosdetalledesc_producto: TWideStringField; qpedidosdetallecantidad: TFloatField; qpedidosdetallecantidadservida: TFloatField; qpedidosdetallepalets: TIntegerField; qpedidosdetalleref: TWideStringField; qpedidosdetalleean: TWideStringField; qpedidosdetallemarca: TWideStringField; qpedidosdetalleobservaciones: TWideStringField; qpedidosdetalleidcajapropia: TWideStringField; qpedidosid: TIntegerField; qpedidoside: TIntegerField; qpedidosidcliente: TIntegerField; qpedidosiddestino: TWideStringField; qpedidosfecha_pedido: TDateField; qpedidosfecha_entrega: TDateField; qpedidoscliente: TWideStringField; qpedidosdestino: TWideStringField; dsqalbaranesiva: TDataSource; qalbaranesiva: TZQuery; albaranesid: TIntegerField; albaranesidempresa: TIntegerField; albaranesidcliente: TIntegerField; albaranesiddestino: TWideStringField; albaranesnif: TWideStringField; albaranesdireccion: TWideStringField; albaranespoblacion: TWideStringField; albaranesprovincia: TWideStringField; albaranescodpost: TWideStringField; albaranesfecha: TDateField; albaranesreferencia: TWideStringField; albaranestelefono: TWideStringField; albaranesnomcliente: TWideStringField; albaranespaiscliente: TWideStringField; albaranesnomdestino: TWideStringField; albaranesdirecciondestino: TWideStringField; albaranespoblaciondestino: TWideStringField; albaranescodpostdestino: TWideStringField; albaranesprovinciadestino: TWideStringField; albaranespaisdestino: TWideStringField; albaranesneto: TFloatField; albaranestotal: TFloatField; albaranesfacturado: TIntegerField; albaranesdocumento: TWideStringField; dsqpedidos2: TDataSource; dsqpedidosdetalle2: TDataSource; qpedidosdetalle2: TZQuery; qpedidos2: TZQuery; IntegerField8: TIntegerField; IntegerField9: TIntegerField; IntegerField10: TIntegerField; WideStringField11: TWideStringField; DateField1: TDateField; DateField2: TDateField; WideStringField12: TWideStringField; WideStringField13: TWideStringField; Panel5: TPanel; qalbaranesivaidalbaran: TIntegerField; qalbaranesivaide: TIntegerField; qalbaranesivabase: TFloatField; qalbaranesivatipo: TFloatField; qalbaranesivaiva: TFloatField; Panel6: TPanel; DBGrid1: TDBGrid; albaranesdescuento_lin: TFloatField; albaranesdescuento_com: TFloatField; albaranesdescuento_pp: TFloatField; albaranesdescuento_total: TFloatField; albaranestotaliva: TFloatField; Label9: TLabel; DBEdit4: TDBEdit; Label12: TLabel; DBEdit7: TDBEdit; Label13: TLabel; DBEdit8: TDBEdit; Label14: TLabel; DBEdit9: TDBEdit; btaimprimir: TButton; btaimportar: TButton; btafacturar: TButton; DBGrid2: TDBGrid; Panel7: TPanel; Button4: TButton; qpedidosdetalle2id: TIntegerField; qpedidosdetalle2ide: TIntegerField; qpedidosdetalle2idpedido: TIntegerField; qpedidosdetalle2idcliente: TIntegerField; qpedidosdetalle2idproductocli: TWideStringField; qpedidosdetalle2idenvase: TWideStringField; qpedidosdetalle2desc_envase: TWideStringField; qpedidosdetalle2desc_producto: TWideStringField; qpedidosdetalle2cantidad: TFloatField; qpedidosdetalle2cantidadservida: TFloatField; qpedidosdetalle2palets: TIntegerField; qpedidosdetalle2ref: TWideStringField; qpedidosdetalle2ean: TWideStringField; qpedidosdetalle2marca: TWideStringField; qpedidosdetalle2observaciones: TWideStringField; qpedidosdetalle2idcajapropia: TWideStringField; DBCheckBox1: TDBCheckBox; DBMemo1: TDBMemo; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; DBGrid3: TDBGrid; btasiguiente: TButton; btaanterior: TButton; infalbaran: TfrxDBDataset; infdetallealbaran: TfrxDBDataset; infalbaranivas: TfrxDBDataset; informe: TfrxReport; albaranesobservaciones: TWideStringField; Label15: TLabel; DBMemo2: TDBMemo; qaux: TZQuery; albaranesidfactura: TIntegerField; qalbaranesivaserie: TWideStringField; qseriesimp_albaran: TWideStringField; qseriesimp_factura: TWideStringField; albaranesserie: TWideStringField; qpedidosdetalleidalbaran: TWideStringField; qpedidosdetalleidexpedicion: TWideStringField; qpedidosdetalle2idalbaran: TWideStringField; qpedidosdetalle2idexpedicion: TWideStringField; albaranesbultos: TFloatField; albaraneskilos: TFloatField; albaranesidformapago: TIntegerField; Label16: TLabel; comboformapago: TDBLookupComboBox; dsqformaspago: TDataSource; qformaspago: TZQuery; qformaspagoide: TIntegerField; qformaspagoid: TIntegerField; qformaspagocodigo: TWideStringField; qformaspagodescripcion: TWideStringField; qformaspagodias: TIntegerField; qclientesidformapago: TIntegerField; listaimpresion: TComboBox; albaranesdetalleidempresa: TIntegerField; albaranesdetalleidalbaran: TIntegerField; albaranesdetallecantidad: TFloatField; albaranesdetalleprecio: TFloatField; albaranesdetalledescuento: TFloatField; albaranesdetallebase: TFloatField; albaranesdetallecal: TWideStringField; albaranesdetallebultos: TFloatField; albaranesdetalletipoiva: TFloatField; albaranesdetalleiva: TFloatField; albaranesdetalletotal: TFloatField; albaranesdetalleid: TIntegerField; albaranesdetalletotaldescuento: TFloatField; albaranesdetalleserie: TWideStringField; albaranesdetalleidarticulo: TWideStringField; albaranesdetallelote: TWideStringField; qarticulos: TZReadOnlyQuery; dsqarticulos: TDataSource; qarticulosidempresa: TIntegerField; qarticulosid: TIntegerField; qarticuloscodigo: TWideStringField; qarticulosdescripcion: TWideStringField; qarticulosfamilia: TIntegerField; qarticulosprovhab: TIntegerField; qarticulostipoiva: TIntegerField; qarticulospreciocoste: TFloatField; qarticulosmargen: TFloatField; qarticulosbeneficio: TFloatField; qarticulospvp: TFloatField; qarticulosstock: TFloatField; qarticulosult_preciocompra: TFloatField; qarticulosfacturable: TIntegerField; qarticulosobservaciones: TWideStringField; qarticulosimagen: TBlobField; qarticulosactivo: TIntegerField; qarticulosvalor_almacen: TFloatField; qarticulosstock_minimo: TFloatField; qarticulosavisar_stock: TIntegerField; qarticuloscontrolar_traza: TIntegerField; qarticulospeso: TFloatField; qtipos_iva: TZReadOnlyQuery; dsqtiposiva: TDataSource; qtipos_ivaid: TIntegerField; qtipos_ivadescripcion: TWideStringField; qtipos_ivatipo: TIntegerField; qtipos_ivatipo_req: TFloatField; albaranescoste_transporte: TFloatField; costetrans: TDBEdit; Label17: TLabel; qalbaranesclientes: TZReadOnlyQuery; dsqalbaranesclientes: TDataSource; albaranesdetallecoste_transporte: TFloatField; albaranesdetallecoste_otros: TFloatField; Panel11: TPanel; gridalbaranesaexcel: TDBGrid; SaveDialog1: TSaveDialog; qclientesexento_iva: TIntegerField; Label18: TLabel; DBEdit10: TDBEdit; albaranespeso_bruto: TFloatField; albaranesprov_transporte: TWideStringField; qpedidospedidocliente: TWideStringField; qpedidos2pedidocliente: TWideStringField; frxPDFExport1: TfrxPDFExport; dsfacturas: TDataSource; dsfacturasdetalle: TDataSource; facturasdetalle: TZQuery; facturasdetalleid: TIntegerField; facturasdetalleidempresa: TIntegerField; facturasdetalleidfactura: TIntegerField; facturasdetalleidarticulo: TWideStringField; facturasdetalledescripcion: TWideStringField; facturasdetallecal: TWideStringField; facturasdetallelote: TWideStringField; facturasdetallecantidad: TFloatField; facturasdetalleprecio: TFloatField; facturasdetalledescuento: TFloatField; facturasdetalletotaldescuento: TFloatField; facturasdetallebase: TFloatField; facturasdetalletipoiva: TFloatField; facturasdetalleiva: TFloatField; facturasdetalletotal: TFloatField; facturasdetalleserie: TWideStringField; facturasdetallebultos: TFloatField; facturas: TZQuery; facturasid: TIntegerField; facturasidempresa: TIntegerField; facturasidcliente: TIntegerField; facturasiddestino: TWideStringField; facturasnif: TWideStringField; facturasdireccion: TWideStringField; facturaspoblacion: TWideStringField; facturasprovincia: TWideStringField; facturascodpost: TWideStringField; facturasfecha: TDateField; facturasreferencia: TWideStringField; facturastelefono: TWideStringField; facturasnomcliente: TWideStringField; facturaspaiscliente: TWideStringField; facturasnomdestino: TWideStringField; facturasdirecciondestino: TWideStringField; facturaspoblaciondestino: TWideStringField; facturascodpostdestino: TWideStringField; facturasprovinciadestino: TWideStringField; facturaspaisdestino: TWideStringField; facturasneto: TFloatField; facturastotal: TFloatField; facturasdocumento: TWideStringField; facturasdescuento_lin: TFloatField; facturasdescuento_com: TFloatField; facturasdescuento_pp: TFloatField; facturasdescuento_total: TFloatField; facturastotaliva: TFloatField; facturasobservaciones: TWideStringField; facturasserie: TWideStringField; facturasbultos: TFloatField; facturaskilos: TFloatField; facturasidformapago: TIntegerField; facturascobrado: TIntegerField; Edit1: TEdit; Label19: TLabel; Button1: TButton; Label20: TLabel; combocuenta: TDBLookupComboBox; Label21: TLabel; qclientescomision: TFloatField; qcuentas: TZReadOnlyQuery; dsqcuentas: TDataSource; albaranescc_pago: TWideStringField; albaranesccid: TIntegerField; albaranescccuentabancaria: TWideStringField; qcuentaside: TIntegerField; qcuentasid: TIntegerField; qcuentasbanco: TWideStringField; qcuentascciban: TWideStringField; qcuentasccentidad: TWideStringField; qcuentasccoficina: TWideStringField; qcuentasccdc: TWideStringField; qcuentascccc: TWideStringField; Label22: TLabel; albaranescomision: TFloatField; albaraneskilosventa: TFloatField; Label8: TLabel; DBEdit3: TDBEdit; Label10: TLabel; DBEdit5: TDBEdit; albaranesnumpalets: TFloatField; comision: TDBEdit; DBText1: TDBText; DBText2: TDBText; DBText16: TDBText; DBText17: TDBText; DBText18: TDBText; albaranesdetallecoste_comision: TFloatField; Button2: TButton; Button5: TButton; Panel8: TPanel; Panel9: TPanel; Edit2: TEdit; Label11: TLabel; Label23: TLabel; dsqseries2: TDataSource; qseries2: TZReadOnlyQuery; comboserie2: TDBLookupComboBox; RadioGroup1: TRadioGroup; RadioButton1: TRadioButton; RadioButton2: TRadioButton; Panel10: TPanel; Label24: TLabel; Label34: TLabel; fdesde: TDateTimePicker; fhasta: TDateTimePicker; Label35: TLabel; Panel12: TPanel; Label32: TLabel; Button8: TButton; DBGrid4: TDBGrid; Panel13: TPanel; Label25: TLabel; Button6: TButton; DBGrid5: TDBGrid; Edit3: TEdit; Edit4: TEdit; qseries2ide: TIntegerField; qseries2id: TWideStringField; qseries2fechainicio: TDateField; qseries2fechafin: TDateField; qseries2num_pedcliente: TIntegerField; qseries2num_albaran: TIntegerField; qseries2num_factura: TIntegerField; qseries2num_expedicion: TIntegerField; qseries2num_pedproveedor: TIntegerField; qseries2imp_albaran: TWideStringField; qseries2imp_factura: TWideStringField; qseries2activo: TIntegerField; qseries2num_presupuesto: TIntegerField; qseriesactivo: TIntegerField; qseriesnum_presupuesto: TIntegerField; Panel14: TPanel; Button3: TButton; btaduplicar: TButton; albaranesdetalledescripcion: TWideStringField; albaranesdetallepesobruto: TFloatField; qpedidosdetalledesc_envpropio: TWideStringField; qpedidosdetalleidcalidad: TWideStringField; qpedidosdetalleidacabado: TWideStringField; qpedidosdetalledesc_calidad: TWideStringField; qpedidosdetalledesc_acabado: TWideStringField; qpedidosdetalleidformatopropio: TIntegerField; qpedidosdetalledesc_formatopropio: TWideStringField; Button7: TButton; comboformulario: TDBLookupComboBox; qformularios: TZReadOnlyQuery; dsqformularios: TDataSource; qformularioside: TIntegerField; qformulariosid: TIntegerField; qformulariosformulario: TWideStringField; qformulariosdescripcion: TWideStringField; qformulariosaplicar_a: TWideStringField; qformulariospordefecto: TIntegerField; Label26: TLabel; DBLookupComboBox1: TDBLookupComboBox; albaranesdetalleidfactura: TIntegerField; qalbaranesclientesserie: TWideStringField; qalbaranesclientesid: TIntegerField; qalbaranesclientesidempresa: TIntegerField; qalbaranesclientesidcliente: TIntegerField; qalbaranesclientesiddestino: TWideStringField; qalbaranesclientesnif: TWideStringField; qalbaranesclientesdireccion: TWideStringField; qalbaranesclientespoblacion: TWideStringField; qalbaranesclientesprovincia: TWideStringField; qalbaranesclientescodpost: TWideStringField; qalbaranesclientesfecha: TDateField; qalbaranesclientesreferencia: TWideStringField; qalbaranesclientestelefono: TWideStringField; qalbaranesclientesnomcliente: TWideStringField; qalbaranesclientespaiscliente: TWideStringField; qalbaranesclientesnomdestino: TWideStringField; qalbaranesclientesdirecciondestino: TWideStringField; qalbaranesclientespoblaciondestino: TWideStringField; qalbaranesclientescodpostdestino: TWideStringField; qalbaranesclientesprovinciadestino: TWideStringField; qalbaranesclientespaisdestino: TWideStringField; qalbaranesclientesneto: TFloatField; qalbaranesclientestotal: TFloatField; qalbaranesclientesfacturado: TIntegerField; qalbaranesclientesdocumento: TWideStringField; qalbaranesclientesdescuento_lin: TFloatField; qalbaranesclientesdescuento_com: TFloatField; qalbaranesclientesdescuento_pp: TFloatField; qalbaranesclientesdescuento_total: TFloatField; qalbaranesclientestotaliva: TFloatField; qalbaranesclientesobservaciones: TWideStringField; qalbaranesclientesidfactura: TIntegerField; qalbaranesclientesbultos: TFloatField; qalbaranesclienteskilos: TFloatField; qalbaranesclientesidformapago: TIntegerField; qalbaranesclientescc_pago: TWideStringField; qalbaranesclientescoste_transporte: TFloatField; qalbaranesclientespeso_bruto: TFloatField; qalbaranesclientesprov_transporte: TWideStringField; qalbaranesclientesccid: TIntegerField; qalbaranesclientescccuentabancaria: TWideStringField; qalbaranesclientescomision: TFloatField; qalbaranesclienteskilosventa: TFloatField; qalbaranesclientesnumpalets: TFloatField; qalbaranesclientesid_1: TIntegerField; qalbaranesclientesidempresa_1: TIntegerField; qalbaranesclientesserie_1: TWideStringField; qalbaranesclientesidalbaran: TIntegerField; qalbaranesclientesidarticulo: TWideStringField; qalbaranesclientesdescripcion: TWideStringField; qalbaranesclientescal: TWideStringField; qalbaranesclienteslote: TWideStringField; qalbaranesclientesbultos_1: TFloatField; qalbaranesclientescantidad: TFloatField; qalbaranesclientesprecio: TFloatField; qalbaranesclientesdescuento: TFloatField; qalbaranesclientestotaldescuento: TFloatField; qalbaranesclientesbase: TFloatField; qalbaranesclientestipoiva: TFloatField; qalbaranesclientesiva: TFloatField; qalbaranesclientestotal_1: TFloatField; qalbaranesclientescoste_transporte_1: TFloatField; qalbaranesclientescoste_otros: TFloatField; qalbaranesclientescoste_comision: TFloatField; qalbaranesclientespesobruto: TFloatField; qalbaranesclientesidfactura_1: TIntegerField; qalbaranesclientesparcela: TWideStringField; Label27: TLabel; DBEdit6: TDBEdit; facturascomision: TFloatField; facturascoste_transporte: TFloatField; facturasdetallecoste_transporte: TFloatField; facturasdetallecoste_otros: TFloatField; facturasdetallecoste_comision: TFloatField; Label28: TLabel; DBEdit11: TDBEdit; albaranesdetallepalets: TFloatField; qedi_cabalbaran: TZReadOnlyQuery; qedi_cabalbarancampo: TWideStringField; qedi_cabalbarantipo: TWideStringField; qedi_cabalbaranlongitud: TFloatField; qedi_cabalbaranpos_inicio: TIntegerField; qedi_cabalbaranpos_fin: TIntegerField; Button9: TButton; qedi_detalbaran: TZReadOnlyQuery; qedi_embalbaran: TZReadOnlyQuery; qedi_lugaresentrega: TZReadOnlyQuery; qedi_marcasembalaje: TZReadOnlyQuery; qedi_detalbarancampo: TWideStringField; qedi_detalbarantipo: TWideStringField; qedi_detalbaranlongitud: TFloatField; qedi_detalbaranpos_inicio: TIntegerField; qedi_detalbaranpos_fin: TIntegerField; qedi_embalbarancampo: TWideStringField; qedi_embalbarantipo: TWideStringField; qedi_embalbaranlongitud: TFloatField; qedi_embalbaranpos_inicio: TIntegerField; qedi_embalbaranpos_fin: TIntegerField; qedi_lugaresentregacampo: TWideStringField; qedi_lugaresentregatipo: TWideStringField; qedi_lugaresentregalongitud: TFloatField; qedi_lugaresentregapos_inicio: TIntegerField; qedi_lugaresentregapos_fin: TIntegerField; qedi_marcasembalajecampo: TWideStringField; qedi_marcasembalajetipo: TWideStringField; qedi_marcasembalajelongitud: TFloatField; qedi_marcasembalajepos_inicio: TIntegerField; qedi_marcasembalajepos_fin: TIntegerField; qedicabecera: TZReadOnlyQuery; qediembalajes: TZReadOnlyQuery; qedilocalizaciones: TZReadOnlyQuery; qedilinalbaran: TZReadOnlyQuery; qedicabeceraIDCAB: TWideStringField; qedicabeceraNUMDES: TIntegerField; qedicabeceraTIPO: TWideStringField; qedicabeceraFECDES: TDateField; qedicabeceraFECENT: TDateField; qedicabeceraNUMALB: TWideStringField; qedicabeceraFECALB: TDateField; qedicabeceraNUMPED: TWideStringField; qedicabeceraORIGEN: TWideStringField; qedicabeceraDESTINO: TWideStringField; qedicabeceraPROVEEDO: TWideStringField; qedicabeceraCOMPRADO: TWideStringField; qedicabeceraRECEPTOR: TWideStringField; qedicabeceraTOTQTY: TFloatField; qedicabeceraFECENV: TDateField; qedicabeceracodprov: TWideStringField; qedicabeceraNOMBREEMISOR: TWideStringField; qedicabeceraNIFEMISOR: TWideStringField; qedicabeceraNOMBRERECEPTOR: TWideStringField; qedicabeceraNOMBRECOMPRADOR: TWideStringField; qedicabeceraNOMBREPROVEEDOR: TWideStringField; qedicabeceraNOMBREPTOENTREGA: TWideStringField; qedicabeceraDIRECCIONEMISOR: TWideStringField; qedicabeceraPOBLACIONEMISOR: TWideStringField; qedicabeceraPROVINCIAEMISOR: TWideStringField; qedicabeceraCPEMISOR: TWideStringField; qedicabeceraDIRECCIONCOMPRADOR: TWideStringField; qedicabeceraPOBLACIONCOMPRADOR: TWideStringField; qedicabeceraPROVINCIACOMPRADOR: TWideStringField; qedicabeceraCPCOMPRADOR: TWideStringField; qedicabeceraDIRECCIONPTOENTREGA: TWideStringField; qedicabeceraPOBLACIONPTOENTREGA: TWideStringField; qedicabeceraPROVINCIAPTOENTREGA: TWideStringField; qedicabeceraCPPTOENTREGA: TWideStringField; qedicabeceraDIRECCIONRECEPTOR: TWideStringField; qedicabeceraPOBLACIONRECEPTOR: TWideStringField; qedicabeceraPROVINCIARECEPTOR: TWideStringField; qedicabeceraCPRECEPTOR: TWideStringField; qedicabeceraNIFPROVEEDOR: TWideStringField; qedicabeceraIMPTOTBRUTO: TFloatField; qedicabeceraIMPTOTNETO: TFloatField; qedicabeceraMONEDA: TWideStringField; qedicabeceraPESOBRUTOT: TFloatField; qedicabeceraPESONETTOT: TFloatField; qedicabeceraNUMTOTBUL: TFloatField; qedicabeceraMEDIOTRAN: TWideStringField; qedicabeceraORDENADOR: TWideStringField; qedilinalbaranIDCAB: TWideStringField; qedilinalbaranIDEMB: TWideStringField; qedilinalbaranCPSO: TFloatField; qedilinalbaranIDLIN: TWideStringField; qedilinalbaranEAN: TWideStringField; qedilinalbaranREFPROV: TWideStringField; qedilinalbaranNUMEXP: TFloatField; qedilinalbaranDESCRIP: TWideStringField; qedilinalbaranCENVFAC: TFloatField; qedilinalbaranCUEXP: TFloatField; qedilinalbaranUNICANT: TWideStringField; qedilinalbaranNUMPED: TWideStringField; qedilinalbaranNUMALB: TWideStringField; qedilinalbaranSSCC: TWideStringField; qedilinalbaranFECENV: TDateField; qedilinalbaranFECCON: TDateField; qedilinalbaranLOTE: TWideStringField; qedilinalbaranCANTLOC1: TFloatField; qedilinalbaranNOMBREPTOENTREGA: TWideStringField; qedilinalbaranFECPED: TDateField; qedilinalbaranFECALB: TDateField; qedilinalbaranPESTOTLIN: TFloatField; qedilinalbaranFECCADET: TDateField; qedilinalbaranPESOBRUTO: TFloatField; qedilinalbaranPESONETO: TFloatField; qediembalajesIDCAB: TWideStringField; qediembalajesIDEMB: TWideStringField; qediembalajesCPSO: TWideStringField; qediembalajesCPSPADRE: TWideStringField; qediembalajesCANTEMB: TLargeintField; qediembalajesTIPEMB: TWideStringField; qediembalajesDESCEMB: TWideStringField; qediembalajesPAGRET: TWideStringField; qediembalajesSSCC1: TWideStringField; qediembalajesBULTPALET: TFloatField; qediembalajesFORMATO: TWideStringField; qediembalajesIDLIN: TWideStringField; qediembalajesIDMARCA: TWideStringField; qediembalajesMARCA1: TWideStringField; qediembalajesFECENV: TDateField; qediembalajesLOTE: TWideStringField; qedilocalizacionesIDCAB: TWideStringField; qedilocalizacionesIDEMB: TFloatField; qedilocalizacionesIDLIN: TWideStringField; qedilocalizacionesIDLOC: TWideStringField; qedilocalizacionesLUGAR: TWideStringField; qedilocalizacionesFECENV: TDateField; qedilocalizacionesCANTIDAD: TFloatField; qedilocalizacionesCANTKGM: TFloatField; qedilocalizacionesNOMBREPTOENTREGA: TWideStringField; qedilocalizacionesUMEDIDA: TWideStringField; qedicabeceraFECPED: TDateField; qedicabeceraDPTO: TWideStringField; qedicabeceraALBARANCLIENTE: TWideStringField; qedilinalbaranALBARANCLIENTE: TWideStringField; qedilinalbaranTEXTO4: TWideStringField; qedilinalbaranTEXTO5: TWideStringField; qedicabeceraULTCONS: TWideStringField; qedilinalbaranNUMEXP2: TWideStringField; Label29: TLabel; ComboBox1: TComboBox; qpedidosdetalleunidadescaja: TIntegerField; qpedidosdetallefecha_caducidad: TDateField; qpedidosdetalleprecio: TFloatField; qalbaraneslotes: TZQuery; qalbaranespalets: TZQuery; qalbaranespaletsid: TIntegerField; qalbaranespaletside: TIntegerField; qalbaranespaletsids: TWideStringField; qalbaranespaletsida: TIntegerField; qalbaranespaletscantidad: TIntegerField; qalbaranespaletstipo_palet: TWideStringField; qalbaraneslotesid: TIntegerField; qalbaranesloteside: TIntegerField; qalbaraneslotesids: TWideStringField; qalbaraneslotesida: TIntegerField; qalbaranesloteslote: TWideStringField; qalbaraneslotesvariedad: TWideStringField; dsalbaranespalets: TDataSource; dsalbarnaeslotes: TDataSource; Panel15: TPanel; DBGrid6: TDBGrid; DBGrid7: TDBGrid; Panel16: TPanel; qinsertarfacturasdetalles: TZQuery; albaranesdetallegrupo: TZQuery; albaranesdetallegrupoidempresa: TIntegerField; albaranesdetallegrupoidalbaran: TIntegerField; albaranesdetallegrupocantidad: TFloatField; albaranesdetallegrupoprecio: TFloatField; albaranesdetallegrupodescuento: TFloatField; albaranesdetallegrupobase: TFloatField; albaranesdetallegrupodescripcion: TWideStringField; albaranesdetallegrupocal: TWideStringField; albaranesdetallegrupopalets: TFloatField; albaranesdetallegrupobultos: TFloatField; albaranesdetallegrupotipoiva: TFloatField; albaranesdetallegrupoiva: TFloatField; albaranesdetallegrupototal: TFloatField; albaranesdetallegrupoid: TIntegerField; albaranesdetallegrupoidarticulo: TWideStringField; albaranesdetallegrupototaldescuento: TFloatField; albaranesdetallegrupolote: TWideStringField; albaranesdetallegruposerie: TWideStringField; albaranesdetallegrupocoste_transporte: TFloatField; albaranesdetallegrupocoste_otros: TFloatField; albaranesdetallegrupocoste_comision: TFloatField; albaranesdetallegrupopesobruto: TFloatField; albaranesdetallegrupoidfactura: TIntegerField; albaranesdetallepais: TWideStringField; albaranesdetalleenvase: TWideStringField; albaranesdetallereferencia: TWideStringField; albaranesdetalleean: TWideStringField; albaranesdetalleunidadescaja: TIntegerField; albaranesdetallegrupopais: TWideStringField; albaranesdetallegrupoenvase: TWideStringField; albaranesdetallegruporeferencia: TWideStringField; albaranesdetallegrupoean: TWideStringField; albaranesdetallegrupounidadescaja: TIntegerField; Panel17: TPanel; Button10: TButton; Panel18: TPanel; Button11: TButton; procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure fechaalbaranEnter(Sender: TObject); procedure btAnuevoClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure dsalbaranesStateChange(Sender: TObject); procedure comboclientesCloseUp(Sender: TObject); procedure combodestinosCloseUp(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure albaranesdetalleBeforePost(DataSet: TDataSet); procedure Button4Click(Sender: TObject); procedure albaranesdetalleAfterPost(DataSet: TDataSet); procedure btaimportarClick(Sender: TObject); procedure btaanteriorClick(Sender: TObject); procedure btasiguienteClick(Sender: TObject); procedure btaimprimirClick(Sender: TObject); procedure btAmodificarClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure dsalbaranesDataChange(Sender: TObject; Field: TField); procedure fechaalbaranCloseUp(Sender: TObject); procedure albaranesBeforePost(DataSet: TDataSet); procedure DBGrid3TitleClick(Column: TColumn); procedure DBGrid2KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DBGrid2ColExit(Sender: TObject); procedure qarticulosBeforeOpen(DataSet: TDataSet); procedure Button3Click(Sender: TObject); procedure DBGrid3DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure albaranesdetalleAfterDelete(DataSet: TDataSet); procedure albaranesdetalleBeforeDelete(DataSet: TDataSet); procedure btafacturarClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Edit1Enter(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure comboserie2CloseUp(Sender: TObject); procedure dsqseries2DataChange(Sender: TObject; Field: TField); procedure comboserieCloseUp(Sender: TObject); procedure btaduplicarClick(Sender: TObject); procedure Button7Click(Sender: TObject); procedure DBGrid2DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBGrid3DblClick(Sender: TObject); procedure Button9Click(Sender: TObject); procedure albaranesBeforeDelete(DataSet: TDataSet); procedure qalbaraneslotesAfterInsert(DataSet: TDataSet); procedure qalbaranespaletsAfterInsert(DataSet: TDataSet); procedure Button10Click(Sender: TObject); procedure Button11Click(Sender: TObject); private { Private declarations } public { Public declarations } procedure ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar = nil); end; var albaranes: Talbaranes; filtro,iddetalle:string; vidempresa,vidarticulo:string; implementation {$R *.dfm} uses fselectpedidos,fbuscararticulos, dlgduplicar, ftraza_materiales2; procedure Talbaranes.Edit1Enter(Sender: TObject); begin edit1.Text:=''; end; procedure Talbaranes.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 Talbaranes.albaranesBeforeDelete(DataSet: TDataSet); begin case dm.PedirConfirmacion('¿Confirma que desea borrar este albaran?',true,true,false) of mrno:Abort; end; end; procedure Talbaranes.albaranesBeforePost(DataSet: TDataSet); begin if albaranes.state in [dsinsert,dsedit] then begin if albaranes.state in [dsinsert] then begin albaranesnumpalets.value:=0; end; qclientes.Close; qdestinos.Close; qdestinos.LinkedFields:='Idempresa;idcliente'; qdestinos.MasterFields:='Idempresa;id'; qdestinos.Mastersource:=dsqclientes; qclientes.open; qdestinos.Open; end; end; procedure Talbaranes.albaranesdetalleAfterDelete(DataSet: TDataSet); var serie,id,idalbaran,pesobruto,pesoneto,pesonetoteorico,numpalets:string; begin serie:=albaranesserie.AsString; id:=albaranesid.AsString; idalbaran:=serie+'/'+id; qalbaranesiva.Refresh; if iddetalle<>'' then albaranesdetalle.Locate('id',iddetalle,[locaseinsensitive]) else albaranesdetalle.Last; qaux.SQL.Clear; qaux.SQL.Add('select * from ea_pesadas where idalbaran='+''''+idalbaran+''''+' and idempresa='+albaranesidempresa.asstring); qaux.open; if qaux.RecordCount>0 then begin qaux.SQL.Clear; qaux.SQL.Add('select sum(peso_bruto-tara0),sum(peso_neto),sum(peso_neto_teorico),sum(num_palets) from ea_pesadas where idalbaran='+''''+idalbaran+''''+' and idempresa='+albaranesidempresa.asstring); qaux.open; pesobruto:=qaux.fields[0].asstring; pesobruto:=stringreplace(pesobruto,',','.',[rfreplaceall]); pesoneto:=qaux.fields[1].asstring; pesoneto:=stringreplace(pesoneto,',','.',[rfreplaceall]); pesonetoteorico:=qaux.fields[2].asstring; pesonetoteorico:=stringreplace(pesonetoteorico,',','.',[rfreplaceall]); numpalets:=qaux.fields[3].asstring; numpalets:=stringreplace(numpalets,',','.',[rfreplaceall]); qaux.SQL.Clear; qaux.SQL.Add('update albaranes set peso_bruto='+pesobruto+',kilos=+'+pesoneto+',kilosventa='+pesonetoteorico+',numpalets=+'+numpalets+' where serie='+''''+serie+''''+' and id='+id+' and idempresa='+albaranesidempresa.AsString);; qaux.execsql; end else begin qaux.SQL.Clear; qaux.SQL.Add('update albaranes set peso_bruto=0,kilos=0,kilosventa=0,numpalets=0 where serie='+''''+serie+''''+' and id='+id+' and idempresa='+albaranesidempresa.AsString);; qaux.execsql; end; albaranes.refresh; albaranes.Locate('serie,id',vararrayof([serie,id]),[locaseinsensitive]) end; procedure Talbaranes.albaranesdetalleAfterPost(DataSet: TDataSet); var serie,id,idalbaran,pesobruto,pesoneto,pesonetoteorico,numpalets:string; begin serie:=albaranesserie.AsString; id:=albaranesid.AsString; idalbaran:=serie+'/'+id; qalbaranesiva.Refresh; qaux.SQL.Clear; qaux.SQL.Add('select * from ea_pesadas where idalbaran='+''''+idalbaran+''''+' and idempresa='+albaranesidempresa.asstring); qaux.open; if qaux.RecordCount>0 then begin qaux.SQL.Clear; qaux.SQL.Add('select sum(peso_bruto-tara0),sum(peso_neto),sum(peso_neto_teorico),(select max(palets) from albaranes_detalles where idalbaran='+id+' and serie='+serie+') as numpalets from ea_pesadas where idalbaran='+''''+idalbaran+''''+' and idempresa='+albaranesidempresa.asstring); qaux.open; pesobruto:=qaux.fields[0].asstring; pesobruto:=stringreplace(pesobruto,',','.',[rfreplaceall]); pesoneto:=qaux.fields[1].asstring; pesoneto:=stringreplace(pesoneto,',','.',[rfreplaceall]); pesonetoteorico:=qaux.fields[2].asstring; pesonetoteorico:=stringreplace(pesonetoteorico,',','.',[rfreplaceall]); numpalets:=qaux.fields[3].asstring; numpalets:=stringreplace(numpalets,',','.',[rfreplaceall]); qaux.SQL.Clear; qaux.SQL.Add('update albaranes set peso_bruto='+pesobruto+',kilos=+'+pesoneto+',kilosventa='+pesonetoteorico+',numpalets=+'+numpalets+' where serie='+''''+serie+''''+' and id='+id+' and idempresa='+albaranesidempresa.AsString);; qaux.execsql; end; albaranes.refresh; albaranes.Locate('serie,id',vararrayof([serie,id]),[locaseinsensitive]) ; if iddetalle<>'' then albaranesdetalle.Locate('id',iddetalle,[locaseinsensitive]) else albaranesdetalle.Last; end; procedure Talbaranes.albaranesdetalleBeforeDelete(DataSet: TDataSet); begin case dm.PedirConfirmacion('¿Confirma que desea borrar esta línea de albaran?',true,true,false) of mrno:Abort; end; vidempresa:=albaranesdetalleidempresa.AsString; vidarticulo:=albaranesdetalleidarticulo.asstring; end; procedure Talbaranes.albaranesdetalleBeforePost(DataSet: TDataSet); var iva,descuento:real; begin iddetalle:=albaranesdetalleid.asstring; if albaranesdetalletipoiva.AsString='' then albaranesdetalletipoiva.Value:=0; if albaranesdetalledescuento.AsString='' then albaranesdetalledescuento.Value:=0; if (albaranesdetallelote.AsString<>'') and (albaranesdetallecoste_otros.asstring='') then begin qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('select coste_kg_ref from parcelas where (codpar,empresa) in (select parcela,idempresa from lotes where codigo='+albaranesdetallelote.AsString+')'); qaux.Open; albaranesdetallecoste_otros.Value:=qaux.Fields[0].AsFloat; end; albaranesdetalleidempresa.Value:=albaranesidempresa.AsInteger; albaranesdetalleidalbaran.Value:=albaranesid.AsInteger; albaranesdetalleserie.Value:=albaranesserie.Asstring; albaranesdetallebase.Value:=albaranesdetalleprecio.AsFloat*albaranesdetallecantidad.AsFloat; descuento:=albaranesdetallebase.AsFloat*(albaranesdetalledescuento.AsFloat/100); albaranesdetalletotaldescuento.value:=descuento; albaranesdetalletotal.Value:=albaranesdetallebase.Asfloat-descuento; iva:=albaranesdetalletotal.AsFloat*(albaranesdetalletipoiva.AsFloat/100); albaranesdetalleiva.Value:=iva; if albaranesdetalle.State in [dsedit] then iddetalle:=albaranesdetalleid.AsString else iddetalle:=''; end; procedure Talbaranes.btAborrarClick(Sender: TObject); begin if albaranes.recordcount>0 then begin if albaranesfacturado.AsInteger=0 then BEGIN albaranes.Delete; albaranesdetalle.Refresh; qpedidos.Refresh; qpedidos2.Refresh; qpedidosdetalle.Refresh; qpedidosdetalle2.Refresh; qalbaranesiva.refresh; END else showmessage('¡¡¡ ALBARAN FACTURADO NO SE PUEDE BORRAR ¡¡¡'); end; end; procedure Talbaranes.btAcancelarClick(Sender: TObject); begin albaranes.Cancel; panel3.Enabled:=false; end; procedure Talbaranes.btaduplicarClick(Sender: TObject); var serie,fecha,idalbaran:string; begin serie:=albaranesserie.asstring; fecha:=albaranesfecha.Asstring; idalbaran:=albaranesid.Asstring; idempresa:=albaranesidempresa.AsString; fdlgduplicar := Tfdlgduplicar.Create(nil); try dlgduplicar.idserie:=serie; dlgduplicar.fecha:=fecha; dlgduplicar.idempresa:=idempresa; dlgduplicar.idalbaran:=idalbaran; fdlgduplicar.showmodal(); finally fdlgduplicar.Free; qseries2.Locate('id',idserie,[locaseinsensitive]); albaranes.refresh; albaranesdetalle.Refresh; albaranes.Locate('serie,id',vararrayof([idserie,idalbaran]),[locaseinsensitive]) end; end; procedure Talbaranes.btafacturarClick(Sender: TObject); var serie,empresa,idfactura,idalbaran,observaciones:string; begin facturas.Open; facturas.Append; facturasidempresa.Value:=albaranesidempresa.AsInteger; facturasserie.Value:=albaranesserie.asstring; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('select num_factura from series_numericas where ide='+albaranesidempresa.AsString+' and id='+''''+albaranesserie.AsString+''''); qaux.Open; facturasid.Value:=qaux.Fields[0].AsInteger; facturasiddestino.Value:=albaranesiddestino.Asstring; facturasidcliente.Value:=albaranesidcliente.AsInteger; facturasnif.Value:=albaranesnif.AsString; facturasdireccion.Value:=albaranesdireccion.asstring; facturaspoblacion.Value:=albaranespoblacion.asstring; facturasprovincia.Value:=albaranesprovincia.asstring; facturascodpost.Value:=albaranescodpost.asstring; facturasfecha.Value:=date(); facturasreferencia.Value:=albaranesreferencia.asstring; facturastelefono.Value:=albaranestelefono.asstring; facturasnomcliente.Value:=albaranesnomcliente.asstring; facturaspaiscliente.Value:=albaranespaiscliente.asstring; facturasnomdestino.Value:=albaranesnomdestino.asstring; facturasidformapago.Value:=albaranesidformapago.Asinteger; facturasdirecciondestino.Value:=albaranesdirecciondestino.asstring; facturaspoblaciondestino.Value:=albaranespoblaciondestino.asstring; facturascodpostdestino.Value:=albaranescodpostdestino.asstring; facturasprovinciadestino.Value:=albaranesprovinciadestino.asstring; facturaspaisdestino.Value:=albaranespaisdestino.asstring; facturasobservaciones.Value:=albaranesobservaciones.AsString; facturascomision.value:=albaranescomision.Value; facturascoste_transporte.value:=albaranescoste_transporte.Value; facturas.Post; albaranes.edit; albaranesidfactura.value:=facturasid.asinteger; albaranesfacturado.Value:=1; albaranesdocumento.Value:='Factura Nº: '+facturasid.AsString; albaranes.post; idfactura:=facturasid.asstring; serie:=facturasserie.AsString; empresa:=facturasidempresa.AsString; idalbaran:=albaranesid.asstring; observaciones:=facturasobservaciones.asstring; qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('update series_numericas set num_factura=num_factura+1 where ide='+empresa+' and id='+''''+serie+''''); qaux.ExecSQL; facturasdetalle.Open; facturasdetalle.Append; facturasdetalleidempresa.Value:=albaranesdetalleidempresa.AsInteger; facturasdetalleserie.value:=albaranesdetalleserie.asstring; facturasdetalleidfactura.Value:=strtoint(idfactura); facturasdetalledescripcion.Value:='Albaran '+idalbaran+' de fecha:'+albaranesfecha.AsString; facturasdetalletipoiva.value:=0; facturasdetalle.Post; qinsertarfacturasdetalles.close; qinsertarfacturasdetalles.prepare; qinsertarfacturasdetalles.ParamByName('EMPRESA').AsInteger:=facturasidempresa.AsInteger; qinsertarfacturasdetalles.ParamByName('FACTURA').AsInteger:=facturasid.AsInteger; qinsertarfacturasdetalles.ParamByName('ALBARAN').AsInteger:=albaranesid.AsInteger; qinsertarfacturasdetalles.ParamByName('SERIE').AsString:=facturasserie.AsString; qinsertarfacturasdetalles.ExecSQL; { qaux.Close; qaux.sql.clear; qaux.sql.add('insert into facturas_detalles (idempresa,serie,idfactura,idarticulo,descripcion,cal,lote,bultos,cantidad,precio,descuento,totaldescuento,base,tipoiva,iva,total,coste_transporte,coste_comision,coste_otros,palets)'); qaux.sql.add(' (SELECT '+''''+empresa+''''+' as idempresa,'+''''+serie+''''+' as serie,'+''''+idfactura+''''+' as idfactura,idarticulo,descripcion,cal,lote,bultos,cantidad,'); qaux.sql.add('precio,descuento,totaldescuento,base,tipoiva,iva,total,coste_transporte,coste_comision,coste_otros,palets'); qaux.sql.add(' FROM albaranes_detalles where (idalbaran,idempresa,serie) in (select id,idempresa,serie from albaranes where idfactura='+idfactura+' and idempresa='+empresa+' and serie='+''''+serie+''''+' and id='+idalbaran+'))'); qaux.execsql; } showmessage('¡¡¡ FACTURA CREADA CORRECTAMENTE CON EL NUMERO: '+SERIE+'/'+IDFACTURA+' ¡¡¡¡'); albaranes.edit; albaranesidfactura.value:=facturasid.asinteger; albaranesfacturado.Value:=1; albaranesdocumento.Value:='Factura Nº: '+facturasid.AsString; albaranes.post; serie:=albaranesserie.AsString; idalbaran:=albaranesid.Asstring; qaux.sql.clear; qaux.sql.add('update albaranes_detalles set idfactura='+facturasid.AsString+' where idempresa='+empresa+' and serie='+''''+serie+''''+' and idalbaran='+idalbaran); qaux.execsql; albaranes.Refresh; albaranes.Locate('idempresa,serie,id', vararrayof([empresa,serie,idalbaran]),[locaseinsensitive]); albaranesdetalle.refresh; end; procedure Talbaranes.btAguardarClick(Sender: TObject); var id,empresa,serie:string; insertando:integer; cantidad,coste_trans,total,comision:real; begin empresa:=albaranesidempresa.AsString; id:=albaranesid.AsString; serie:=albaranesserie.AsString; if albaranes.State in [dsinsert] then insertando:=1 else insertando:=0; albaranescccuentabancaria.Value:=qcuentasbanco.asstring+' '+qcuentascciban.asstring+qcuentasccentidad.asstring+qcuentasccoficina.asstring+qcuentasccdc.asstring+qcuentascccc.asstring; //albaranescomision.value:=qclientescomision.asfloat; albaranes.Post; if insertando=1 then begin qseries.edit; qseriesnum_albaran.Value:=qseriesnum_albaran.AsInteger+1; qseries.Post; end; if insertando=0 then begin qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('select sum(cantidad),sum(total) from albaranes_detalles where lote is not null and idempresa='+empresa+' and serie='+''''+serie+''''+' and idalbaran='+albaranesid.asstring); qaux.Open; cantidad:=qaux.Fields[0].AsFloat; total:=qaux.Fields[1].AsFloat; if (cantidad>0) and (albaranescoste_transporte.AsFloat>0) then begin coste_trans:=albaranescoste_transporte.AsFloat/cantidad; qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('update albaranes_detalles set coste_transporte=cantidad*'+stringreplace(floattostr(coste_trans),',','.',[rfreplaceall])+' where lote is not null and idempresa='+empresa+' and serie='+''''+serie+''''+' and idalbaran='+albaranesid.asstring+' and idarticulo<>(select codcomision from empresa where id='+albaranesidempresa.AsString+') and idarticulo<>(select codtransporte from empresa where id='+albaranesidempresa.AsString+')'); qaux.execsql; end; comision:=albaranescomision.AsFloat/100; qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('update albaranes_detalles set coste_comision=total*'+stringreplace(floattostr(comision),',','.',[rfreplaceall])+' where idempresa='+empresa+' and serie='+''''+serie+''''+' and idalbaran='+albaranesid.asstring+' and idarticulo<>(select codcomision from empresa where id='+albaranesidempresa.AsString+') and idarticulo<>(select codtransporte from empresa where id='+albaranesidempresa.AsString+')'); qaux.execsql; end; albaranesdetalle.open; albaranesdetalle.Refresh; albaranesdetalle.Last; albaranes.Refresh; albaranes.Locate('serie,id',vararrayof([serie,id]),[locaseinsensitive]); qalbaranesiva.Open; qalbaranesiva.Refresh; panel3.Enabled:=false; comboserie2.keyvalue:=qseriesid.AsString; albaranes.Close; albaranes.SQL.Clear; albaranes.SQL.Add('select * from albaranes where serie='+''''+qseriesid.AsString+''''+' order by serie desc,id desc'); albaranes.Open; albaranes.Locate('serie,id',vararrayof([serie,id]),[locaseinsensitive]); end; procedure Talbaranes.btAmodificarClick(Sender: TObject); begin if albaranesfacturado.AsInteger=0 then BEGIN panel3.Enabled:=true; albaranes.Edit; qclientes.Close; qclientes.SQL.Clear; qclientes.SQL.Add('select * from clientes order by nombre'); qclientes.open; qdestinos.Close; qdestinos.SQL.Clear; qdestinos.SQL.Add('select * from clientes_destinos order by descripcion'); qdestinos.open; comboserie.Enabled:=true; comboclientes.Enabled:=true; combodestinos.Enabled:=true; comboformapago.Enabled:=true; dbedit1.Enabled:=true; dbmemo2.Enabled:=true; dbedit2.Enabled:=true; dbgrid2.Enabled:=true; END else begin panel3.enabled:=true; comboserie.Enabled:=false; comboclientes.Enabled:=false; combodestinos.Enabled:=false; comboformapago.Enabled:=false; dbedit1.Enabled:=false; dbmemo2.Enabled:=false; dbedit2.Enabled:=false; //dbgrid2.Enabled:=false; costetrans.enabled:=true; comision.Enabled:=true; costetrans.SetFocus; end end; procedure Talbaranes.btAnuevoClick(Sender: TObject); begin panel3.Enabled:=true; comboserie.SetFocus; comboserie.KeyValue:=qseriesid.Asstring; //fechaalbaran.Date:=date; albaranes.Append; qclientes.Close; qclientes.SQL.Clear; qclientes.SQL.Add('select * from clientes order by nombre'); qclientes.open; qdestinos.Close; qdestinos.SQL.Clear; qdestinos.SQL.Add('select * from clientes_destinos order by descripcion'); qdestinos.open; albaranesdetalle.Close; qalbaranesiva.close; albaranesfecha.Value:=date; end; procedure Talbaranes.btaimprimirClick(Sender: TObject); var filtro,documento,formapago,pedidos,fechacarga,desg_ivas,base,iva,tipo,lotes,palets,variedades,cant_palets:string; fecha:tdate; begin if listaimpresion.ItemIndex=0 then begin dsalbaranesdetalle.DataSet:=albaranesdetallegrupo; {.SQL.Add('select idempresa,idalbaran,sum(cantidad) as cantidad,precio,descuento,sum(base) as base,descripcion,cal,sum(palets) as palets,sum(bultos) as bultos,tipoiva,sum(iva) as iva,sum(total) as total,id,'+''''''+' as idarticulo,sum(totaldescuento) as totaldescuento,'+''''''+' as lote,serie,coste_transporte,coste_otros'); albaranesdetalle.SQL.Add(',coste_comision,sum(pesobruto) as pesobruto,idfactura from albaranes_detalles group by idempresa,idalbaran,descripcion,cal,precio order by id');} end; if listaimpresion.ItemIndex=1 then begin dsalbaranesdetalle.DataSet:=albaranesdetalle; { albaranesdetalle.Close; albaranesdetalle.SQL.Clear; albaranesdetalle.SQL.Add('select * from albaranes_detalles order by id'); albaranesdetalle.open;} end; filtro:='id='; filtro:=filtro+albaranesid.asstring; filtro:=filtro+' and serie='+''''+albaranesserie.AsString+''''; if comboformulario.KeyValue=null then documento:=qseriesimp_albaran.AsString else documento:=qformulariosformulario.AsString; albaranes.Filter:=filtro; albaranes.filtered:=true; fecha:=albaranesfecha.AsDateTime; fecha:=fecha+qformaspagodias.asinteger; formapago:='FORMA DE PAGO: '+qformaspagodescripcion.AsString+' FECHA DE VENCIMIENTO EL '+DATETOSTR(FECHA); if albaranesccid.AsString<>'' then begin { qaux.SQL.Clear; qaux.SQL.Add('SELECT concat(banco,'+''''+' '+''''+',cciban,'+''''+'-'+''''+',ccentidad,'+''''+'-'+''''+',ccoficina,'+''''+'-'+''''+',ccdc,'+''''+'-'+''''+',cccc) FROM cuentas_bancarias where ide='+albaranesidempresa.AsString+' and id='+albaranesccid.asstring); qaux.open;} formapago:=formapago+' '+qaux.Fields[0].asstring; end; qalbaranesiva.First; desg_ivas:=''; while not qalbaranesiva.Eof do begin if qalbaranesivabase.AsFloat<>0 then begin tipo:=format('%2d',[qalbaranesivatipo.asinteger]); base:=format('%10.2f',[qalbaranesivabase.Asfloat]); iva:=format('%8.2f',[qalbaranesivaiva.asfloat]); desg_ivas:=desg_ivas+tipo+' '+iva; end; qalbaranesiva.Next; end; qalbaraneslotes.First; lotes:=''; variedades:=''; while not qalbaraneslotes.Eof do begin lotes:=lotes+qalbaranesloteslote.AsString+#13+#10; variedades:=variedades+qalbaraneslotesvariedad.AsString+#13+#10; qalbaraneslotes.Next; end; qalbaranespalets.First; palets:=''; cant_palets:=''; while not qalbaranespalets.Eof do begin palets:=palets+qalbaranespaletstipo_palet.AsString+#13+#10; cant_palets:=cant_palets+qalbaranespaletscantidad.asstring+#13+#10; // palets:=palets+qalbaranespaletstipo_palet.asstring+#9+#9+qalbaranespaletscantidad.AsString+#13+#10; qalbaranespalets.Next; end; pedidos:=''; qaux.SQL.Clear; qaux.SQL.Add('SELECT pedidocliente,fecha_carga FROM pedidos where (id,ide) in (select idpedido,ide from pedidosdetalle where idalbaran='+''''+albaranesserie.AsString+'/'+albaranesid.AsString+''''+')'); qaux.open; while not qaux.Eof do begin pedidos:=pedidos+' '+qaux.Fields[0].AsString; qaux.Next; end; fechacarga:=qaux.Fields[1].AsString; infalbaran.Datasource:=dsalbaranes; infdetallealbaran.Datasource:=dsalbaranesdetalle; infalbaranivas.Datasource:=dsqalbaranesiva; informe.Report.Clear; informe.LoadFromFile('c:\agrigest\informes\'+documento+'.fr3'); informe.Variables.Variables['FORMAPAGO']:=QUOTEDSTR(formapago); informe.Variables.Variables['PEDIDOS']:=QUOTEDSTR(pedidos); informe.Variables.Variables['FECHACARGA']:=QUOTEDSTR(fechacarga); informe.Variables.Variables['DESGIVAS']:=QUOTEDSTR(desg_ivas); informe.Variables.Variables['LOTES']:=QUOTEDSTR(lotes); informe.Variables.Variables['PALETS']:=QUOTEDSTR(palets); informe.Variables.Variables['CANTIDAD']:=QUOTEDSTR(cant_palets); informe.Variables.Variables['VARIEDAD']:=QUOTEDSTR(variedades); informe.ShowReport(); informe.Clear; // informe.Variables.Variables['TITULO']:=QUOTEDSTR(panel100.Caption); albaranes.filtered:=false; dsalbaranesdetalle.DataSet:=albaranesdetalle; { albaranesdetalle.Close; albaranesdetalle.SQL.Clear; albaranesdetalle.SQL.Add('select * from albaranes_detalles order by id'); albaranesdetalle.open;} end; procedure Talbaranes.btaimportarClick(Sender: TObject); var serie,idalbaran:string; begin serie:=albaranesserie.AsString; idalbaran:=albaranesid.AsString; seleccionarpedidos := Tseleccionarpedidos.Create(nil); try seleccionarpedidos.showmodal(); finally seleccionarpedidos.Free; albaranes.refresh; albaranes.Locate('serie,id',vararrayof([serie,idalbaran]),[locaseinsensitive]) end; end; procedure Talbaranes.Button10Click(Sender: TObject); begin qalbaraneslotes.Delete; end; procedure Talbaranes.Button11Click(Sender: TObject); begin qalbaranespalets.delete; end; procedure Talbaranes.Button1Click(Sender: TObject); var precio,serie,id:string; i:integer; begin serie:=albaranesserie.AsString; id:=albaranesid.AsString; if albaranesdetalle.RecordCount>0 then begin precio:=stringreplace((edit1.Text),'.',',',[rfreplaceall]); if dbgrid2.Selectedrows.Count>0 then begin for i := 0 to dbgrid2.Selectedrows.Count - 1 do begin albaranesdetalle.GotoBookmark ((dbgrid2.selectedrows[i])); albaranesdetalle.Edit; albaranesdetalleprecio.Value:=strtofloat(precio); albaranesdetalle.Post; end; end else begin albaranesdetalle.first; while not albaranesdetalle.Eof do begin if albaranesdetallecantidad.AsFloat>0 then begin albaranesdetalle.Edit; albaranesdetalleprecio.Value:=strtofloat(precio); albaranesdetalle.Post; end; albaranesdetalle.Next; end; end; end; albaranesdetalle.refresh; albaranes.Refresh; albaranes.Locate('serie,id',vararrayof([serie,id]),[locaseinsensitive]); end; procedure Talbaranes.Button2Click(Sender: TObject); var id,codcomision,empresa,serie:string; coste_trans,cantidad,comision:real; begin codcomision:=dm.tempresacodcomision.AsString; empresa:=albaranesidempresa.AsString; serie:=albaranesserie.AsString; id:=albaranesid.AsString; albaranesdetalle.Append; dbgrid2.Fields[0].Value:=codcomision; filtro:=albaranesdetalleidarticulo.asstring; qarticulos.Close; qarticulos.Open; if qarticulos.RecordCount>0 then begin qtipos_iva.Open; albaranesdetalledescripcion.value:=qarticulosdescripcion.AsString; if qclientesexento_iva.AsInteger=0 then albaranesdetalletipoiva.value:=qtipos_ivatipo.Asfloat else albaranesdetalletipoiva.value:=0; end; dbgrid2.Fields[7].Value:=-1; dbgrid2.Fields[8].Value:=albaranesneto.AsFloat*(albaranescomision.AsFloat/100); albaranesdetalle.Post; qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('select sum(cantidad),sum(total) from albaranes_detalles where lote is not null and idempresa='+empresa+' and serie='+''''+serie+''''+' and idalbaran='+albaranesid.asstring); qaux.Open; cantidad:=qaux.Fields[0].AsFloat; if (cantidad>0) and (albaranescoste_transporte.AsFloat>0) then begin coste_trans:=albaranescoste_transporte.AsFloat/cantidad; qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('update albaranes_detalles set coste_transporte=cantidad*'+stringreplace(floattostr(coste_trans),',','.',[rfreplaceall])+' where lote is not null and idempresa='+empresa+' and serie='+''''+serie+''''+' and idalbaran='+albaranesid.asstring+' and idarticulo<>(select codcomision from empresa where id='+albaranesidempresa.AsString+') and idarticulo<>(select codtransporte from empresa where id='+albaranesidempresa.AsString+')'); qaux.execsql; end; comision:=albaranescomision.AsFloat/100; qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('update albaranes_detalles set coste_comision=total*'+stringreplace(floattostr(comision),',','.',[rfreplaceall])+' where idempresa='+empresa+' and serie='+''''+serie+''''+' and idalbaran='+albaranesid.asstring+' and idarticulo<>(select codcomision from empresa where id='+albaranesidempresa.AsString+') and idarticulo<>(select codtransporte from empresa where id='+albaranesidempresa.AsString+')'); qaux.execsql; albaranes.Refresh; albaranes.Locate('serie,id',vararrayof([serie,id]),[locaseinsensitive]); albaranesdetalle.Refresh; albaranesdetalle.Last; qalbaranesiva.Refresh; end; procedure Talbaranes.Button3Click(Sender: TObject); var archivo:string; begin qalbaranesclientes.Close; qalbaranesclientes.SQL.Clear; qalbaranesclientes.SQL.Add('(select a.*,ad.*,l.parcela from albaranes a,albaranes_detalles ad,lotes l where l.idempresa=ad.idempresa and l.codigo=ad.lote and a.idempresa=ad.idempresa and a.serie=ad.serie and a.id=ad.idalbaran and a.serie='+''''+qseries2id.AsString+''''+') '); qalbaranesclientes.SQL.Add(' union ALL '); qalbaranesclientes.SQL.Add('(select a.*,ad.*,'+''''+' '+''''+' as parcela from albaranes a,albaranes_detalles ad where ad.lote is null and a.idempresa=ad.idempresa and a.serie=ad.serie and a.id=ad.idalbaran and a.serie='+''''+qseries2id.AsString+''''+') order by fecha desc'); qalbaranesclientes.open; savedialog1.FileName:='ALBARANES CLIENTES.xlsx'; savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'ALBARANES',gridalbaranesaexcel); finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure Talbaranes.Button4Click(Sender: TObject); var serie,id:string; begin if albaranesdetalle.recordcount>0 then begin serie:=albaranesserie.AsString; id:=albaranesid.AsString; albaranesdetalle.Delete; albaranesdetalle.Refresh; // albaranes.Refresh; // albaranes.Locate('serie;id',vararrayof([serie,id]),[locaseinsensitive,lopartialkey]); qalbaranesiva.Refresh; end; end; procedure Talbaranes.Button5Click(Sender: TObject); var id,codtransporte,empresa,serie:string; coste_trans,cantidad,comision:real; begin id:=albaranesid.AsString; empresa:=albaranesidempresa.AsString; serie:=albaranesserie.AsString; codtransporte:=dm.tempresacodtransporte.AsString; albaranesdetalle.Append; dbgrid2.Fields[0].Value:=codtransporte; filtro:=albaranesdetalleidarticulo.asstring; qarticulos.Close; qarticulos.Open; if qarticulos.RecordCount>0 then begin qtipos_iva.Open; albaranesdetalledescripcion.value:=qarticulosdescripcion.AsString; if qclientesexento_iva.AsInteger=0 then albaranesdetalletipoiva.value:=qtipos_ivatipo.Asfloat else albaranesdetalletipoiva.value:=0; end; dbgrid2.Fields[7].Value:=-1; dbgrid2.Fields[8].Value:=albaranescoste_transporte.AsFloat; albaranesdetalle.Post; qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('select sum(cantidad),sum(total) from albaranes_detalles where lote is not null and idempresa='+empresa+' and serie='+''''+serie+''''+' and idalbaran='+albaranesid.asstring); qaux.Open; cantidad:=qaux.Fields[0].AsFloat; if (cantidad>0) and (albaranescoste_transporte.AsFloat>0) then begin coste_trans:=albaranescoste_transporte.AsFloat/cantidad; qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('update albaranes_detalles set coste_transporte=cantidad*'+stringreplace(floattostr(coste_trans),',','.',[rfreplaceall])+' where lote is not null and idempresa='+empresa+' and serie='+''''+serie+''''+' and idalbaran='+albaranesid.asstring+' and idarticulo<>(select codcomision from empresa where id='+albaranesidempresa.AsString+') and idarticulo<>(select codtransporte from empresa where id='+albaranesidempresa.AsString+')'); qaux.execsql; end; comision:=albaranescomision.AsFloat/100; qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('update albaranes_detalles set coste_comision=total*'+stringreplace(floattostr(comision),',','.',[rfreplaceall])+' where idempresa='+empresa+' and serie='+''''+serie+''''+' and idalbaran='+albaranesid.asstring+' and idarticulo<>(select codcomision from empresa where id='+albaranesidempresa.AsString+') and idarticulo<>(select codtransporte from empresa where id='+albaranesidempresa.AsString+')'); qaux.execsql; albaranes.Refresh; albaranes.Locate('serie,id',vararrayof([serie,id]),[locaseinsensitive]); albaranesdetalle.Refresh; albaranesdetalle.Last; qalbaranesiva.Refresh; end; procedure Talbaranes.Button7Click(Sender: TObject); begin traza_materiales2 := Ttraza_materiales2.Create(nil); try traza_materiales2.qpesadas.close; traza_materiales2.qpesadas.SQL.Clear; traza_materiales2.qpesadas.SQL.Add('select mat.idea,mat.idea2,mat.idaf,af.descripcion,mat.cantidad,mat.lote,e.documento as doc_compra,p.nombre as proveedor,:documento as documento from ea_materiales mat ,articulosf af,entradas_detalle ed,entradas e,proveedores p where'); traza_materiales2.qpesadas.SQL.Add('mat.idaf=af.id and mat.ide=af.idempresa and mat.idaf=ed.id_propio and mat.lote=ed.lote and ed.identrada=e.id and mat.ide=e.idempresa and e.idproveedor=p.id and'); traza_materiales2.qpesadas.SQL.Add(' (ide,idea,idea2) in (select idempresa,id,idea from ea_pesadas where idalbaran=:documento) order by idaf,idea,idea2'); traza_materiales2.qpesadas.ParamByName('documento').AsString:=albaranesserie.AsString+'/'+albaranesid.AsString; traza_materiales2.qpesadas.prepare; traza_materiales2.qpesadas.open; traza_materiales2.DBGrid2.Columns[0].Title.caption:='Albaran'; traza_materiales2.showmodal(); finally traza_materiales2.Free; end; end; procedure Talbaranes.Button9Click(Sender: TObject); var cabecera,embalajes,lineas,localizaciones,marcas:textfile; campo,tipo,ruta,archivo,cadena,parteentera,partedecimal,linea,vdia,vmes,vanyo:string; largo,num_envases,num_bultos:real; i,largototal,decimales,encontrado,numlinea,idenvase:integer; dia,mes,anyo:word; begin SaveDialog1.FileName := 'CABALB.TXT'; SaveDialog1.Execute(); ruta:= extractfilepath(savedialog1.filename); try assignfile(cabecera, ruta+'CABALB.TXT'); rewrite(cabecera); assignfile(embalajes, ruta+'EMBALB.TXT'); rewrite(embalajes); assignfile(lineas, ruta+'LINALB.TXT'); rewrite(lineas); assignfile(localizaciones, ruta+'LOCALB.TXT'); rewrite(localizaciones); assignfile(marcas, ruta+'MARCALB.TXT'); rewrite(marcas); if dbgrid3.SelectedRows.Count>0 then for i := 0 to dbgrid3.Selectedrows.Count - 1 do begin albaranes.GotoBookmark ((dbgrid3.selectedrows[i])); qedicabecera.close; qedicabecera.Prepare; qedicabecera.ParamByName('SERIE').Asstring:=albaranesserie.asstring; qedicabecera.ParamByName('ALBARAN').Asinteger:=albaranesid.asinteger; qedicabecera.open; qediembalajes.Close; qediembalajes.Prepare; qediembalajes.ParamByName('ALBARAN').AsString:=albaranesserie.AsString+'/'+albaranesid.AsString; qediembalajes.Open; qedilocalizaciones.close; qedilocalizaciones.Prepare; qedilocalizaciones.ParamByName('SERIE').Asstring:=albaranesserie.asstring; qedilocalizaciones.ParamByName('ALBARAN').Asinteger:=albaranesid.asinteger; qedilocalizaciones.open; qedilinalbaran.close; qedilinalbaran.Prepare; qedilinalbaran.ParamByName('SERIE').Asstring:=albaranesserie.asstring; qedilinalbaran.ParamByName('ALBARAN').Asinteger:=albaranesid.asinteger; qedilinalbaran.open; ///// CABECERA ALBARAN qedi_cabalbaran.Open; qedi_cabalbaran.First; linea:=''; while not qedi_cabalbaran.Eof do begin campo:=qedi_cabalbarancampo.AsString; largo:=qedi_cabalbaranlongitud.AsFloat; cadena:=formatfloat('#####.0',largo); parteentera:= copy(cadena,0,pos(',',cadena)-1); largototal:=strtoint(parteentera); partedecimal:= copy(cadena,pos(',',cadena)+1,length(Cadena)); decimales:=strtoint(partedecimal); tipo:=qedi_cabalbarantipo.AsString; cadena:=''; if tipo='X' then begin //campo:=copy(campo,0,largototal-1); if campo='IDCAB' then begin cadena:=qedicabeceraidcab.AsString; end; if campo='NUMDES' then begin cadena:=qedicabeceranumdes.AsString; end; if campo='TIPO' then begin cadena:=qedicabeceratipo.AsString; end; if campo='FUNCION' then begin cadena:='9'; end; if campo='DPTO' then begin cadena:=qedicabeceradpto.asstring; end; if campo='FECDES' then begin decodedate(qedicabecerafecdes.AsDateTime,anyo,mes,dia); vdia:=inttostr(dia); vdia:=StringOfChar('0', 2 - length(vdia))+vdia; vmes:=inttostr(mes); vmes:=StringOfChar('0', 2 - length(vmes))+vmes; vanyo:=inttostr(anyo); vanyo:=StringOfChar('0', 2 - length(vanyo))+vanyo; cadena:=vanyo+vmes+vdia; end; if campo='FECPED' then begin decodedate(qedicabecerafecped.AsDateTime,anyo,mes,dia); vdia:=inttostr(dia); vdia:=StringOfChar('0', 2 - length(vdia))+vdia; vmes:=inttostr(mes); vmes:=StringOfChar('0', 2 - length(vmes))+vmes; vanyo:=inttostr(anyo); vanyo:=StringOfChar('0', 2 - length(vanyo))+vanyo; cadena:=vanyo+vmes+vdia; end; if campo='FECENT' then begin decodedate(qedicabecerafecent.AsDateTime,anyo,mes,dia); vdia:=inttostr(dia); vdia:=StringOfChar('0', 2 - length(vdia))+vdia; vmes:=inttostr(mes); vmes:=StringOfChar('0', 2 - length(vmes))+vmes; vanyo:=inttostr(anyo); vanyo:=StringOfChar('0', 2 - length(vanyo))+vanyo; cadena:=vanyo+vmes+vdia; end; if campo='NUMALB' then begin if qedicabeceraalbarancliente.AsString<>'' then cadena:=qedicabeceraalbarancliente.AsString else cadena:=qedicabeceranumalb.AsString; end; if campo='FECALB' then begin decodedate(qedicabecerafecalb.AsDateTime,anyo,mes,dia); vdia:=inttostr(dia); vdia:=StringOfChar('0', 2 - length(vdia))+vdia; vmes:=inttostr(mes); vmes:=StringOfChar('0', 2 - length(vmes))+vmes; vanyo:=inttostr(anyo); vanyo:=StringOfChar('0', 2 - length(vanyo))+vanyo; cadena:=vanyo+vmes+vdia; end; if campo='NUMPED' then begin cadena:=qedicabeceranumped.AsString; end; if campo='ORIGEN' then begin cadena:=qedicabeceraorigen.AsString; end; if campo='DESTINO' then begin cadena:=qedicabeceradestino.AsString; end; if campo='PROVEEDO' then begin cadena:=qedicabeceraorigen.AsString; //cadena:=qedicabeceraproveedo.AsString; end; if campo='COMPRADO' then begin cadena:=qedicabeceracomprado.AsString; end; if campo='RECEPTOR' then begin cadena:=qedicabecerareceptor.Asstring; end; if campo='FECENV' then begin decodedate(qedicabecerafecenv.AsDateTime,anyo,mes,dia); vdia:=inttostr(dia); vdia:=StringOfChar('0', 2 - length(vdia))+vdia; vmes:=inttostr(mes); vmes:=StringOfChar('0', 2 - length(vmes))+vmes; vanyo:=inttostr(anyo); vanyo:=StringOfChar('0', 2 - length(vanyo))+vanyo; cadena:=vanyo+vmes+vdia; end; if campo='CODPROV' then begin cadena:=qedicabeceracodprov.AsString; end; if campo='NOMBREEMISOR' then begin cadena:=qedicabeceranombreemisor.asstring; end; if campo='NIFEMISOR' then begin cadena:=qedicabeceranifemisor.asstring; end; if campo='NIFPROVEEDOR' then begin cadena:=qedicabeceranifemisor.asstring; end; if campo='PAISPROVEEDOR' then begin cadena:='ESP'; end; if campo='NOMBRERECEPTOR' then begin cadena:=qedicabeceranombrereceptor.asstring; end; if campo='NOMBRECOMPRADOR' then begin cadena:=qedicabeceranombrecomprador.asstring; end; if campo='NOMBREPROVEEDOR' then begin cadena:=qedicabeceranombreemisor.asstring; //cadena:=qedicabeceranombreproveedor.asstring; end; if campo='NOMBREPTOENTREGA' then begin cadena:=qedicabeceranombreptoentrega.asstring; end; if campo='DIRECCIONEMISOR' then begin cadena:=qedicabeceradireccionemisor.asstring; end; if campo='POBLACIONEMISOR' then begin cadena:=qedicabecerapoblacionemisor.asstring; end; if campo='PROVINCIAEMISOR' then begin cadena:=qedicabeceraprovinciaemisor.asstring; end; if campo='CPEMISOR' then begin cadena:=qedicabeceracpemisor.asstring; end; if campo='DIRECCIONPROVEEDOR' then begin cadena:=qedicabeceradireccionemisor.asstring; end; if campo='POBLACIONPROVEEDOR' then begin cadena:=qedicabecerapoblacionemisor.asstring; end; if campo='PROVINCIAPROVEEDOR' then begin cadena:=qedicabeceraprovinciaemisor.asstring; end; if campo='CPPROVEEDOR' then begin cadena:=qedicabeceracpemisor.asstring; end; if campo='DIRECCIONCOMPRADOR' then begin cadena:=qedicabeceradireccioncomprador.asstring; end; if campo='POBLACIONCOMPRADOR' then begin cadena:=qedicabecerapoblacioncomprador.asstring; end; if campo='PROVINCIACOMPRADOR' then begin cadena:=qedicabeceraprovinciacomprador.asstring; end; if campo='CPCOMPRADOR' then begin cadena:=qedicabeceracpcomprador.asstring; end; if campo='DIRECCIONPTOENTREGA' then begin cadena:=qedicabeceradireccionptoentrega.asstring; end; if campo='POBLACIONPTOENTREGA' then begin cadena:=qedicabecerapoblacionptoentrega.asstring; end; if campo='PROVINCIAPTOENTREGA' then begin cadena:=qedicabeceraprovinciaptoentrega.asstring; end; if campo='CPPTOENTREGA' then begin cadena:=qedicabeceracpptoentrega.asstring; end; if campo='DIRECCIONRECEPTOR' then begin cadena:=qedicabeceradireccionreceptor.asstring; end; if campo='POBLACIONRECEPTOR' then begin cadena:=qedicabecerapoblacionreceptor.asstring; end; if campo='PROVINCIARECEPTOR' then begin cadena:=qedicabeceraprovinciareceptor.asstring; end; if campo='CPRECEPTOR' then begin cadena:=qedicabeceracpreceptor.asstring; end; if campo='NIFPROVEEDOR' then begin cadena:=qedicabeceranifemisor.asstring; //cadena:=qedicabeceranifproveedor.asstring; end; if campo='MONEDA' then begin cadena:=qedicabeceramoneda.asstring; end; if campo='MEDIOTRAN' then begin cadena:=qedicabeceramediotran.asstring; end; if campo='ORDENADOR' then begin cadena:=qedicabeceraordenador.asstring; end; if campo='NOMCONREC' then begin cadena:='PERECEDEROS'; end; if campo='ULTCONS' then begin cadena:=qedicabeceraultcons.asstring; end; cadena:=copy(cadena,0,largototal); linea:= linea + cadena + StringOfChar(' ', largototal - length(cadena)); end; if tipo='N' then begin largo:=0; if campo='TOTQTY' then begin largo:=qedicabeceratotqty.Asfloat; end; if campo='IMPTOTBRUTO' then begin largo:=qedicabeceraimptotbruto.Asfloat; end; if campo='IMPTOTNETO' then begin largo:=qedicabeceraimptotneto.Asfloat; end; if campo='PESOBRUTOT' then begin largo:=qedicabecerapesobrutot.Asfloat; end; if campo='PESONETTOT' then begin largo:=qedicabecerapesonettot.Asfloat; end; if campo='NUMTOTBUL' then begin largo:=qedicabeceranumtotbul.Asfloat; end; if largo>0 then begin case decimales of 0:cadena:=formatfloat('#####',largo); 1:cadena:=formatfloat('#####.0',largo); 2:cadena:=formatfloat('#####.00',largo); 3:cadena:=formatfloat('#####.000',largo); 4:cadena:=formatfloat('#####.0000',largo); 5:cadena:=formatfloat('#####.00000',largo); end; // cadena:=floattostrf(largo,ffGeneral,largototal,decimales); linea:=linea+ StringOfChar('0', largototal - length(cadena))+cadena; end else begin cadena:=''; cadena:=copy(cadena,0,largototal); linea:= linea + cadena + StringOfChar(' ', largototal - length(cadena)); end; end; qedi_cabalbaran.next; end; writeln(cabecera, linea ); ///// EMBALAJES idenvase:=1; while not qediembalajes.eof do begin qedi_embalbaran.Open; qedi_embalbaran.First; linea:=''; while not qedi_embalbaran.Eof do begin campo:=qedi_embalbarancampo.AsString; largo:=qedi_embalbaranlongitud.AsFloat; cadena:=formatfloat('#####.0',largo); parteentera:= copy(cadena,0,pos(',',cadena)-1); largototal:=strtoint(parteentera); partedecimal:= copy(cadena,pos(',',cadena)+1,length(Cadena)); decimales:=strtoint(partedecimal); tipo:=qedi_embalbarantipo.AsString; cadena:=''; if tipo='X' then begin if campo='IDCAB' then begin cadena:=qediembalajesidcab.asstring; end; if campo='IDEMB' then begin cadena:=qediembalajescpso.asstring; { cadena:=inttostr(idenvase); if qediembalajescpso.AsString='1' then begin idenvase:=idenvase+1; end;} end; if campo='CPS' then begin cadena:=qediembalajescpso.asstring; { if pos('PALET',qediembalajesdescemb.asstring)>0 then begin cadena:='1';//qediembalajescpso.asstring; end else begin cadena:=inttostr(numlinea); if qediembalajescpso.AsString='1' then begin numlinea:=numlinea+1; end; end;} end; if campo='CPSPADRE' then begin if pos('PALET',qediembalajesdescemb.asstring)>0 then begin cadena:='';//qediembalajescpso.asstring; end else cadena:='1'; end; if campo='TIPEMB' then begin encontrado:=0; cadena:=qediembalajesdescemb.asstring; if encontrado=0 then encontrado:=pos('CARTON',cadena); if encontrado>0 then begin cadena:='CT'; encontrado:=-1; end; if encontrado=0 then encontrado:=pos('PALET',cadena); if encontrado>0 then cadena:='09'; if encontrado=0 then cadena:='CS'; end; if campo='DESCEMB' then begin cadena:=qediembalajesdescemb.asstring; end; if campo='PAGRET' then begin cadena:=qediembalajespagret.asstring; end; if campo='SSCC1' then begin if pos('PALET',qediembalajesdescemb.asstring)>0 then begin cadena:='';//qediembalajescpso.asstring; end else cadena:=qediembalajessscc1.asstring; end; if campo='FORMATO' then begin cadena:=qediembalajesformato.asstring; end; cadena:=copy(cadena,0,largototal); linea:= linea + cadena + StringOfChar(' ', largototal - length(cadena)); end; if tipo='N' then begin largo:=0; if campo='CANTEMB' then begin // num_envases:=num_envases+qediembalajescantemb.Asfloat; num_envases:=qediembalajescantemb.Asfloat; largo:=num_envases; end; if campo='BULTPALET' then begin num_bultos:=qediembalajesbultpalet.Asfloat; // num_bultos:=num_bultos+qediembalajesbultpalet.Asfloat; largo:=num_bultos end; if largo>0 then begin case decimales of 0:cadena:=formatfloat('#####',largo); 1:cadena:=formatfloat('#####.0',largo); 2:cadena:=formatfloat('#####.00',largo); 3:cadena:=formatfloat('#####.000',largo); 4:cadena:=formatfloat('#####.0000',largo); 5:cadena:=formatfloat('#####.00000',largo); end; // cadena:=floattostrf(largo,ffGeneral,largototal,decimales); linea:=linea+ StringOfChar('0', largototal - length(cadena))+cadena; end else begin cadena:=''; cadena:=copy(cadena,0,largototal); linea:= linea + cadena + StringOfChar(' ', largototal - length(cadena)); end; end; qedi_embalbaran.next; end; writeln(embalajes, linea ); qediembalajes.Next; end; ///// MARCAS qediembalajes.First; numlinea:=1; while not qediembalajes.eof do begin qedi_marcasembalaje.Open; qedi_marcasembalaje.First; linea:=''; while not qedi_marcasembalaje.Eof do begin campo:=qedi_marcasembalajecampo.AsString; largo:=qedi_marcasembalajelongitud.AsFloat; cadena:=formatfloat('#####.0',largo); parteentera:= copy(cadena,0,pos(',',cadena)-1); largototal:=strtoint(parteentera); partedecimal:= copy(cadena,pos(',',cadena)+1,length(Cadena)); decimales:=strtoint(partedecimal); tipo:=qedi_marcasembalajetipo.AsString; cadena:=''; if tipo='X' then begin if campo='IDCAB' then begin cadena:=qediembalajesidcab.asstring; end; if campo='IDEMB' then begin cadena:=qediembalajescpso.asstring; end; if campo='IDLIN' then begin cadena:='0';//inttostr(numlinea);//qediembalajesidLIN.asstring; end; if campo='IDMARCA' then begin cadena:=inttostr(numlinea);//qediembalajesidMARCA.asstring; end; if campo='MARCA1' then begin cadena:=qediembalajesMARCA1.asstring; end; if campo='SSCC' then begin if pos('PALET',qediembalajesdescemb.asstring)>0 then begin cadena:='';//qediembalajescpso.asstring; end else cadena:=qediembalajessscc1.asstring; end; if campo='FECENV' then begin decodedate(qediembalajesfecenv.AsDateTime,anyo,mes,dia); vdia:=inttostr(dia); vdia:=StringOfChar('0', 2 - length(vdia))+vdia; vmes:=inttostr(mes); vmes:=StringOfChar('0', 2 - length(vmes))+vmes; vanyo:=inttostr(anyo); vanyo:=StringOfChar('0', 2 - length(vanyo))+vanyo; if pos('PALET',qediembalajesdescemb.asstring)>0 then begin cadena:='';//qediembalajescpso.asstring; end else cadena:=vanyo+vmes+vdia; end; if campo='LOTE' then begin cadena:=qediembalajesLOTE.asstring; end; cadena:=copy(cadena,0,largototal); linea:= linea + cadena + StringOfChar(' ', largototal - length(cadena)); end; if tipo='N' then begin largo:=0; if largo>0 then begin case decimales of 0:cadena:=formatfloat('#####',largo); 1:cadena:=formatfloat('#####.0',largo); 2:cadena:=formatfloat('#####.00',largo); 3:cadena:=formatfloat('#####.000',largo); 4:cadena:=formatfloat('#####.0000',largo); 5:cadena:=formatfloat('#####.00000',largo); end; // cadena:=floattostrf(largo,ffGeneral,largototal,decimales); linea:=linea+ StringOfChar('0', largototal - length(cadena))+cadena; end else begin cadena:=''; cadena:=copy(cadena,0,largototal); linea:= linea + cadena + StringOfChar(' ', largototal - length(cadena)); end; end; qedi_marcasembalaje.next; end; writeln(marcas, linea ); qediembalajes.Next; numlinea:=numlinea+1; end; ////LINEAS ALBARAN qedilinalbaran.First; numlinea:=1; idenvase:=2; while not qedilinalbaran.eof do begin qedi_detalbaran.Open; qedi_detalbaran.First; linea:=''; while not qedi_detalbaran.Eof do begin campo:=qedi_detalbarancampo.AsString; largo:=qedi_detalbaranlongitud.AsFloat; cadena:=formatfloat('#####.0',largo); parteentera:= copy(cadena,0,pos(',',cadena)-1); largototal:=strtoint(parteentera); partedecimal:= copy(cadena,pos(',',cadena)+1,length(Cadena)); decimales:=strtoint(partedecimal); tipo:=qedi_detalbarantipo.AsString; cadena:=''; if tipo='X' then begin if campo='IDCAB' then begin cadena:=qedilinalbaranidcab.asstring; end; if campo='IDEMB' then begin cadena:=qedilinalbarancpso.asstring; { cadena:=inttostr(idenvase); if qedilinalbarancpso.AsString='1' then begin idenvase:=idenvase+1; end;} end; if campo='IDLIN' then begin cadena:=inttostr(numlinea);//qedilinalbaranidlin.asstring; numlinea:=numlinea+1; end; if campo='EAN' then begin cadena:=qedilinalbaranean.asstring; end; if campo='NUMEXP' then begin if qedilinalbarannumexp2.AsString='' then cadena:=qedilinalbarannumexp.asstring else cadena:=qedilinalbarannumexp2.asstring; end; if campo='DESCRIP' then begin cadena:=qedilinalbarandescrip.asstring; end; if campo='TIPART' then begin cadena:='CU'; end; if campo='NUMPED' then begin cadena:=qedilinalbarannumped.asstring; end; if campo='NUMALB' then begin if qedilinalbaranalbarancliente.AsString<>'' then cadena:=qedilinalbaranalbarancliente.AsString else cadena:=qedilinalbarannumalb.asstring; end; if campo='SSCC1' then begin cadena:=qedilinalbaransscc.asstring; end; if campo='FECENV' then begin decodedate(qedilinalbaranfecenv.AsDateTime,anyo,mes,dia); vdia:=inttostr(dia); vdia:=StringOfChar('0', 2 - length(vdia))+vdia; vmes:=inttostr(mes); vmes:=StringOfChar('0', 2 - length(vmes))+vmes; vanyo:=inttostr(anyo); vanyo:=StringOfChar('0', 2 - length(vanyo))+vanyo; cadena:=vanyo+vmes+vdia; end; if campo='LOTE' then begin cadena:=qedilinalbaranLOTE.asstring; end; if campo='DESTINO' then begin cadena:=qedilinalbarannombreptoentrega.asstring; end; if campo='FECPED' then begin decodedate(qedilinalbaranfecped.AsDateTime,anyo,mes,dia); vdia:=inttostr(dia); vdia:=StringOfChar('0', 2 - length(vdia))+vdia; vmes:=inttostr(mes); vmes:=StringOfChar('0', 2 - length(vmes))+vmes; vanyo:=inttostr(anyo); vanyo:=StringOfChar('0', 2 - length(vanyo))+vanyo; cadena:=vanyo+vmes+vdia; end; if campo='FECALB' then begin decodedate(qedilinalbaranfecalb.AsDateTime,anyo,mes,dia); vdia:=inttostr(dia); vdia:=StringOfChar('0', 2 - length(vdia))+vdia; vmes:=inttostr(mes); vmes:=StringOfChar('0', 2 - length(vmes))+vmes; vanyo:=inttostr(anyo); vanyo:=StringOfChar('0', 2 - length(vanyo))+vanyo; cadena:=vanyo+vmes+vdia; end; if campo='FECCADET' then begin decodedate(qedilinalbaranfeccadet.AsDateTime,anyo,mes,dia); vdia:=inttostr(dia); vdia:=StringOfChar('0', 2 - length(vdia))+vdia; vmes:=inttostr(mes); vmes:=StringOfChar('0', 2 - length(vmes))+vmes; vanyo:=inttostr(anyo); vanyo:=StringOfChar('0', 2 - length(vanyo))+vanyo; cadena:=vanyo+vmes+vdia; end; if campo='REFPROV' then begin cadena:=qedilinalbaranrefprov.asstring; end; if campo='UNICANT' then begin cadena:=qedilinalbaranunicant.asstring; end; if campo='TEXTO4' then begin cadena:=qedilinalbarantexto4.asstring; end; if campo='TEXTO5' then begin cadena:=qedilinalbarantexto5.asstring; end; if campo='FECCON' then begin decodedate(qedilinalbaranfeccon.AsDateTime,anyo,mes,dia); vdia:=inttostr(dia); vdia:=StringOfChar('0', 2 - length(vdia))+vdia; vmes:=inttostr(mes); vmes:=StringOfChar('0', 2 - length(vmes))+vmes; vanyo:=inttostr(anyo); vanyo:=StringOfChar('0', 2 - length(vanyo))+vanyo; cadena:=vanyo+vmes+vdia; end; cadena:=copy(cadena,0,largototal); linea:= linea + cadena + StringOfChar(' ', largototal - length(cadena)); end; if tipo='N' then begin largo:=0; if campo='CENVFAC' then begin largo:=qedilinalbarancenvfac.Asfloat; end; if campo='CUEXP' then begin if qedilinalbarancuexp.Asfloat=0 then largo:=1 else largo:=qedilinalbarancuexp.Asfloat; end; if campo='CANTLOC1' then begin largo:=qedilinalbarancantloc1.Asfloat; end; if campo='PESTOTLIN' then begin if qedilinalbarancuexp.Asfloat=0 then largo:=qedilinalbaranpestotlin.Asfloat else largo:=0; end; if campo='PESOBRUTO' then begin largo:=qedilinalbaranpesobruto.Asfloat; end; if campo='PESONETO' then begin largo:=qedilinalbaranpesoneto.Asfloat; end; if largo>0 then begin case decimales of 0:cadena:=formatfloat('#####',largo); 1:cadena:=formatfloat('#####.0',largo); 2:cadena:=formatfloat('#####.00',largo); 3:cadena:=formatfloat('#####.000',largo); 4:cadena:=formatfloat('#####.0000',largo); 5:cadena:=formatfloat('#####.00000',largo); end; // cadena:=floattostrf(largo,ffGeneral,largototal,decimales); linea:=linea+ StringOfChar('0', largototal - length(cadena))+cadena; end else begin cadena:=''; cadena:=copy(cadena,0,largototal); linea:= linea + cadena + StringOfChar(' ', largototal - length(cadena)); end; end; qedi_detalbaran.next; end; writeln(lineas, linea ); qedilinalbaran.Next; end; /// LOCALIZACIONES /// qedilocalizaciones.First; numlinea:=1; while not qedilocalizaciones.eof do begin qedi_lugaresentrega.Open; qedi_lugaresentrega.First; linea:=''; while not qedi_lugaresentrega.Eof do begin campo:=qedi_lugaresentregacampo.AsString; largo:=qedi_lugaresentregalongitud.AsFloat; cadena:=formatfloat('#####.0',largo); parteentera:= copy(cadena,0,pos(',',cadena)-1); largototal:=strtoint(parteentera); partedecimal:= copy(cadena,pos(',',cadena)+1,length(Cadena)); decimales:=strtoint(partedecimal); tipo:=qedi_lugaresentregatipo.AsString; cadena:=''; if tipo='X' then begin if campo='IDCAB' then begin cadena:=qedilocalizacionesidcab.asstring; end; if campo='IDEMB' then begin cadena:=qedilocalizacionesidemb.asstring; end; if campo='IDLIN' then begin cadena:=inttostr(numlinea);//qedilocalizacionesidlin.asstring; numlinea:=numlinea+1; end; if campo='IDLOC' then begin cadena:=qedilocalizacionesidloc.asstring; end; if campo='LUGAR' then begin cadena:=qedilocalizacioneslugar.asstring; end; if campo='FECHAENT' then begin decodedate(qedilocalizacionesfecenv.AsDateTime,anyo,mes,dia); vdia:=inttostr(dia); vdia:=StringOfChar('0', 2 - length(vdia))+vdia; vmes:=inttostr(mes); vmes:=StringOfChar('0', 2 - length(vmes))+vmes; vanyo:=inttostr(anyo); vanyo:=StringOfChar('0', 2 - length(vanyo))+vanyo; cadena:=vanyo+vmes+vdia; end; if campo='NOMBREPTOENTREGA' then begin cadena:=qedilocalizacionesnombreptoentrega.asstring; end; if campo='UMEDIDA' then begin cadena:=qedilocalizacionesumedida.asstring; end; cadena:=copy(cadena,0,largototal); linea:= linea + cadena + StringOfChar(' ', largototal - length(cadena)); end; if tipo='N' then begin largo:=0; if campo='CANTIDAD' then begin largo:=qedilocalizacionescantidad.Asfloat; end; if campo='CANTKGM' then begin largo:=qedilocalizacionescantkgm.Asfloat; end; if largo>0 then begin case decimales of 0:cadena:=formatfloat('#####',largo); 1:cadena:=formatfloat('#####.0',largo); 2:cadena:=formatfloat('#####.00',largo); 3:cadena:=formatfloat('#####.000',largo); 4:cadena:=formatfloat('#####.0000',largo); 5:cadena:=formatfloat('#####.00000',largo); end; // cadena:=floattostrf(largo,ffGeneral,largototal,decimales); linea:=linea+ StringOfChar('0', largototal - length(cadena))+cadena; end else begin cadena:=''; cadena:=copy(cadena,0,largototal); linea:= linea + cadena + StringOfChar(' ', largototal - length(cadena)); end; end; qedi_lugaresentrega.next; end; writeln(localizaciones, linea ); qedilocalizaciones.Next end; end finally closefile(cabecera); closefile(embalajes); closefile(lineas); closefile(localizaciones); closefile(marcas); showmessage('Los datos han sido exportados correctamente'); end; end; procedure Talbaranes.btasiguienteClick(Sender: TObject); begin albaranes.Prior; end; procedure Talbaranes.btaanteriorClick(Sender: TObject); begin albaranes.next; end; procedure Talbaranes.DBGrid2ColExit(Sender: TObject); begin if albaranesdetalle.State in [dsedit,dsinsert] then begin if dbgrid2.SelectedIndex=0 then begin filtro:=albaranesdetalleidarticulo.asstring; qarticulos.Close; qarticulos.Open; if qarticulos.RecordCount>0 then begin qtipos_iva.Open; albaranesdetalledescripcion.value:=qarticulosdescripcion.AsString; if qclientesexento_iva.AsInteger<>0 then albaranesdetalletipoiva.value:=qtipos_ivatipo.Asfloat else albaranesdetalletipoiva.value:=0; end; end; end; end; procedure Talbaranes.DBGrid2DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if albaranesdetalleidfactura.AsString<>'' then begin dbgrid2.Canvas.brush.Color := verde; end; dbgrid2.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure Talbaranes.DBGrid2KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (key=115) then begin buscararticulos := Tbuscararticulos.Create(nil); try fbuscararticulos.padre:=albaranes.Name; fbuscararticulos.filtro:=albaranesdetalleidarticulo.AsString; buscararticulos.Edit1.Text:=albaranesdetalleidarticulo.AsString; buscararticulos.showmodal(); finally if albaranesdetalle.State in [dsbrowse] then albaranesdetalle.Edit; albaranesdetalleidarticulo.Value:=buscararticulos.qarticuloscodigo.AsString; albaranesdetalledescripcion.value:=buscararticulos.qarticulosdescripcion.AsString; albaranesdetalletipoiva.value:=buscararticulos.qtipos_ivatipo.Asfloat; buscararticulos.Free; end; end; end; procedure Talbaranes.DBGrid3DblClick(Sender: TObject); begin pagecontrol1.TabIndex:=0; end; procedure Talbaranes.DBGrid3DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if albaranesfacturado.asinteger=0 then begin dbgrid3.Canvas.brush.Color := rojo; end; if albaranesfacturado.asinteger=1 then begin dbgrid3.Canvas.brush.Color := verde; end; dbgrid3.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure Talbaranes.DBGrid3TitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=albaranes.SortType; albaranes.SortedFields:=Column.FieldName+',fecha'; If st = stAscending then albaranes.SortType:=stDescending else albaranes.SortType:=stAscending; dsalbaranes.DataSet.First; end; procedure Talbaranes.comboserie2CloseUp(Sender: TObject); begin albaranes.Close; albaranes.SQL.Clear; albaranes.SQL.Add('select * from albaranes where serie='+''''+qseries2id.AsString+''''+' order by serie desc,id desc'); albaranes.Open; // albaranes.Locate('serie;id',vararrayof([serie,id]),[locaseinsensitive]); end; procedure Talbaranes.comboserieCloseUp(Sender: TObject); begin if albaranes.State in [dsedit,dsinsert] then begin albaranesid.Value:=qseriesnum_albaran.AsInteger; dbedit2.SetFocus; end; end; procedure Talbaranes.comboclientesCloseUp(Sender: TObject); begin albaranesnomcliente.value:=qclientesnombre.Asstring; albaranesnif.value:=qclientesnif.Asstring; albaranesdireccion.value:=qclientesdireccion.Asstring; albaranesprovincia.value:=qclientesprovincia.Asstring; albaranespoblacion.value:=qclientespoblacion.Asstring; albaranescodpost.value:=qclientescodpost.Asstring; albaranespaiscliente.value:=qclientespais.Asstring; albaranesidformapago.Value:=qclientesidformapago.asinteger; albaranescomision.Value:=qclientescomision.AsFloat; end; procedure Talbaranes.combodestinosCloseUp(Sender: TObject); begin albaranesnomdestino.value:=qdestinosdescripcion.Asstring; albaranesdirecciondestino.value:=qdestinosdireccion.Asstring; albaranesprovinciadestino.value:=qdestinosprovincia.Asstring; albaranescodpostdestino.value:=qdestinoscodpost.Asstring; albaranespoblaciondestino.Value:=qdestinospoblacion.AsString; albaranespaisdestino.value:=qdestinospais.Asstring; end; procedure Talbaranes.dsalbaranesDataChange(Sender: TObject; Field: TField); begin if (albaranes.State in [dsbrowse]) and (albaranes.recordcount>0) then begin qpedidos2.Close; qpedidos2.SQL.Clear; qpedidos2.SQL.Add('select p.id,p.ide,p.idcliente,p.iddestino,p.fecha_pedido,p.fecha_entrega,c.nombre_corto as cliente,d.descripcion as destino,p.pedidocliente from pedidos p,clientes c,clientes_destinos d where'); qpedidos2.SQL.Add(' p.ide=c.idempresa and p.idcliente=c.id and p.ide=d.idempresa and p.idcliente=d.idcliente and p.iddestino=d.codigo and'); qpedidos2.SQL.Add(' p.id in (select pd.idpedido from pedidosdetalle pd where pd.idalbaran='+''''+albaranesserie.asstring+'/'+albaranesid.AsString+''''+')'); qpedidos2.Open; qpedidosdetalle2.close; qpedidosdetalle2.SQL.Clear; qpedidosdetalle2.SQL.Add('select * from pedidosdetalle where idalbaran='+''''+albaranesserie.asstring+'/'+albaranesid.AsString+''''); qpedidosdetalle2.Open; qclientes.Close; qclientes.SQL.Clear; qclientes.SQL.Add('select * from clientes where idempresa='+albaranesidempresa.asstring+' and id='+albaranesidcliente.asstring); qclientes.open; qdestinos.Close; qdestinos.SQL.Clear; qdestinos.SQL.Add('select * from clientes_destinos where idempresa='+albaranesidempresa.asstring+' and idcliente='+albaranesidcliente.asstring+' and codigo='+''''+albaranesiddestino.asstring+''''); qdestinos.open; albaranesdetalle.Close; albaranesdetalle.prepare; albaranesdetalle.ParamByName('empresa').AsInteger:=albaranesidempresa.AsInteger; albaranesdetalle.ParamByName('serie').AsString:=albaranesserie.AsString; albaranesdetalle.ParamByName('albaran').AsInteger:=albaranesid.AsInteger; albaranesdetalle.open; albaranesdetallegrupo.Close; albaranesdetallegrupo.prepare; albaranesdetallegrupo.ParamByName('empresa').AsInteger:=albaranesidempresa.AsInteger; albaranesdetallegrupo.ParamByName('serie').AsString:=albaranesserie.AsString; albaranesdetallegrupo.ParamByName('albaran').AsInteger:=albaranesid.AsInteger; albaranesdetallegrupo.open; qalbaraneslotes.Close; qalbaraneslotes.Prepare; qalbaraneslotes.ParamByName('EMPRESA').AsInteger:=albaranesidempresa.AsInteger; qalbaraneslotes.ParamByName('SERIE').AsString:=albaranesserie.Asstring; qalbaraneslotes.ParamByName('ALBARAN').AsInteger:=albaranesid.AsInteger; qalbaraneslotes.Open; qalbaranespalets.Close; qalbaranespalets.Prepare; qalbaranespalets.ParamByName('EMPRESA').AsInteger:=albaranesidempresa.AsInteger; qalbaranespalets.ParamByName('SERIE').AsString:=albaranesserie.Asstring; qalbaranespalets.ParamByName('ALBARAN').AsInteger:=albaranesid.AsInteger; qalbaranespalets.Open; if albaranesfacturado.AsInteger=1 then begin btafacturar.enabled:=false; end else begin btafacturar.enabled:=true; dbgrid2.Enabled:=true; end; if albaranesccid.AsString='' then begin dbtext1.Visible:=false; dbtext2.Visible:=false; dbtext16.Visible:=false; dbtext17.Visible:=false; dbtext18.Visible:=false; end else begin dbtext1.Visible:=true; dbtext2.Visible:=true; dbtext16.Visible:=true; dbtext17.Visible:=true; dbtext18.Visible:=true; end; end; end; procedure Talbaranes.dsalbaranesStateChange(Sender: TObject); begin if albaranes.State in [dsedit,dsinsert] then begin btanuevo.Enabled:=false; btamodificar.Enabled:=false; btaborrar.Enabled:=false; btacancelar.Enabled:=true; btaguardar.Enabled:=true; btaanterior.Enabled:=false; btasiguiente.Enabled:=false; btaimportar.Enabled:=false; btaimprimir.Enabled:=false; btafacturar.Enabled:=false; qdestinos.Close; qclientes.Close; qdestinos.LinkedFields:='Idempresa;idcliente'; qdestinos.MasterFields:='Idempresa;id'; qdestinos.Mastersource:=dsqclientes; qclientes.open; qdestinos.Open; end else begin btanuevo.Enabled:=true; btamodificar.Enabled:=true; btaborrar.Enabled:=true; btacancelar.Enabled:=false; btaguardar.Enabled:=false; btaanterior.Enabled:=true; btasiguiente.Enabled:=true; btaimportar.Enabled:=true; btaimprimir.Enabled:=true; btafacturar.Enabled:=true; qclientes.Close; qdestinos.Close; qdestinos.LinkedFields:=''; qdestinos.MasterFields:=''; qdestinos.Mastersource:=nil; qclientes.open; qdestinos.Open; end; end; procedure Talbaranes.dsqseries2DataChange(Sender: TObject; Field: TField); begin albaranes.Close; albaranes.SQL.Clear; albaranes.SQL.Add('select * from albaranes where serie='+''''+qseries2id.AsString+''''+' order by serie desc,id desc'); albaranes.Open; end; procedure Talbaranes.fechaalbaranCloseUp(Sender: TObject); begin // albaranesfecha.Value:=fechaalbaran.Date; end; procedure Talbaranes.fechaalbaranEnter(Sender: TObject); begin // if albaranes.State in [dsinsert] then albaranesfecha.Value:=fechaalbaran.Date; // if albaranes.State in [dsedit] then fechaalbaran.Date:=albaranesfecha.Value; end; procedure Talbaranes.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Talbaranes.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is tdbgrid) then begin key:=','; end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Talbaranes.FormShow(Sender: TObject); begin dm.tempresa.Open; qseries.Close; qseries2.Close; qdestinos.Close; qclientes.Close; qpedidos.Close; qpedidos2.close; qpedidosdetalle.Close; qpedidosdetalle2.Close; albaranes.Close; albaranesdetalle.Close; qalbaranesiva.Close; qformaspago.Close; qarticulos.Close; qtipos_iva.Close; qcuentas.Close; qformularios.Close; qseries.open; qseries2.Open; qdestinos.open; qclientes.open; qpedidos.open; qpedidos2.open; qpedidosdetalle.open; qpedidosdetalle2.open; albaranes.Close; albaranes.SQL.Clear; albaranes.SQL.Add('select * from albaranes where serie='+''''+qseries2id.AsString+''''+' order by serie desc,id desc'); albaranes.Open; albaranesdetalle.open; qalbaranesiva.open; qformaspago.open; qarticulos.open; qtipos_iva.open; qcuentas.open; qformularios.Open; pagecontrol1.TabIndex:=1; comboserie2.KeyValue:=qseries2id.Asstring; comboformulario.KeyValue:=null; end; procedure Talbaranes.qalbaraneslotesAfterInsert(DataSet: TDataSet); begin qalbaranesloteside.Value:=albaranesidempresa.AsInteger; qalbaraneslotesids.Value:=albaranesserie.AsString; qalbaraneslotesida.Value:=albaranesid.AsInteger; end; procedure Talbaranes.qalbaranespaletsAfterInsert(DataSet: TDataSet); begin qalbaranespaletside.Value:=albaranesidempresa.AsInteger; qalbaranespaletsids.Value:=albaranesserie.AsString; qalbaranespaletsida.Value:=albaranesid.AsInteger; end; procedure Talbaranes.qarticulosBeforeOpen(DataSet: TDataSet); var filtrolocal:string; begin filtrolocal:=''; filtrolocal:=' and (descripcion like('+''''+'%'+filtro+'%'+''''+') or codigo like('+''''+'%'+filtro+'%'+''''+'))'; qarticulos.SQL.Clear; qarticulos.SQL.Add('select * from articulosf where activo=1 and facturable=1'+filtrolocal+' order by descripcion'); end; end. ======================================== FICHERO: falbaranes_PORTATIL_ago.-08-175659-2020_Conflict.pas ======================================== unit falbaranes; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, Vcl.DBCtrls,datos, Vcl.Mask, Vcl.Grids, Vcl.DBGrids, Vcl.ComCtrls, frxClass, frxDBSet, ComObj, Excel2000, frxExportPDF; type Talbaranes = class(TForm) Panel1: TPanel; Panel4: TPanel; btAcancelar: TButton; btAmodificar: TButton; btAborrar: TButton; btAnuevo: TButton; btAguardar: TButton; Panel2: TPanel; dsalbaranes: TDataSource; dsalbaranesdetalle: TDataSource; albaranes: TZQuery; albaranesdetalle: TZQuery; Panel3: TPanel; comboserie: TDBLookupComboBox; qseries: TZQuery; dsqseries: TDataSource; qserieside: TIntegerField; qseriesid: TWideStringField; qseriesfechainicio: TDateField; qseriesfechafin: TDateField; qseriesnum_pedcliente: TIntegerField; qseriesnum_albaran: TIntegerField; qseriesnum_factura: TIntegerField; qseriesnum_expedicion: TIntegerField; qseriesnum_pedproveedor: TIntegerField; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; DBEdit1: TDBEdit; comboclientes: TDBLookupComboBox; combodestinos: TDBLookupComboBox; Label5: TLabel; DBEdit2: TDBEdit; dsqclientes: TDataSource; qclientes: TZQuery; qclientesid: TIntegerField; qclientesIdempresa: TIntegerField; qclientesnif: TWideStringField; qclientesnombre: TWideStringField; qclientesnombre_corto: TWideStringField; qclientesdireccion: TWideStringField; qclientespoblacion: TWideStringField; qclientescodpost: TWideStringField; qclientesprovincia: TWideStringField; qclientestelefono: TWideStringField; qclientestelefono2: TWideStringField; qclientesmovil: TWideStringField; qclientesemail: TWideStringField; qclientespersonacontacto: TWideStringField; qclientescodigomercado: TIntegerField; qclientesactivo: TIntegerField; qclientesobservaciones: TWideStringField; qclientesccontable: TIntegerField; qclientesdescuento: TFloatField; dsqdestinos: TDataSource; qdestinos: TZQuery; qdestinoscodigo: TWideStringField; qdestinosidcliente: TIntegerField; qdestinosidempresa: TIntegerField; qdestinosdescripcion: TWideStringField; qdestinosseleccionado: TIntegerField; qdestinosactivo: TIntegerField; qdestinosdireccion: TWideStringField; qdestinospoblacion: TWideStringField; qdestinoscodpost: TWideStringField; qdestinosprovincia: TWideStringField; Label6: TLabel; Label7: TLabel; DBText3: TDBText; DBText4: TDBText; DBText5: TDBText; DBText6: TDBText; DBText7: TDBText; DBText8: TDBText; DBText9: TDBText; DBText10: TDBText; qclientespais: TWideStringField; qdestinospais: TWideStringField; DBText11: TDBText; DBText12: TDBText; DBText13: TDBText; DBText14: TDBText; DBText15: TDBText; dsqpedidos: TDataSource; qpedidos: TZQuery; dsqpedidosdetalle: TDataSource; qpedidosdetalle: TZQuery; qpedidosdetalleid: TIntegerField; qpedidosdetalleide: TIntegerField; qpedidosdetalleidpedido: TIntegerField; qpedidosdetalleidcliente: TIntegerField; qpedidosdetalleidproductocli: TWideStringField; qpedidosdetalleidenvase: TWideStringField; qpedidosdetalledesc_envase: TWideStringField; qpedidosdetalledesc_producto: TWideStringField; qpedidosdetallecantidad: TFloatField; qpedidosdetallecantidadservida: TFloatField; qpedidosdetallepalets: TIntegerField; qpedidosdetalleref: TWideStringField; qpedidosdetalleean: TWideStringField; qpedidosdetallemarca: TWideStringField; qpedidosdetalleobservaciones: TWideStringField; qpedidosdetalleidcajapropia: TWideStringField; qpedidosid: TIntegerField; qpedidoside: TIntegerField; qpedidosidcliente: TIntegerField; qpedidosiddestino: TWideStringField; qpedidosfecha_pedido: TDateField; qpedidosfecha_entrega: TDateField; qpedidoscliente: TWideStringField; qpedidosdestino: TWideStringField; dsqalbaranesiva: TDataSource; qalbaranesiva: TZQuery; albaranesid: TIntegerField; albaranesidempresa: TIntegerField; albaranesidcliente: TIntegerField; albaranesiddestino: TWideStringField; albaranesnif: TWideStringField; albaranesdireccion: TWideStringField; albaranespoblacion: TWideStringField; albaranesprovincia: TWideStringField; albaranescodpost: TWideStringField; albaranesfecha: TDateField; albaranesreferencia: TWideStringField; albaranestelefono: TWideStringField; albaranesnomcliente: TWideStringField; albaranespaiscliente: TWideStringField; albaranesnomdestino: TWideStringField; albaranesdirecciondestino: TWideStringField; albaranespoblaciondestino: TWideStringField; albaranescodpostdestino: TWideStringField; albaranesprovinciadestino: TWideStringField; albaranespaisdestino: TWideStringField; albaranesneto: TFloatField; albaranestotal: TFloatField; albaranesfacturado: TIntegerField; albaranesdocumento: TWideStringField; dsqpedidos2: TDataSource; dsqpedidosdetalle2: TDataSource; qpedidosdetalle2: TZQuery; qpedidos2: TZQuery; IntegerField8: TIntegerField; IntegerField9: TIntegerField; IntegerField10: TIntegerField; WideStringField11: TWideStringField; DateField1: TDateField; DateField2: TDateField; WideStringField12: TWideStringField; WideStringField13: TWideStringField; Panel5: TPanel; qalbaranesivaidalbaran: TIntegerField; qalbaranesivaide: TIntegerField; qalbaranesivabase: TFloatField; qalbaranesivatipo: TFloatField; qalbaranesivaiva: TFloatField; Panel6: TPanel; DBGrid1: TDBGrid; albaranesdescuento_lin: TFloatField; albaranesdescuento_com: TFloatField; albaranesdescuento_pp: TFloatField; albaranesdescuento_total: TFloatField; albaranestotaliva: TFloatField; Label8: TLabel; DBEdit3: TDBEdit; Label9: TLabel; DBEdit4: TDBEdit; Label10: TLabel; DBEdit5: TDBEdit; Label11: TLabel; DBEdit6: TDBEdit; Label12: TLabel; DBEdit7: TDBEdit; Label13: TLabel; DBEdit8: TDBEdit; Label14: TLabel; DBEdit9: TDBEdit; btaimprimir: TButton; btaimportar: TButton; btafacturar: TButton; DBGrid2: TDBGrid; Panel7: TPanel; Button4: TButton; qpedidosdetalle2id: TIntegerField; qpedidosdetalle2ide: TIntegerField; qpedidosdetalle2idpedido: TIntegerField; qpedidosdetalle2idcliente: TIntegerField; qpedidosdetalle2idproductocli: TWideStringField; qpedidosdetalle2idenvase: TWideStringField; qpedidosdetalle2desc_envase: TWideStringField; qpedidosdetalle2desc_producto: TWideStringField; qpedidosdetalle2cantidad: TFloatField; qpedidosdetalle2cantidadservida: TFloatField; qpedidosdetalle2palets: TIntegerField; qpedidosdetalle2ref: TWideStringField; qpedidosdetalle2ean: TWideStringField; qpedidosdetalle2marca: TWideStringField; qpedidosdetalle2observaciones: TWideStringField; qpedidosdetalle2idcajapropia: TWideStringField; DBCheckBox1: TDBCheckBox; DBMemo1: TDBMemo; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; DBGrid3: TDBGrid; btasiguiente: TButton; btaanterior: TButton; infalbaran: TfrxDBDataset; infdetallealbaran: TfrxDBDataset; infalbaranivas: TfrxDBDataset; informe: TfrxReport; albaranesobservaciones: TWideStringField; Label15: TLabel; DBMemo2: TDBMemo; qaux: TZQuery; albaranesidfactura: TIntegerField; qalbaranesivaserie: TWideStringField; qseriesimp_albaran: TWideStringField; qseriesimp_factura: TWideStringField; albaranesserie: TWideStringField; qpedidosdetalleidalbaran: TWideStringField; qpedidosdetalleidexpedicion: TWideStringField; qpedidosdetalle2idalbaran: TWideStringField; qpedidosdetalle2idexpedicion: TWideStringField; albaranesbultos: TFloatField; albaraneskilos: TFloatField; albaranesidformapago: TIntegerField; Label16: TLabel; comboformapago: TDBLookupComboBox; dsqformaspago: TDataSource; qformaspago: TZQuery; qformaspagoide: TIntegerField; qformaspagoid: TIntegerField; qformaspagocodigo: TWideStringField; qformaspagodescripcion: TWideStringField; qformaspagodias: TIntegerField; qclientesidformapago: TIntegerField; listaimpresion: TComboBox; albaranesdetalleidempresa: TIntegerField; albaranesdetalleidalbaran: TIntegerField; albaranesdetallecantidad: TFloatField; albaranesdetalleprecio: TFloatField; albaranesdetalledescuento: TFloatField; albaranesdetallebase: TFloatField; albaranesdetalledescripcion: TWideStringField; albaranesdetallecal: TWideStringField; albaranesdetallebultos: TFloatField; albaranesdetalletipoiva: TFloatField; albaranesdetalleiva: TFloatField; albaranesdetalletotal: TFloatField; albaranesdetalleid: TIntegerField; albaranesdetalletotaldescuento: TFloatField; albaranesdetalleserie: TWideStringField; albaranesdetalleidarticulo: TWideStringField; albaranesdetallelote: TWideStringField; qarticulos: TZReadOnlyQuery; dsqarticulos: TDataSource; qarticulosidempresa: TIntegerField; qarticulosid: TIntegerField; qarticuloscodigo: TWideStringField; qarticulosdescripcion: TWideStringField; qarticulosfamilia: TIntegerField; qarticulosprovhab: TIntegerField; qarticulostipoiva: TIntegerField; qarticulospreciocoste: TFloatField; qarticulosmargen: TFloatField; qarticulosbeneficio: TFloatField; qarticulospvp: TFloatField; qarticulosstock: TFloatField; qarticulosult_preciocompra: TFloatField; qarticulosfacturable: TIntegerField; qarticulosobservaciones: TWideStringField; qarticulosimagen: TBlobField; qarticulosactivo: TIntegerField; qarticulosvalor_almacen: TFloatField; qarticulosstock_minimo: TFloatField; qarticulosavisar_stock: TIntegerField; qarticuloscontrolar_traza: TIntegerField; qarticulospeso: TFloatField; qtipos_iva: TZReadOnlyQuery; DataSource1: TDataSource; qtipos_ivaid: TIntegerField; qtipos_ivadescripcion: TWideStringField; qtipos_ivatipo: TIntegerField; qtipos_ivatipo_req: TFloatField; albaranescoste_transporte: TFloatField; costetrans: TDBEdit; Label17: TLabel; qalbaranesclientes: TZReadOnlyQuery; dsqalbaranesclientes: TDataSource; albaranesdetallecoste_transporte: TFloatField; albaranesdetallecoste_otros: TFloatField; Panel11: TPanel; Button3: TButton; gridalbaranesaexcel: TDBGrid; qalbaranesclientesserie: TWideStringField; qalbaranesclientesid: TIntegerField; qalbaranesclientesidempresa: TIntegerField; qalbaranesclientesidcliente: TIntegerField; qalbaranesclientesiddestino: TWideStringField; qalbaranesclientesnif: TWideStringField; qalbaranesclientesdireccion: TWideStringField; qalbaranesclientespoblacion: TWideStringField; qalbaranesclientesprovincia: TWideStringField; qalbaranesclientescodpost: TWideStringField; qalbaranesclientesfecha: TDateField; qalbaranesclientesreferencia: TWideStringField; qalbaranesclientestelefono: TWideStringField; qalbaranesclientesnomcliente: TWideStringField; qalbaranesclientespaiscliente: TWideStringField; qalbaranesclientesnomdestino: TWideStringField; qalbaranesclientesdirecciondestino: TWideStringField; qalbaranesclientespoblaciondestino: TWideStringField; qalbaranesclientescodpostdestino: TWideStringField; qalbaranesclientesprovinciadestino: TWideStringField; qalbaranesclientespaisdestino: TWideStringField; qalbaranesclientesneto: TFloatField; qalbaranesclientestotal: TFloatField; qalbaranesclientesfacturado: TIntegerField; qalbaranesclientesdocumento: TWideStringField; qalbaranesclientesdescuento_lin: TFloatField; qalbaranesclientesdescuento_com: TFloatField; qalbaranesclientesdescuento_pp: TFloatField; qalbaranesclientesdescuento_total: TFloatField; qalbaranesclientestotaliva: TFloatField; qalbaranesclientesobservaciones: TWideStringField; qalbaranesclientesidfactura: TIntegerField; qalbaranesclientesbultos: TFloatField; qalbaranesclienteskilos: TFloatField; qalbaranesclientesidformapago: TIntegerField; qalbaranesclientescoste_transporte: TFloatField; qalbaranesclientesid_1: TIntegerField; qalbaranesclientesidempresa_1: TIntegerField; qalbaranesclientesserie_1: TWideStringField; qalbaranesclientesidalbaran: TIntegerField; qalbaranesclientesidarticulo: TWideStringField; qalbaranesclientesdescripcion: TWideStringField; qalbaranesclientescal: TWideStringField; qalbaranesclienteslote: TWideStringField; qalbaranesclientesbultos_1: TFloatField; qalbaranesclientescantidad: TFloatField; qalbaranesclientesprecio: TFloatField; qalbaranesclientesdescuento: TFloatField; qalbaranesclientestotaldescuento: TFloatField; qalbaranesclientesbase: TFloatField; qalbaranesclientestipoiva: TFloatField; qalbaranesclientesiva: TFloatField; qalbaranesclientestotal_1: TFloatField; qalbaranesclientescoste_transporte_1: TFloatField; qalbaranesclientescoste_otros: TFloatField; SaveDialog1: TSaveDialog; qalbaranesclientesparcela: TWideStringField; qclientesexento_iva: TIntegerField; procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure fechaalbaranEnter(Sender: TObject); procedure btAnuevoClick(Sender: TObject); procedure comboserieCloseUp(Sender: TObject); procedure FormShow(Sender: TObject); procedure dsalbaranesStateChange(Sender: TObject); procedure comboclientesCloseUp(Sender: TObject); procedure combodestinosCloseUp(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure albaranesdetalleBeforePost(DataSet: TDataSet); procedure Button4Click(Sender: TObject); procedure albaranesdetalleAfterPost(DataSet: TDataSet); procedure btaimportarClick(Sender: TObject); procedure btaanteriorClick(Sender: TObject); procedure btasiguienteClick(Sender: TObject); procedure btaimprimirClick(Sender: TObject); procedure btAmodificarClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure dsalbaranesDataChange(Sender: TObject; Field: TField); procedure fechaalbaranCloseUp(Sender: TObject); procedure comboclientesEnter(Sender: TObject); procedure combodestinosEnter(Sender: TObject); procedure comboserieEnter(Sender: TObject); procedure albaranesBeforePost(DataSet: TDataSet); procedure DBGrid3TitleClick(Column: TColumn); procedure DBGrid2KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure TabSheet2Enter(Sender: TObject); procedure DBGrid2ColExit(Sender: TObject); procedure qarticulosBeforeOpen(DataSet: TDataSet); procedure Button3Click(Sender: TObject); procedure DBGrid3DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure albaranesdetalleAfterDelete(DataSet: TDataSet); procedure albaranesdetalleBeforeDelete(DataSet: TDataSet); private { Private declarations } public { Public declarations } procedure ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar = nil); end; var albaranes: Talbaranes; filtro,iddetalle:string; vidempresa,vidarticulo:string; implementation {$R *.dfm} uses fselectpedidos,fbuscararticulos; procedure Talbaranes.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 Talbaranes.albaranesBeforePost(DataSet: TDataSet); begin if albaranes.state in [dsinsert,dsedit] then begin qclientes.Close; qdestinos.Close; qdestinos.LinkedFields:='Idempresa;idcliente'; qdestinos.MasterFields:='Idempresa;id'; qdestinos.Mastersource:=dsqclientes; qclientes.open; qdestinos.Open; end; end; procedure Talbaranes.albaranesdetalleAfterDelete(DataSet: TDataSet); begin qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('select * from entradas_detalle where stock>0 and idempresa='+vidempresa+' and idearticulo='+vidarticulo+' order by id'); end; procedure Talbaranes.albaranesdetalleAfterPost(DataSet: TDataSet); var serie,id:string; begin serie:=albaranesserie.AsString; id:=albaranesid.AsString; albaranes.Refresh; albaranes.Locate('serie;id',vararrayof([serie,id]),[locaseinsensitive]); qalbaranesiva.Refresh; if iddetalle<>'' then albaranesdetalle.Locate('id',iddetalle,[locaseinsensitive]) else albaranesdetalle.Last; end; procedure Talbaranes.albaranesdetalleBeforeDelete(DataSet: TDataSet); begin vidempresa:=albaranesdetalleidempresa.AsString; vidarticulo:=albaranesdetalleidarticulo.asstring; end; procedure Talbaranes.albaranesdetalleBeforePost(DataSet: TDataSet); var iva,descuento:real; begin if albaranesdetalletipoiva.AsString='' then albaranesdetalletipoiva.Value:=0; if albaranesdetalledescuento.AsString='' then albaranesdetalledescuento.Value:=0; if (albaranesdetallelote.AsString<>'') and (albaranesdetallecoste_otros.asstring='') then begin qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('select coste_kg_ref from parcelas where (codpar,empresa) in (select parcela,idempresa from lotes where codigo='+albaranesdetallelote.AsString+')'); qaux.Open; albaranesdetallecoste_otros.Value:=qaux.Fields[0].AsFloat; end; albaranesdetalleserie.Value:=albaranesserie.Asstring; albaranesdetallebase.Value:=albaranesdetalleprecio.AsFloat*albaranesdetallecantidad.AsFloat; descuento:=albaranesdetallebase.AsFloat*(albaranesdetalledescuento.AsFloat/100); albaranesdetalletotaldescuento.value:=descuento; albaranesdetalletotal.Value:=albaranesdetallebase.Asfloat-descuento; iva:=albaranesdetalletotal.AsFloat*(albaranesdetalletipoiva.AsFloat/100); albaranesdetalleiva.Value:=iva; if albaranesdetalle.State in [dsedit] then iddetalle:=albaranesdetalleid.AsString else iddetalle:=''; end; procedure Talbaranes.btAborrarClick(Sender: TObject); begin if albaranes.recordcount>0 then begin if albaranesfacturado.AsInteger=0 then BEGIN albaranes.Delete; albaranesdetalle.Refresh; qpedidos.Refresh; qpedidos2.Refresh; qpedidosdetalle.Refresh; qpedidosdetalle2.Refresh; qalbaranesiva.refresh; END else showmessage('¡¡¡ ALBARAN FACTURADO NO SE PUEDE BORRAR ¡¡¡'); end; end; procedure Talbaranes.btAcancelarClick(Sender: TObject); begin albaranes.Cancel; panel3.Enabled:=false; end; procedure Talbaranes.btAguardarClick(Sender: TObject); var empresa,serie:string; insertando:integer; cantidad,coste_trans:real; begin empresa:=albaranesidempresa.AsString; serie:=''''+albaranesserie.AsString+''''; if albaranes.State in [dsinsert] then insertando:=1 else insertando:=0; albaranes.Post; if insertando=1 then begin qseries.edit; qseriesnum_albaran.Value:=qseriesnum_albaran.AsInteger+1; qseries.Post; end; if insertando=0 then begin qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('select sum(cantidad) from albaranes_detalles where lote is not null and idempresa='+empresa+' and serie='+serie+' and idalbaran='+albaranesid.asstring); qaux.Open; cantidad:=qaux.Fields[0].AsFloat; if (cantidad>0) and (albaranescoste_transporte.AsFloat>0) then begin coste_trans:=albaranescoste_transporte.AsFloat/cantidad; qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('update albaranes_detalles set coste_transporte='+stringreplace(floattostr(coste_trans),',','.',[rfreplaceall])+' where lote is not null and idempresa='+empresa+' and serie='+serie+' and idalbaran='+albaranesid.asstring); qaux.execsql; end; end; albaranesdetalle.open; qalbaranesiva.open; albaranes.Refresh; albaranesdetalle.Refresh; qalbaranesiva.Refresh; panel3.Enabled:=false; end; procedure Talbaranes.btAmodificarClick(Sender: TObject); begin if albaranesfacturado.AsInteger=0 then BEGIN panel3.Enabled:=true; albaranes.Edit; qclientes.Close; qclientes.SQL.Clear; qclientes.SQL.Add('select * from clientes order by nombre'); qclientes.open; qdestinos.Close; qdestinos.SQL.Clear; qdestinos.SQL.Add('select * from clientes_destinos order by descripcion'); qdestinos.open; comboserie.Enabled:=true; comboclientes.Enabled:=true; combodestinos.Enabled:=true; comboformapago.Enabled:=true; dbedit1.Enabled:=true; dbmemo2.Enabled:=true; dbedit2.Enabled:=true; dbgrid2.Enabled:=true; END else begin panel3.enabled:=true; comboserie.Enabled:=false; comboclientes.Enabled:=false; combodestinos.Enabled:=false; comboformapago.Enabled:=false; dbedit1.Enabled:=false; dbmemo2.Enabled:=false; dbedit2.Enabled:=false; //dbgrid2.Enabled:=false; costetrans.enabled:=true; costetrans.SetFocus; end end; procedure Talbaranes.btAnuevoClick(Sender: TObject); begin panel3.Enabled:=true; comboserie.SetFocus; comboserie.KeyValue:=qseriesid.Asstring; //fechaalbaran.Date:=date; albaranes.Append; qclientes.Close; qclientes.SQL.Clear; qclientes.SQL.Add('select * from clientes order by nombre'); qclientes.open; qdestinos.Close; qdestinos.SQL.Clear; qdestinos.SQL.Add('select * from clientes_destinos order by descripcion'); qdestinos.open; albaranesdetalle.Close; qalbaranesiva.close; albaranesfecha.Value:=date; end; procedure Talbaranes.btaimprimirClick(Sender: TObject); var filtro,documento,formapago:string; fecha:tdate; begin if listaimpresion.ItemIndex=0 then begin albaranesdetalle.Close; albaranesdetalle.SQL.Clear; albaranesdetalle.SQL.Add('select idempresa,idalbaran,sum(cantidad) as cantidad,precio,descuento,sum(base) as base,descripcion,cal,sum(bultos) as bultos,tipoiva,sum(iva) as iva,sum(total) as total,id,'+''''''+' as idarticulo,sum(totaldescuento) as totaldescuento,'+''''''+' as lote,serie,coste_transporte,coste_otros '); albaranesdetalle.SQL.Add(' from albaranes_detalles group by idempresa,idalbaran,descripcion,cal,precio'); albaranesdetalle.open; end; if listaimpresion.ItemIndex=1 then begin albaranesdetalle.Close; albaranesdetalle.SQL.Clear; albaranesdetalle.SQL.Add('select * from albaranes_detalles'); albaranesdetalle.open; end; filtro:='id='; filtro:=filtro+albaranesid.asstring; filtro:=filtro+' and serie='+''''+albaranesserie.AsString+''''; documento:=qseriesimp_albaran.AsString; albaranes.Filter:=filtro; albaranes.filtered:=true; fecha:=albaranesfecha.AsDateTime; fecha:=fecha+qformaspagodias.asinteger; formapago:='FORMA DE PAGO: '+qformaspagodescripcion.AsString+' FECHA DE VENCIMIENTO EL '+DATETOSTR(FECHA); infalbaran.Datasource:=dsalbaranes; infdetallealbaran.Datasource:=dsalbaranesdetalle; infalbaranivas.Datasource:=dsqalbaranesiva; informe.Report.Clear; informe.LoadFromFile('c:\agrigest\informes\'+documento+'.fr3'); informe.Variables.Variables['FORMAPAGO']:=QUOTEDSTR(formapago); informe.ShowReport(); informe.Clear; // informe.Variables.Variables['TITULO']:=QUOTEDSTR(panel100.Caption); albaranes.filtered:=false; albaranesdetalle.Close; albaranesdetalle.SQL.Clear; albaranesdetalle.SQL.Add('select * from albaranes_detalles'); albaranesdetalle.open; end; procedure Talbaranes.btaimportarClick(Sender: TObject); begin seleccionarpedidos := Tseleccionarpedidos.Create(nil); try seleccionarpedidos.showmodal(); finally seleccionarpedidos.Free; end; end; procedure Talbaranes.Button3Click(Sender: TObject); var archivo:string; begin qalbaranesclientes.Close; qalbaranesclientes.SQL.Clear; qalbaranesclientes.SQL.Add('(select a.*,ad.*,l.parcela from albaranes a,albaranes_detalles ad,lotes l where l.idempresa=ad.idempresa and l.codigo=ad.lote and a.idempresa=ad.idempresa and a.serie=ad.serie and a.id=ad.idalbaran) '); qalbaranesclientes.SQL.Add(' union '); qalbaranesclientes.SQL.Add('(select a.*,ad.*,'+''''+' '+''''+' as parcela from albaranes a,albaranes_detalles ad where ad.lote is null and a.idempresa=ad.idempresa and a.serie=ad.serie and a.id=ad.idalbaran) order by fecha desc'); qalbaranesclientes.open; savedialog1.FileName:='ALBARANES CLIENTES.xls'; savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'ALBARANES',gridalbaranesaexcel); finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure Talbaranes.Button4Click(Sender: TObject); var serie,id:string; begin if albaranesdetalle.recordcount>0 then begin serie:=albaranesserie.AsString; id:=albaranesid.AsString; albaranesdetalle.Delete; // albaranes.Refresh; // albaranes.Locate('serie;id',vararrayof([serie,id]),[locaseinsensitive,lopartialkey]); qalbaranesiva.Refresh; end; end; procedure Talbaranes.btasiguienteClick(Sender: TObject); begin albaranes.prior; end; procedure Talbaranes.btaanteriorClick(Sender: TObject); begin albaranes.next; end; procedure Talbaranes.comboserieCloseUp(Sender: TObject); begin albaranesid.value:=qseriesnum_albaran.AsInteger; end; procedure Talbaranes.comboserieEnter(Sender: TObject); begin comboserie.DropDown; end; procedure Talbaranes.DBGrid2ColExit(Sender: TObject); begin if albaranesdetalle.State in [dsedit,dsinsert] then begin if dbgrid2.SelectedIndex=0 then begin filtro:=albaranesdetalleidarticulo.asstring; qarticulos.Close; qarticulos.Open; if qarticulos.RecordCount>0 then begin qtipos_iva.Open; albaranesdetalledescripcion.value:=qarticulosdescripcion.AsString; if qclientesexento_iva.AsInteger=0 then albaranesdetalletipoiva.value:=qtipos_ivatipo.Asfloat else albaranesdetalletipoiva.value:=0; end; end; end; end; procedure Talbaranes.DBGrid2KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (key=115) then begin buscararticulos := Tbuscararticulos.Create(nil); try fbuscararticulos.padre:=albaranes.Name; fbuscararticulos.filtro:=albaranesdetalleidarticulo.AsString; buscararticulos.Edit1.Text:=albaranesdetalleidarticulo.AsString; buscararticulos.showmodal(); finally if albaranesdetalle.State in [dsbrowse] then albaranesdetalle.Edit; albaranesdetalleidarticulo.Value:=buscararticulos.qarticuloscodigo.AsString; albaranesdetalledescripcion.value:=buscararticulos.qarticulosdescripcion.AsString; albaranesdetalletipoiva.value:=buscararticulos.qtipos_ivatipo.Asfloat; buscararticulos.Free; end; end; end; procedure Talbaranes.DBGrid3DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if albaranesfacturado.asinteger=0 then begin dbgrid3.Canvas.brush.Color := rojo; end; if albaranesfacturado.asinteger=1 then begin dbgrid3.Canvas.brush.Color := verde; end; dbgrid3.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure Talbaranes.DBGrid3TitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=albaranes.SortType; albaranes.SortedFields:=Column.FieldName; If st = stAscending then albaranes.SortType:=stDescending else albaranes.SortType:=stAscending; dsalbaranes.DataSet.First; end; procedure Talbaranes.comboclientesCloseUp(Sender: TObject); begin albaranesnomcliente.value:=qclientesnombre.Asstring; albaranesnif.value:=qclientesnif.Asstring; albaranesdireccion.value:=qclientesdireccion.Asstring; albaranesprovincia.value:=qclientesprovincia.Asstring; albaranespoblacion.value:=qclientesprovincia.Asstring; albaranescodpost.value:=qclientescodpost.Asstring; albaranespaiscliente.value:=qclientespais.Asstring; albaranesidformapago.Value:=qclientesidformapago.asinteger; end; procedure Talbaranes.comboclientesEnter(Sender: TObject); begin combodestinos.dropdown; end; procedure Talbaranes.combodestinosCloseUp(Sender: TObject); begin albaranesnomdestino.value:=qdestinosdescripcion.Asstring; albaranesdirecciondestino.value:=qdestinosdireccion.Asstring; albaranesprovinciadestino.value:=qdestinosprovincia.Asstring; albaranescodpostdestino.value:=qdestinoscodpost.Asstring; albaranespoblaciondestino.Value:=qdestinospoblacion.AsString; albaranespaisdestino.value:=qdestinospais.Asstring; end; procedure Talbaranes.combodestinosEnter(Sender: TObject); begin comboformapago.dropdown; end; procedure Talbaranes.dsalbaranesDataChange(Sender: TObject; Field: TField); begin if (albaranes.State in [dsbrowse]) and (albaranes.recordcount>0) then begin qpedidos2.Close; qpedidos2.SQL.Clear; qpedidos2.SQL.Add('select p.id,p.ide,p.idcliente,p.iddestino,p.fecha_pedido,p.fecha_entrega,c.nombre_corto as cliente,d.descripcion as destino from pedidos p,clientes c,clientes_destinos d where'); qpedidos2.SQL.Add(' p.ide=c.idempresa and p.idcliente=c.id and p.ide=d.idempresa and p.idcliente=d.idcliente and p.iddestino=d.codigo and'); qpedidos2.SQL.Add(' p.id in (select pd.idpedido from pedidosdetalle pd where pd.idalbaran='+''''+albaranesserie.asstring+'/'+albaranesid.AsString+''''+')'); qpedidos2.Open; qpedidosdetalle2.close; qpedidosdetalle2.SQL.Clear; qpedidosdetalle2.SQL.Add('select * from pedidosdetalle where idalbaran='+''''+albaranesserie.asstring+'/'+albaranesid.AsString+''''); qpedidosdetalle2.Open; qclientes.Close; qclientes.SQL.Clear; qclientes.SQL.Add('select * from clientes where idempresa='+albaranesidempresa.asstring+' and id='+albaranesidcliente.asstring); qclientes.open; qdestinos.Close; qdestinos.SQL.Clear; qdestinos.SQL.Add('select * from clientes_destinos where idempresa='+albaranesidempresa.asstring+' and idcliente='+albaranesidcliente.asstring+' and codigo='+''''+albaranesiddestino.asstring+''''); qdestinos.open; if albaranesfacturado.AsInteger=1 then begin //dbgrid2.Enabled:=false; end else dbgrid2.Enabled:=true; end; end; procedure Talbaranes.dsalbaranesStateChange(Sender: TObject); begin if albaranes.State in [dsedit,dsinsert] then begin btanuevo.Enabled:=false; btamodificar.Enabled:=false; btaborrar.Enabled:=false; btacancelar.Enabled:=true; btaguardar.Enabled:=true; qdestinos.Close; qclientes.Close; qdestinos.LinkedFields:='Idempresa;idcliente'; qdestinos.MasterFields:='Idempresa;id'; qdestinos.Mastersource:=dsqclientes; qclientes.open; qdestinos.Open; end else begin btanuevo.Enabled:=true; btamodificar.Enabled:=true; btaborrar.Enabled:=true; btacancelar.Enabled:=false; btaguardar.Enabled:=false; qclientes.Close; qdestinos.Close; qdestinos.LinkedFields:=''; qdestinos.MasterFields:=''; qdestinos.Mastersource:=nil; qclientes.open; qdestinos.Open; end; end; procedure Talbaranes.fechaalbaranCloseUp(Sender: TObject); begin // albaranesfecha.Value:=fechaalbaran.Date; end; procedure Talbaranes.fechaalbaranEnter(Sender: TObject); begin // if albaranes.State in [dsinsert] then albaranesfecha.Value:=fechaalbaran.Date; // if albaranes.State in [dsedit] then fechaalbaran.Date:=albaranesfecha.Value; end; procedure Talbaranes.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Talbaranes.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is tdbgrid) then begin key:=','; end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Talbaranes.FormShow(Sender: TObject); begin dm.tempresa.Open; qseries.Close; qdestinos.Close; qclientes.Close; qpedidos.Close; qpedidos2.close; qpedidosdetalle.Close; qpedidosdetalle2.Close; albaranes.Close; albaranesdetalle.Close; qalbaranesiva.Close; qformaspago.Close; qarticulos.Close; qtipos_iva.Close; qseries.open; qdestinos.open; qclientes.open; qpedidos.open; qpedidos2.open; qpedidosdetalle.open; qpedidosdetalle2.open; albaranes.open; albaranesdetalle.open; qalbaranesiva.open; qformaspago.open; qarticulos.open; qtipos_iva.open; end; procedure Talbaranes.qarticulosBeforeOpen(DataSet: TDataSet); var filtrolocal:string; begin filtrolocal:=''; filtrolocal:=' and (descripcion like('+''''+'%'+filtro+'%'+''''+') or codigo like('+''''+'%'+filtro+'%'+''''+'))'; qarticulos.SQL.Clear; qarticulos.SQL.Add('select * from articulosf where activo=1 and facturable=1'+filtrolocal+' order by descripcion'); end; procedure Talbaranes.TabSheet2Enter(Sender: TObject); var serie,id:string ; begin serie:=albaranesserie.AsString; id:=albaranesid.AsString; albaranes.Close; albaranes.SQL.Clear; albaranes.SQL.Add('select * from albaranes order by serie desc,id desc'); albaranes.Open; albaranes.Locate('serie;id',vararrayof([serie,id]),[locaseinsensitive]); end; end. ======================================== FICHERO: farticulo.pas ======================================== unit farticulo; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs; type Tarticulo = class(TForm) private { Private declarations } public { Public declarations } end; var articulo: Tarticulo; implementation {$R *.dfm} end. ======================================== FICHERO: farticulos.pas ======================================== unit farticulos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,Vcl.StdCtrls, Vcl.DBCtrls, Vcl.Mask, Vcl.ComCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls,DATA.DB, ZAbstractRODataset, ZDataset, ZAbstractDataset,shellapi, ZAbstractTable, Vcl.ExtDlgs; type Tarticulos = class(TForm) Panel1: TPanel; Panel2: TPanel; Panel5: TPanel; Label1: TLabel; todosarticulos: TCheckBox; tbuscar: TEdit; DBGrid1: TDBGrid; particulos: TPanel; pdatosarticulos: TPanel; Panel14: TPanel; Label10: TLabel; Label11: TLabel; Label12: TLabel; Label13: TLabel; Label14: TLabel; Label2: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; DBCheckBox2: TDBCheckBox; DBEdit1: TDBEdit; DBEdit10: TDBEdit; DBEdit11: TDBEdit; DBEdit12: TDBEdit; DBEdit3: TDBEdit; DBEdit4: TDBEdit; DBEdit8: TDBEdit; DBEdit9: TDBEdit; DBEdit22: TDBEdit; Detallesarticulos: TPageControl; TAlbaranes: TTabSheet; Panel10: TPanel; Label32: TLabel; btALcancelar: TButton; btALmodificar: TButton; btALborrar: TButton; btALnuevo: TButton; btALguardar: TButton; DBGrid7: TDBGrid; TFacturas: TTabSheet; Panel11: TPanel; Label31: TLabel; btFcancelar: TButton; btFmodificar: TButton; btFborrar: TButton; btFnuevo: TButton; btFguardar: TButton; DBGrid8: TDBGrid; Panel4: TPanel; Label36: TLabel; btAcancelar: TButton; btAmodificar: TButton; btAborrar: TButton; btAnuevo: TButton; btAguardar: TButton; qfamilias: TZReadOnlyQuery; qfamiliasidempresa: TIntegerField; qfamiliasid: TIntegerField; qfamiliasdescripcion: TWideStringField; combofamilias: TDBLookupComboBox; dsqfamilias: TDataSource; qfamiliasactivo: TIntegerField; DBMemo1: TDBMemo; Label3: TLabel; DBCheckBox1: TDBCheckBox; qproveedores: TZReadOnlyQuery; dsqproveedores: TDataSource; qtipoivas: TZReadOnlyQuery; dsqtiposiva: TDataSource; qproveedoresid: TIntegerField; qproveedoresIdempresa: TIntegerField; qproveedoresnif: TWideStringField; qproveedoresnombre: TWideStringField; qproveedoresnombre_corto: TWideStringField; qtipoivasid: TIntegerField; qtipoivasdescripcion: TWideStringField; qtipoivastipo: TIntegerField; DBLookupComboBox2: TDBLookupComboBox; DBLookupComboBox3: TDBLookupComboBox; qaux: TZReadOnlyQuery; TabSheet4: TTabSheet; DBCheckBox3: TDBCheckBox; DBEdit2: TDBEdit; Label15: TLabel; Label16: TLabel; DBEdit5: TDBEdit; Label17: TLabel; qlistadoproveedores: TZReadOnlyQuery; qlistadoproveedoresidproveedor: TIntegerField; qlistadoproveedoresnombre: TWideStringField; qlistadoproveedoresid: TWideStringField; qlistadoproveedoresid_propio: TWideStringField; qlistadoproveedoresult_precio: TFloatField; qlistadoproveedoresidempresa: TIntegerField; DBGrid2: TDBGrid; dsqlistproveedores: TDataSource; DBCheckBox4: TDBCheckBox; qcompras: TZReadOnlyQuery; qcomprasnombre: TWideStringField; qcomprasdocumento: TWideStringField; qcomprasfecha: TDateField; qcomprascodigo: TWideStringField; qcomprasdescripcion: TWideStringField; qcomprasid_propio: TWideStringField; qcomprascantidad: TFloatField; qcomprasprecio: TFloatField; qcomprasidempresa: TIntegerField; qcomprasdesc_propia: TWideStringField; DBGrid3: TDBGrid; dsqcompras: TDataSource; Panel3: TPanel; Button3: TButton; Button4: TButton; qcomprasstock: TFloatField; qarticulosfinal: TZReadOnlyQuery; qarticulosfinalidempresa: TIntegerField; qarticulosfinalid: TIntegerField; qarticulosfinalcodigo: TWideStringField; qarticulosfinaldescripcion: TWideStringField; qarticulosfinalactivo: TIntegerField; qarticulosfinalpreciocoste: TFloatField; dsqarticulosfinal: TDataSource; dtarticulosfinal: TZQuery; dtarticulosfinalidempresa: TIntegerField; dtarticulosfinalid: TIntegerField; dtarticulosfinalcodigo: TWideStringField; dtarticulosfinaldescripcion: TWideStringField; dtarticulosfinalfamilia: TIntegerField; dtarticulosfinalprovhab: TIntegerField; dtarticulosfinaltipoiva: TIntegerField; dtarticulosfinalpreciocoste: TFloatField; dtarticulosfinalmargen: TFloatField; dtarticulosfinalbeneficio: TFloatField; dtarticulosfinalpvp: TFloatField; dtarticulosfinalstock: TFloatField; dtarticulosfinalult_preciocompra: TFloatField; dtarticulosfinalfacturable: TIntegerField; dtarticulosfinalobservaciones: TWideStringField; dtarticulosfinalimagen: TBlobField; dtarticulosfinalactvo: TIntegerField; dtarticulosfinalvalor_almacen: TFloatField; dtarticulosfinalstock_minimo: TFloatField; dtarticulosfinalavisar_stock: TIntegerField; dtarticulosfinalcontrolar_traza: TIntegerField; dsarticulosfinal: TDataSource; DBEdit6: TDBEdit; Label18: TLabel; dtarticulosfinalpeso: TFloatField; ZQuery1: TZQuery; ZQuery1id: TIntegerField; ZQuery1idempresa: TIntegerField; ZQuery1identrada: TIntegerField; ZQuery1idproveedor: TIntegerField; ZQuery1codigo: TWideStringField; ZQuery1id_propio: TWideStringField; ZQuery1descripcion: TWideStringField; ZQuery1lote: TWideStringField; ZQuery1cantidad: TFloatField; ZQuery1stock: TFloatField; ZQuery1precio: TFloatField; ZQuery1tipo_iva: TIntegerField; ZQuery1base: TFloatField; ZQuery1total: TFloatField; Label19: TLabel; DBEdit7: TDBEdit; dtarticulosfinaldescripcion_doc: TWideStringField; qcompraslote: TWideStringField; dtarticulosfinalinventariable: TIntegerField; dtarticulosfinalactualizar_stock: TIntegerField; DBCheckBox5: TDBCheckBox; dtarticulosfinalregistro: TWideStringField; PageControl1: TPageControl; TabSheet6: TTabSheet; TabSheet7: TTabSheet; dtarticulosfinalmateria_activa: TWideStringField; dtarticulosfinalplazo_seguridad: TIntegerField; dtarticulosfinaldosis: TWideStringField; temp_fotos: TZTable; temp_fotoside: TIntegerField; temp_fotosidt: TIntegerField; temp_fotosimagen: TBlobField; temp_fotosextension: TWideStringField; dsempfotos: TDataSource; Panel34: TPanel; Panel35: TPanel; Panel36: TPanel; Label43: TLabel; Button5: TButton; Button15: TButton; Panel37: TPanel; DBGrid4: TDBGrid; Memo2: TMemo; Button21: TButton; Button20: TButton; dsdocumentos: TDataSource; documentos: TZQuery; documentos_tmp: TZTable; OpenPictureDialog1: TOpenPictureDialog; OpenDialog2: TOpenDialog; 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; documentos_tmpidaf: TIntegerField; documentosid: TIntegerField; documentoside: TIntegerField; documentosfecha: TDateField; documentosdescripcion: TWideStringField; documentosnomarchivo: TWideStringField; documentosextension: TWideStringField; documentosidaf: TIntegerField; Panel6: TPanel; Label20: TLabel; Label21: TLabel; Label22: TLabel; Label23: TLabel; Label24: TLabel; DBEdit13: TDBEdit; DBEdit14: TDBEdit; DBEdit15: TDBEdit; DBEdit16: TDBEdit; DBEdit17: TDBEdit; qtemp_doc: TZQuery; qtemp_docid: TIntegerField; qtemp_docide: TIntegerField; qtemp_docarchivo: TBlobField; qtemp_docextension: TWideStringField; qtemp_docnomarchivo: TWideStringField; SaveDialog1: TSaveDialog; dtarticulosfinalnum_aplicaciones: TIntegerField; dtarticulosfinalfrecuencia: TWideStringField; Label25: TLabel; DBEdit18: TDBEdit; qmateriaactiva: TZReadOnlyQuery; qmateriaactivamateria_activa: TWideStringField; combofamilia: TDBLookupComboBox; Label26: TLabel; qfamilias2: TZReadOnlyQuery; dsqfamilias2: TDataSource; qfamilias2idempresa: TIntegerField; qfamilias2id: TIntegerField; qfamilias2descripcion: TWideStringField; qfamilias2activo: TIntegerField; qfamilias2grupo: TIntegerField; qfamilias2COMUN: TIntegerField; qfamilias2ABONOS: TIntegerField; qfamilias2FITOSANITARIOS: TIntegerField; qfamilias2SUMINISTROS: TIntegerField; qfamilias2GENERADORES: TIntegerField; dtarticulosfinalvol_hect: TFloatField; dtarticulosfinalpermitir_mezcla: TIntegerField; dtarticulosfinalunidad_medida: TWideStringField; Label27: TLabel; DBEdit19: TDBEdit; Label28: TLabel; DBEdit20: TDBEdit; Label29: TLabel; DBCheckBox6: TDBCheckBox; qactualizar_stocks: TZQuery; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); procedure tbuscarChange(Sender: TObject); procedure todosarticulosClick(Sender: TObject); procedure btAnuevoClick(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure btAmodificarClick(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); procedure DBEdit12Change(Sender: TObject); procedure DBEdit8Change(Sender: TObject); procedure DBEdit22Change(Sender: TObject); procedure DBEdit10Change(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure dsqarticulosfinalStateChange(Sender: TObject); procedure qarticulosfinalAfterClose(DataSet: TDataSet); procedure qarticulosfinalAfterOpen(DataSet: TDataSet); procedure qarticulosfinalAfterRefresh(DataSet: TDataSet); procedure qarticulosfinalBeforeOpen(DataSet: TDataSet); procedure dsarticulosfinalStateChange(Sender: TObject); procedure dsarticulosfinalDataChange(Sender: TObject; Field: TField); procedure Image2DblClick(Sender: TObject); procedure Button15Click(Sender: TObject); procedure Button19Click(Sender: TObject); procedure Button21Click(Sender: TObject); procedure Button20Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure DBEdit13Exit(Sender: TObject); procedure combofamiliaClick(Sender: TObject); procedure dsqfamilias2DataChange(Sender: TObject; Field: TField); private { Private declarations } public { Public declarations } var filtro:string; vertodos:integer; end; var articulos: Tarticulos; implementation {$R *.dfm} uses datos; procedure Tarticulos.btAcancelarClick(Sender: TObject); begin dtarticulosfinal.cancel; dtarticulosfinal.MasterSource:=dsqarticulosfinal; end; procedure Tarticulos.btAmodificarClick(Sender: TObject); begin dtarticulosfinal.MasterSource:=nil; dtarticulosfinal.edit; // dbedit1.SetFocus; end; procedure Tarticulos.btAborrarClick(Sender: TObject); begin dtarticulosfinal.delete; qarticulosfinal.Refresh; dtarticulosfinal.Refresh; end; procedure Tarticulos.btAnuevoClick(Sender: TObject); begin qaux.SQL.Clear; qaux.SQL.Add('select max(id)+1 from articulosf'); qaux.Open; dtarticulosfinal.MasterSource:=nil; dtarticulosfinal.append; pagecontrol1.TabIndex:= 0; dbedit1.SetFocus; dbedit1.Text:=qaux.Fields[0].AsString; combofamilias.KeyValue:=dm.tempresaidfamilia.asinteger; end; procedure Tarticulos.Button15Click(Sender: TObject); var ext,nomarchivo:string; 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; documentos_tmp.Open; documentos_tmp.Append; ext:= ExtractFileExt(opendialog2.FileName); nomarchivo:= extractfilename(opendialog2.FileName); documentos_tmpidaf.Value:=dtarticulosfinalid.Asinteger; documentos_tmpfecha.Value:=date(); documentos_tmpide.Value:=dtarticulosfinalidempresa.asinteger; documentos_tmpnomarchivo.Value:=nomarchivo; documentos_tmpdescripcion.Value:=nomarchivo; documentos_tmpextension.Value:=ext; documentos_tmparchivo.LoadFromFile(opendialog2.FileName); documentos_tmp.Post; qaux.SQL.Clear; qaux.SQL.Add('insert into documentos (ide,fecha,descripcion,archivo,nomarchivo,extension,idlote,codpar,idea,idt,idaf) (select ide,fecha,descripcion,archivo,nomarchivo,extension,idlote,codpar,idea,idt,idaf from documentos_tmp)'); qaux.ExecSQL; qaux.SQL.Clear; qaux.SQL.Add('delete from documentos_tmp '); qaux.ExecSQL; documentos.Close; documentos.Prepare; documentos.ParamByName('ARTICULO').AsInteger:=dtarticulosfinalid.AsInteger; documentos.ParamByName('EMPRESA').AsInteger:=dtarticulosfinalidempresa.AsInteger; documentos.open; end else begin memo2.Clear; memo2.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(memo2.Lines[x]); nomarchivo:= extractfilename(memo2.Lines[x]); documentos_tmpidaf.Value:=dtarticulosfinalid.Asinteger; documentos_tmpfecha.Value:=date(); documentos_tmpide.Value:=dtarticulosfinalidempresa.Asinteger; documentos_tmpnomarchivo.Value:=nomarchivo; documentos_tmpdescripcion.Value:=nomarchivo; documentos_tmpextension.Value:=ext; documentos_tmparchivo.LoadFromFile(memo2.Lines[x]); documentos_tmp.Post; qaux.SQL.Clear; qaux.SQL.Add('insert into documentos (ide,fecha,descripcion,archivo,nomarchivo,extension,idlote,codpar,idea,idt,idaf) (select ide,fecha,descripcion,archivo,nomarchivo,extension,idlote,codpar,idea,idt,idaf from documentos_tmp)'); qaux.ExecSQL; qaux.SQL.Clear; qaux.SQL.Add('delete from documentos_tmp '); qaux.ExecSQL; documentos.Close; documentos.Prepare; documentos.ParamByName('ARTICULO').AsInteger:=dtarticulosfinalid.Asinteger; documentos.ParamByName('EMPRESA').AsInteger:=dtarticulosfinalidempresa.Asinteger; documentos.open; panel37.Visible:=true; end; end; end; end; end; procedure Tarticulos.Button19Click(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; end; end; end; procedure Tarticulos.Button20Click(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); end; procedure Tarticulos.Button21Click(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); end; procedure Tarticulos.Button5Click(Sender: TObject); begin documentos.Delete; end; procedure Tarticulos.combofamiliaClick(Sender: TObject); begin combofamilia.KeyValue:=null; end; procedure Tarticulos.DBEdit10Change(Sender: TObject); begin if dbedit10.Text<>'' then begin if (dtarticulosfinal.State in [dsedit,dsinsert]) and (dbedit10.Focused) then begin dtarticulosfinalpvp.Value:=(1+(dtarticulosfinalmargen.asfloat/100))*strtofloat(dbedit10.Text); dtarticulosfinalbeneficio.Value:=dtarticulosfinalpvp.AsFloat-strtofloat(dbedit10.Text); end; end; end; procedure Tarticulos.DBEdit12Change(Sender: TObject); begin if dbedit12.Text<>'' then begin if (dtarticulosfinal.State in [dsedit,dsinsert]) and (dbedit12.Focused) then begin dtarticulosfinalpvp.Value:=dtarticulosfinalpreciocoste.AsFloat*((strtofloat(dbedit12.Text)/100)+1); dtarticulosfinalbeneficio.Value:=dtarticulosfinalpvp.AsFloat-dtarticulosfinalpreciocoste.asfloat; end; end; end; procedure Tarticulos.DBEdit13Exit(Sender: TObject); begin if dtarticulosfinalregistro.AsString<>'' then begin qmateriaactiva.Close; qmateriaactiva.Prepare; qmateriaactiva.ParamByName('REGISTRO').AsString:=dtarticulosfinalregistro.asstring; qmateriaactiva.Open; if qmateriaactivamateria_activa.asstring<>'' then dtarticulosfinalmateria_activa.Value:=qmateriaactivamateria_activa.asstring; end; end; procedure Tarticulos.DBEdit22Change(Sender: TObject); begin if dbedit22.Text<>'' then begin if (dtarticulosfinal.State in [dsedit,dsinsert]) and (dbedit22.Focused) then begin dtarticulosfinalmargen.Value:=(((strtofloat(dbedit22.Text)*100)/dtarticulosfinalpreciocoste.AsFloat))-100; dtarticulosfinalbeneficio.Value:=strtofloat(dbedit22.Text)-dtarticulosfinalpreciocoste.asfloat; end; end; end; procedure Tarticulos.DBEdit8Change(Sender: TObject); begin if dbedit8.Text<>'' then begin if (dtarticulosfinal.State in [dsedit,dsinsert]) and (dbedit8.Focused) then begin dtarticulosfinalpvp.Value:=strtofloat(dbedit8.Text)+dtarticulosfinalpreciocoste.asfloat; dtarticulosfinalmargen.Value:=((dtarticulosfinalpvp.asfloat*100)/dtarticulosfinalpreciocoste.AsFloat)-100; end; end; end; procedure Tarticulos.dsarticulosfinalDataChange(Sender: TObject; Field: TField); begin qcompras.close; qcompras.ParamByName('EMPRESA').Asinteger:=dtarticulosfinalidempresa.AsInteger; qcompras.ParamByName('ARTICULO').Asstring:=dtarticulosfinalcodigo.Asstring; qcompras.Open; qlistadoproveedores.close; qlistadoproveedores.ParamByName('EMPRESA').Asinteger:=dtarticulosfinalidempresa.AsInteger; qlistadoproveedores.ParamByName('ARTICULO').Asstring:=dtarticulosfinalcodigo.Asstring; qlistadoproveedores.Open; documentos.Close; documentos.Prepare; documentos.ParamByName('ARTICULO').AsInteger:=dtarticulosfinalid.AsInteger; documentos.ParamByName('EMPRESA').AsInteger:=dtarticulosfinalidempresa.AsInteger; documentos.open; end; procedure Tarticulos.dsarticulosfinalStateChange(Sender: TObject); begin if dtarticulosfinal.State in [dsedit,dsinsert] then begin Panel14.Enabled:=true; btAnuevo.enabled:=false; btAborrar.enabled:=false; btAmodificar.enabled:=false; btAguardar.enabled:=true; btAcancelar.enabled:=true; end; if dtarticulosfinal.State in [dsbrowse] then begin Panel14.Enabled:=false; btAnuevo.enabled:=true; btAborrar.enabled:=true; btAmodificar.enabled:=true; btAguardar.enabled:=false; btAcancelar.enabled:=false; end; end; procedure Tarticulos.dsqarticulosfinalStateChange(Sender: TObject); begin if dtarticulosfinal.State in [dsedit,dsinsert] then begin Panel14.Enabled:=true; btAnuevo.enabled:=false; btAborrar.enabled:=false; btAmodificar.enabled:=false; btAguardar.enabled:=true; btAcancelar.enabled:=true; end; if dtarticulosfinal.State in [dsbrowse] then begin Panel14.Enabled:=false; btAnuevo.enabled:=true; btAborrar.enabled:=true; btAmodificar.enabled:=true; btAguardar.enabled:=false; btAcancelar.enabled:=false; end; end; procedure Tarticulos.dsqfamilias2DataChange(Sender: TObject; Field: TField); begin filtro:='%'+tbuscar.Text+'%'; if todosarticulos.Checked then vertodos:=1 else vertodos:=0; qarticulosfinal.Close; qarticulosfinal.open; end; procedure Tarticulos.btAguardarClick(Sender: TObject); begin dtarticulosfinal.Post; qarticulosfinal.Refresh; qarticulosfinal.Locate('id',dtarticulosfinalid.AsInteger,[locaseinsensitive,lopartialkey]); dtarticulosfinal.MasterSource:=dsqarticulosfinal; dtarticulosfinal.Refresh; end; procedure Tarticulos.FormClose(Sender: TObject; var Action: TCloseAction); begin qarticulosfinal.close; filtro:=''; vertodos:=0; end; procedure Tarticulos.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tarticulos.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is tdbgrid) then begin key:=','; end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tarticulos.FormShow(Sender: TObject); begin qactualizar_stocks.ExecSQL; qarticulosfinal.close; qarticulosfinal.Open; detallesarticulos.ActivePageIndex:=5; qlistadoproveedores.Prepare; qcompras.Prepare; qfamilias2.Open; end; procedure Tarticulos.Image2DblClick(Sender: TObject); var nomarchivo:string; begin nomarchivo:='empimg'+temp_fotosextension.AsString; ShellExecute(Handle,nil,PChar('c:\agrigest\tmp\'+nomarchivo),'','',SW_SHOWNORMAL); end; procedure Tarticulos.qarticulosfinalAfterClose(DataSet: TDataSet); begin dtarticulosfinal.close; qfamilias.close; qtipoivas.close; qproveedores.close; end; procedure Tarticulos.qarticulosfinalAfterOpen(DataSet: TDataSet); begin dtarticulosfinal.Open; qfamilias.Open; qtipoivas.Open; qproveedores.Open; end; procedure Tarticulos.qarticulosfinalAfterRefresh(DataSet: TDataSet); begin dtarticulosfinal.refresh; qfamilias.refresh; qtipoivas.refresh; qproveedores.refresh; end; procedure Tarticulos.qarticulosfinalBeforeOpen(DataSet: TDataSet); var vdescripcion,vcodigo,vid,vfamilia,vactivo:string; begin { if filtro<>'' then begin begin filtrolocal:=' where descripcion like('+''''+filtro+''''+') or codigo like('+''''+filtro+''''+') or id like('+''''+filtro+''''+')'; end; if vertodos=0 then begin begin filtrolocal:=' where (descripcion like('+''''+filtro+''''+') or codigo like('+''''+filtro+''''+') or id like('+''''+filtro+''''+')'; filtrolocal:=filtrolocal+') and activo=1 '; end; end; end; if filtro='' then begin filtrolocal:=''; if vertodos=0 then begin filtrolocal:=' where activo=1 '; end; end; } vdescripcion:=filtro; vcodigo:=filtro; vid:=filtro; if combofamilia.KeyValue=null then vfamilia:='%' else vfamilia:=combofamilia.KeyValue; if vertodos=0 then vactivo:='1' else vactivo:='%'; qarticulosfinal.Prepare; qarticulosfinal.ParamByName('DESCRIPCION').AsString:=vdescripcion; qarticulosfinal.ParamByName('CODIGO').AsString:=vcodigo; qarticulosfinal.ParamByName('ID').AsString:=vid; qarticulosfinal.ParamByName('FAMILIA').AsString:=vfamilia; qarticulosfinal.ParamByName('ACTIVO').AsString:=vactivo; // qarticulosfinal.SQL.Clear; // qarticulosfinal.SQL.Add('select idempresa,id,codigo,descripcion,activo,preciocoste from articulosf ' + filtrolocal +' order by descripcion') end; procedure Tarticulos.tbuscarChange(Sender: TObject); begin filtro:='%'+tbuscar.Text+'%'; if todosarticulos.Checked then vertodos:=1 else vertodos:=0; qarticulosfinal.Close; qarticulosfinal.open; end; procedure Tarticulos.todosarticulosClick(Sender: TObject); begin if todosarticulos.Checked=true then begin vertodos:=1; qarticulosfinal.Close; // qarticulosfinal.SQL.Clear; // qarticulosfinal.SQL.add('select * from articulosf order by descripcion asc'); qarticulosfinal.Open; end else begin vertodos:=0; qarticulosfinal.Close; // qarticulosfinal.SQL.Clear; // qarticulosfinal.SQL.add('select * from articulosf where activo=1 order by descripcion asc'); qarticulosfinal.Open; end; end; end. ======================================== FICHERO: fbalanceventas.pas ======================================== unit fbalanceventas; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.StdCtrls, ZAbstractRODataset, ZDataset, Vcl.ExtCtrls, Vcl.DBCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.Menus, ZAbstractDataset, Vcl.Tabs, Vcl.ComCtrls, Vcl.Mask, ZAbstractConnection, ZConnection, ZAbstractTable, Vcl.ExtDlgs, Vcl.Imaging.jpeg, frxClass, frxDBSet, frxExportPDF, frxBarcode, Vcl.Buttons, VCLTee.TeEngine, VCLTee.Series, VCLTee.TeeData, VCLTee.TeeProcs, VCLTee.Chart, VCLTee.DBChart,ShellApi, Vcl.OleCtrls,IdHTTP,mshtml, SHDocVw, wgssSTU_TLB,SignatureForm, Vcl.ToolWin, Vcl.ImgList,dateutils, Vcl.OleServer, ComObj, Excel2000, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdMessage, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdMessageClient, IdSMTPBase, IdSMTP; type Tbalanceventas = class(TForm) Panel1: TPanel; qcampanyas: TZReadOnlyQuery; qbalanceventas: TZReadOnlyQuery; dsqcampanayas: TDataSource; dsbalanceventas: TDataSource; listaagrupacion: TComboBox; listaordenacion: TComboBox; qcampanyasid: TIntegerField; qcampanyasidempresa: TIntegerField; qcampanyasid_anterior: TIntegerField; qcampanyasdescripcion: TWideStringField; qcampanyasfechainicio: TDateField; qcampanyasfechafin: TDateField; qcampanyasult_pesada: TIntegerField; listacampanyas: TDBLookupComboBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; grdatos: TDBGrid; Checkdetallado: TCheckBox; Panel2: TPanel; Button1: TButton; Button2: TButton; btfiltrar: TButton; SaveDialog1: TSaveDialog; qbalanceventasidcliente: TIntegerField; qbalanceventasnomcliente: TWideStringField; qbalanceventasserie: TWideStringField; qbalanceventasidfactura: TIntegerField; qbalanceventasfecha: TDateField; qbalanceventasidarticulo: TWideStringField; qbalanceventaslote: TWideStringField; qbalanceventascantidad: TFloatField; qbalanceventasprecio: TFloatField; qbalanceventasbase: TFloatField; qbalanceventastipoiva: TFloatField; qbalanceventasiva: TFloatField; qbalanceventasdescuento: TFloatField; qbalanceventastotaldescuento: TFloatField; qbalanceventastotal: TFloatField; qbalanceventasparcela: TWideStringField; qbalanceventasmprima: TWideStringField; informedb: TfrxDBDataset; informes: TfrxReport; qbalanceventasobtentor: TWideStringField; Label4: TLabel; listaseries: TDBLookupComboBox; qseries: TZReadOnlyQuery; dsqseries: TDataSource; qserieside: TIntegerField; qseriesid: TWideStringField; qseriesfechainicio: TDateField; qseriesfechafin: TDateField; qseriesnum_pedcliente: TIntegerField; qseriesnum_albaran: TIntegerField; qseriesnum_factura: TIntegerField; qseriesnum_expedicion: TIntegerField; qseriesnum_pedproveedor: TIntegerField; qseriesimp_albaran: TWideStringField; qseriesimp_factura: TWideStringField; qseriesactivo: TIntegerField; qseriesnum_presupuesto: TIntegerField; qseriesseriecontable: TWideStringField; procedure FormShow(Sender: TObject); procedure btfiltrarClick(Sender: TObject); procedure CheckdetalladoClick(Sender: TObject); procedure listaagrupacionChange(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure listaordenacionChange(Sender: TObject); private { Private declarations } public { Public declarations } procedure ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar = nil); end; var balanceventas: Tbalanceventas; implementation {$R *.dfm} procedure Tbalanceventas.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.columns[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 if DBGrid.columns[J].Visible then 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 Tbalanceventas.btfiltrarClick(Sender: TObject); var dia,mes,anyo:word; finicio,ffin,serie:string; grupo,orden:integer; begin decodedate(qcampanyasfechainicio.asdatetime,anyo,mes,dia); finicio:=''''+inttostr(anyo)+'/'+inttostr(mes)+'/'+inttostr(dia)+''''; decodedate(qcampanyasfechafin.asdatetime,anyo,mes,dia); ffin:=''''+inttostr(anyo)+'/'+inttostr(mes)+'/'+inttostr(dia)+''''; serie:=''''+qseriesid.AsString+''''; if checkdetallado.Checked then begin grupo:=-1; orden:=-1; qbalanceventas.Close; qbalanceventas.SQL.Clear; qbalanceventas.SQL.Add('select * from vista_balanceventas where serie='+serie+' and fecha>='+finicio+' and fecha<='+ffin); end else begin grupo:=listaagrupacion.ItemIndex; orden:=listaordenacion.ItemIndex; qbalanceventas.Close; qbalanceventas.SQL.Clear; qbalanceventas.SQL.Add('select idcliente,nomcliente,serie,idfactura,fecha,idarticulo,lote,sum(cantidad) as cantidad,precio,sum(base) as base,tipoiva,sum(iva) as iva,descuento,sum(totaldescuento) as totaldescuento,sum(total) as total,parcela,mprima,obtentor '); qbalanceventas.SQL.Add(' from vista_balanceventas where serie='+serie+' and fecha>='+finicio+' and fecha<='+ffin); end; case grupo of 0:begin qbalanceventas.SQL.Add(' group by mprima '); end; 1:begin qbalanceventas.SQL.Add(' group by parcela '); end; 2:begin qbalanceventas.SQL.Add(' group by idcliente'); end; 3:begin qbalanceventas.SQL.Add(' group by idfactura '); end; end; case orden of 0:begin qbalanceventas.SQL.Add(' order by mprima '); end; 1:begin qbalanceventas.SQL.Add(' order by parcela '); end; 2:begin qbalanceventas.SQL.Add(' order by idcliente '); end; 3:begin qbalanceventas.SQL.Add(' order by idfactura '); end; end; qbalanceventas.open; end; procedure Tbalanceventas.Button1Click(Sender: TObject); begin informedb.Datasource:=dsbalanceventas; { if edit2.text<>'' then begin dmestadisticas.qproduccionimpresion.close; dmestadisticas.qproduccionimpresion.sql.clear; dmestadisticas.qproduccionimpresion.sql.add('select * from ea_pesadas ea where codigoR='+''''+'R'+edit2.Text+''''+' order by ea.destino,ea.id_envase,ea.fecha,ea.id,ea.mprima'); dmestadisticas.qproduccion.Open; end; } case listaagrupacion.ItemIndex of 0:begin informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\balancemasasvariedad.fr3'); informes.Variables.Variables['TITULO']:=QUOTEDSTR('Balance de masas por variedad '+qcampanyasdescripcion.AsString); informes.Variables.Variables['AGRUPACION']:=QUOTEDSTR('Variedad'); end; 1:begin informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\balancemasasparcela.fr3'); informes.Variables.Variables['TITULO']:=QUOTEDSTR('Balance de masas por parcela '+qcampanyasdescripcion.AsString); informes.Variables.Variables['AGRUPACION']:=QUOTEDSTR('Parcela'); end; 2:begin informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\balancemasascliente.fr3'); informes.Variables.Variables['TITULO']:=QUOTEDSTR('Balance de masas por cliente '+qcampanyasdescripcion.AsString); informes.Variables.Variables['AGRUPACION']:=QUOTEDSTR('Cliente'); end; 3:begin informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\balancemasasdetallado.fr3'); informes.Variables.Variables['TITULO']:=QUOTEDSTR('Balance de masas detallado '+qcampanyasdescripcion.AsString); end; end; // informes.Report.FileName:=TMES.Text+' ' + qjornalestrabajador.asstring; informes.ShowReport(); informes.Clear end; procedure Tbalanceventas.Button2Click(Sender: TObject); var archivo:string; begin savedialog1.FileName:='BALANCE-DE-MASAS.xlsx'; savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'BALANCE-DE-MASAS',grdatos); finally showmessage('Los datos han sido exportados correctamente a '+archivo); end; end; procedure Tbalanceventas.CheckdetalladoClick(Sender: TObject); begin if checkdetallado.Checked then begin grdatos.columns[0].Visible:=true; grdatos.columns[1].Visible:=true; grdatos.columns[2].Visible:=true; grdatos.columns[3].Visible:=true; grdatos.columns[4].Visible:=true; grdatos.columns[5].Visible:=true; grdatos.columns[6].Visible:=true; grdatos.columns[7].Visible:=true; grdatos.columns[8].Visible:=true; grdatos.columns[9].Visible:=true; grdatos.columns[10].Visible:=true; grdatos.columns[11].Visible:=true; grdatos.columns[12].Visible:=true; grdatos.columns[13].Visible:=true; grdatos.columns[14].Visible:=true; grdatos.columns[15].Visible:=true; grdatos.columns[16].Visible:=true; end else case listaagrupacion.ItemIndex of 0:begin grdatos.columns[0].Visible:=true; grdatos.columns[1].Visible:=false; grdatos.columns[2].Visible:=false; grdatos.columns[3].Visible:=false; grdatos.columns[4].Visible:=false; grdatos.columns[5].Visible:=false; grdatos.columns[6].Visible:=true; grdatos.columns[7].Visible:=false; grdatos.columns[8].Visible:=false; grdatos.columns[9].Visible:=true; grdatos.columns[10].Visible:=false; grdatos.columns[11].Visible:=true; grdatos.columns[12].Visible:=false; grdatos.columns[13].Visible:=false; grdatos.columns[14].Visible:=false; grdatos.columns[15].Visible:=false; grdatos.columns[16].Visible:=true; end; 1:begin grdatos.columns[0].Visible:=true; grdatos.columns[1].Visible:=false; grdatos.columns[2].Visible:=false; grdatos.columns[3].Visible:=false; grdatos.columns[4].Visible:=false; grdatos.columns[5].Visible:=false; grdatos.columns[6].Visible:=false; grdatos.columns[7].Visible:=true; grdatos.columns[8].Visible:=false; grdatos.columns[9].Visible:=true; grdatos.columns[10].Visible:=false; grdatos.columns[11].Visible:=true; grdatos.columns[12].Visible:=false; grdatos.columns[13].Visible:=false; grdatos.columns[14].Visible:=false; grdatos.columns[15].Visible:=false; grdatos.columns[16].Visible:=true; end; 2:begin grdatos.columns[0].Visible:=false; grdatos.columns[1].Visible:=false; grdatos.columns[2].Visible:=false; grdatos.columns[3].Visible:=false; grdatos.columns[4].Visible:=false; grdatos.columns[5].Visible:=false; grdatos.columns[6].Visible:=false; grdatos.columns[7].Visible:=true; grdatos.columns[8].Visible:=false; grdatos.columns[9].Visible:=false; grdatos.columns[10].Visible:=true; grdatos.columns[11].Visible:=false; grdatos.columns[12].Visible:=true; grdatos.columns[13].Visible:=false; grdatos.columns[14].Visible:=false; grdatos.columns[15].Visible:=true; end; end; end; procedure Tbalanceventas.FormShow(Sender: TObject); begin qcampanyas.Open; qseries.Open; listaseries.KeyValue:=qseriesid.AsInteger; listacampanyas.KeyValue:=qcampanyasid.AsString; // qbalanceventas.Open; end; procedure Tbalanceventas.listaagrupacionChange(Sender: TObject); begin btfiltrar.Click; case listaagrupacion.ItemIndex of 0:begin grdatos.columns[0].Visible:=false; grdatos.columns[1].Visible:=false; grdatos.columns[2].Visible:=false; grdatos.columns[3].Visible:=false; grdatos.columns[4].Visible:=false; grdatos.columns[5].Visible:=false; grdatos.columns[6].Visible:=true; grdatos.columns[7].Visible:=true; grdatos.columns[8].Visible:=false; grdatos.columns[9].Visible:=false; grdatos.columns[10].Visible:=true; grdatos.columns[11].Visible:=false; grdatos.columns[12].Visible:=true; grdatos.columns[13].Visible:=false; grdatos.columns[14].Visible:=true; grdatos.columns[15].Visible:=false; grdatos.columns[16].Visible:=false; grdatos.columns[17].Visible:=true; end; 1:begin grdatos.columns[0].Visible:=false; grdatos.columns[1].Visible:=false; grdatos.columns[2].Visible:=false; grdatos.columns[3].Visible:=false; grdatos.columns[4].Visible:=false; grdatos.columns[5].Visible:=false; grdatos.columns[6].Visible:=false; grdatos.columns[7].Visible:=false; grdatos.columns[8].Visible:=true; grdatos.columns[9].Visible:=false; grdatos.columns[10].Visible:=true; grdatos.columns[11].Visible:=false; grdatos.columns[12].Visible:=true; grdatos.columns[13].Visible:=false; grdatos.columns[14].Visible:=true; grdatos.columns[15].Visible:=false; grdatos.columns[16].Visible:=false; grdatos.columns[17].Visible:=true; end; 2:begin grdatos.columns[0].Visible:=false; grdatos.columns[1].Visible:=false; grdatos.columns[2].Visible:=false; grdatos.columns[3].Visible:=false; grdatos.columns[4].Visible:=false; grdatos.columns[5].Visible:=false; grdatos.columns[6].Visible:=false; grdatos.columns[7].Visible:=false; grdatos.columns[8].Visible:=false; grdatos.columns[9].Visible:=true; grdatos.columns[10].Visible:=true; grdatos.columns[11].Visible:=false; grdatos.columns[12].Visible:=true; grdatos.columns[13].Visible:=false; grdatos.columns[14].Visible:=true; grdatos.columns[15].Visible:=false; grdatos.columns[16].Visible:=false; grdatos.columns[17].Visible:=true; end; end; end; procedure Tbalanceventas.listaordenacionChange(Sender: TObject); begin btfiltrar.Click; end; end. ======================================== FICHERO: fbasculas.pas ======================================== unit fbasculas; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZDataset, ZAbstractRODataset, ZAbstractDataset, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids; type Tbasculas = class(TForm) DBGrid1: TDBGrid; Panel1: TPanel; btnuevo: TButton; btmodificar: TButton; btborrar: TButton; btguardar: TButton; btcancelar: TButton; qbasculas: TZQuery; dsqbasculas: TDataSource; qid: TZReadOnlyQuery; qidid: TLargeintField; qbasculaside: TIntegerField; qbasculasid: TIntegerField; qbasculasdescripcion: TWideStringField; qbasculasmodelo: TWideStringField; qbasculasfecha_adquisicion: TDateField; qbasculaspeso_control: TFloatField; procedure dsqbasculasStateChange(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); procedure qbasculasAfterInsert(DataSet: TDataSet); procedure qbasculasAfterPost(DataSet: TDataSet); procedure qbasculasBeforeDelete(DataSet: TDataSet); procedure qbasculasBeforePost(DataSet: TDataSet); procedure btnuevoClick(Sender: TObject); procedure btmodificarClick(Sender: TObject); procedure btborrarClick(Sender: TObject); procedure btguardarClick(Sender: TObject); procedure btcancelarClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var basculas: Tbasculas; implementation {$R *.dfm} uses datos; procedure Tbasculas.btborrarClick(Sender: TObject); begin qbasculas.Delete; end; procedure Tbasculas.btcancelarClick(Sender: TObject); begin qbasculas.Cancel; end; procedure Tbasculas.btguardarClick(Sender: TObject); begin qbasculas.Post; end; procedure Tbasculas.btmodificarClick(Sender: TObject); begin qbasculas.Edit; end; procedure Tbasculas.btnuevoClick(Sender: TObject); begin qbasculas.append; end; procedure Tbasculas.dsqbasculasStateChange(Sender: TObject); begin if qbasculas.State in [dsedit,dsinsert] then begin btnuevo.Enabled:=false; btmodificar.Enabled:=false; btborrar.Enabled:=false; btcancelar.Enabled:=true; btguardar.Enabled:=true; end else begin btnuevo.Enabled:=true; btmodificar.Enabled:=true; btborrar.Enabled:=true; btcancelar.Enabled:=false; btguardar.Enabled:=false; end; end; procedure Tbasculas.FormKeyPress(Sender: TObject; var Key: Char); begin key:=upcase(key); if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tbasculas.FormShow(Sender: TObject); begin qbasculas.Open; dm.tempresa.Open; end; procedure Tbasculas.qbasculasAfterInsert(DataSet: TDataSet); begin qid.close; qid.ParamByName('EMPRESA').AsInteger:=dm.tempresaid.AsInteger; qid.open; if qidid.asstring='' then qbasculasid.value:=1 else qbasculasid.Value:=qidid.asinteger; end; procedure Tbasculas.qbasculasAfterPost(DataSet: TDataSet); begin qbasculas.Cancel; qbasculas.Refresh; end; procedure Tbasculas.qbasculasBeforeDelete(DataSet: TDataSet); begin case dm.PedirConfirmacion('¿Confirma que desea borrar esta bascula?',true,true,false) of mrno:Abort; end; end; procedure Tbasculas.qbasculasBeforePost(DataSet: TDataSet); var x:integer; begin if qbasculas.State in [dsinsert] then qbasculaside.Value:=dm.tempresaid.AsInteger; if qbasculas.state=dsinsert then x:=dm.PedirConfirmacion('¿Confirma que desea dar de alta esta bascula?',true,true,true) else x:=dm.PedirConfirmacion('¿Confirma que desea modificar esta bascula?',true,true,true); case x of mrno: begin qbasculas.cancel; abort; end; mrcancel:BEGIN abort; END; end; end; end. ======================================== FICHERO: fboquillas.pas ======================================== unit fboquillas; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, Vcl.Grids, Vcl.DBGrids; type Tboquillas = class(TForm) DBGrid1: TDBGrid; dsboquillas: TDataSource; boquillas: TZQuery; boquillasid: TIntegerField; boquillascodigo: TWideStringField; boquillasdescripcion: TWideStringField; boquillasFloatField5bar: TFloatField; boquillasFloatField6bar: TFloatField; boquillasFloatField7bar: TFloatField; boquillasFloatField8bar: TFloatField; boquillasFloatField9bar: TFloatField; boquillasFloatField10bar: TFloatField; boquillasFloatField11bar: TFloatField; boquillasFloatField12bar: TFloatField; boquillasFloatField13bar: TFloatField; boquillasFloatField14bar: TFloatField; boquillasFloatField15bar: TFloatField; boquillasFloatField16bar: TFloatField; boquillasFloatField17bar: TFloatField; boquillasFloatField18bar: TFloatField; boquillasFloatField19bar: TFloatField; boquillasFloatField20bar: TFloatField; boquillasFloatField21bar: TFloatField; boquillasFloatField22bar: TFloatField; boquillasFloatField23bar: TFloatField; boquillasFloatField24bar: TFloatField; boquillasFloatField25bar: TFloatField; procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var boquillas: Tboquillas; implementation {$R *.dfm} procedure Tboquillas.FormCreate(Sender: TObject); begin boquillas.Open; end; end. ======================================== FICHERO: fbuscararticulos.pas ======================================== unit fbuscararticulos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.StdCtrls, Data.DB, ZAbstractRODataset, ZDataset; type Tbuscararticulos = class(TForm) Panel1: TPanel; DBGrid1: TDBGrid; Label1: TLabel; Edit1: TEdit; qarticulos: TZReadOnlyQuery; dsqarticulos: TDataSource; btAguardar: TButton; DataSource1: TDataSource; qtipos_iva: TZReadOnlyQuery; qtipos_ivaid: TIntegerField; qtipos_ivadescripcion: TWideStringField; qtipos_ivatipo: TIntegerField; qtipos_ivatipo_req: TFloatField; qarticulosidempresa: TIntegerField; qarticulosid: TIntegerField; qarticuloscodigo: TWideStringField; qarticulosdescripcion: TWideStringField; qarticulosfamilia: TIntegerField; qarticulosprovhab: TIntegerField; qarticulostipoiva: TIntegerField; qarticulospreciocoste: TFloatField; qarticulosmargen: TFloatField; qarticulosbeneficio: TFloatField; qarticulospvp: TFloatField; qarticulosstock: TFloatField; qarticulosult_preciocompra: TFloatField; qarticulosfacturable: TIntegerField; qarticulosobservaciones: TWideStringField; qarticulosimagen: TBlobField; qarticulosactivo: TIntegerField; qarticulosvalor_almacen: TFloatField; qarticulosstock_minimo: TFloatField; qarticulosavisar_stock: TIntegerField; qarticuloscontrolar_traza: TIntegerField; qarticulospeso: TFloatField; qarticulosdescripcion_doc: TWideStringField; qarticulosinventariable: TIntegerField; qarticulosactualizar_stock: TIntegerField; qarticulosregistro: TWideStringField; qarticulosmateria_activa: TWideStringField; qarticulosplazo_seguridad: TIntegerField; qarticulosdosis: TWideStringField; procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); procedure Edit1Change(Sender: TObject); procedure qarticulosBeforeOpen(DataSet: TDataSet); procedure btAguardarClick(Sender: TObject); procedure Edit1Exit(Sender: TObject); procedure DBGrid1ColExit(Sender: TObject); private { Private declarations } public { Public declarations } end; var buscararticulos: Tbuscararticulos; padre,filtro:string; implementation {$R *.dfm} procedure Tbuscararticulos.btAguardarClick(Sender: TObject); begin buscararticulos.Close; end; procedure Tbuscararticulos.DBGrid1ColExit(Sender: TObject); begin if dbgrid1.SelectedIndex=1 then btaguardar.SetFocus; end; procedure Tbuscararticulos.Edit1Change(Sender: TObject); begin filtro:=edit1.Text; qarticulos.Close; qarticulos.Open; qtipos_iva.Open; end; procedure Tbuscararticulos.Edit1Exit(Sender: TObject); begin dbgrid1.SetFocus; end; procedure Tbuscararticulos.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin key:=upcase(key); GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin if (key='.') and (activecontrol is tdbgrid) then begin key:=','; end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tbuscararticulos.FormShow(Sender: TObject); begin qarticulos.Open; end; procedure Tbuscararticulos.qarticulosBeforeOpen(DataSet: TDataSet); var filtrolocal:string; begin filtrolocal:=''; filtrolocal:=' and (descripcion like('+''''+'%'+filtro+'%'+''''+') or codigo like('+''''+'%'+filtro+'%'+''''+'))'; qarticulos.SQL.Clear; qarticulos.SQL.Add('select * from articulosf where activo=1 '+filtrolocal+' order by descripcion'); end; end. ======================================== FICHERO: fbuscararticulosprov.pas ======================================== unit fbuscararticulosprov; 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.Grids, Vcl.DBGrids, Data.DB, ZAbstractRODataset, ZDataset; type Tbuscararticulosprov = class(TForm) DBGrid1: TDBGrid; Panel1: TPanel; Label1: TLabel; Edit1: TEdit; btAguardar: TButton; qarticulos: TZReadOnlyQuery; dsqarticulos: TDataSource; qarticulosidempresa: TIntegerField; qarticulosid: TWideStringField; qarticuloscodigo: TWideStringField; qarticulosdescripcion: TWideStringField; qarticulospvp: TFloatField; procedure Edit1Change(Sender: TObject); procedure qarticulosBeforeOpen(DataSet: TDataSet); procedure btAguardarClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var buscararticulosprov: Tbuscararticulosprov; filtro:string; implementation {$R *.dfm} uses fentradas; procedure Tbuscararticulosprov.btAguardarClick(Sender: TObject); begin buscararticulosprov.Close; end; procedure Tbuscararticulosprov.Edit1Change(Sender: TObject); begin filtro:=edit1.Text; qarticulos.Close; qarticulos.Open; end; procedure Tbuscararticulosprov.qarticulosBeforeOpen(DataSet: TDataSet); var filtrolocal:string; begin filtrolocal:=''; filtrolocal:=' and (descripcion like('+''''+'%'+filtro+'%'+''''+') or id like('+''''+'%'+filtro+'%'+''''+'))'; qarticulos.SQL.Clear; qarticulos.SQL.Add('select idempresa,id,id_propio as codigo,descripcion,ult_precio as pvp from proveedores_articulos where idempresa='+entradas.entradasidempresa.AsString+' and idproveedor='+entradas.entradasidproveedor.asstring+filtrolocal+' order by descripcion'); end; end. ======================================== FICHERO: fbuscarempleado.pas ======================================== unit fbuscarempleado; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZDataset, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids; type Tbuscarempleado = class(TForm) DBGrid1: TDBGrid; Panel1: TPanel; Label1: TLabel; Edit1: TEdit; btAguardar: TButton; qempleados: TZReadOnlyQuery; dsqempleados: TDataSource; qempleadosid: TSmallintField; qempleadosnombre: TWideStringField; procedure btAguardarClick(Sender: TObject); procedure Edit1Change(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } end; var buscarempleado: Tbuscarempleado; filtro:string; empresa:integer; implementation {$R *.dfm} uses datos; procedure Tbuscarempleado.btAguardarClick(Sender: TObject); begin buscarempleado.Close; end; procedure Tbuscarempleado.Edit1Change(Sender: TObject); begin if edit1.text='' then filtro:='%' else filtro:='%'+edit1.Text+'%'; qempleados.Close; qempleados.ParamByName('EMPRESA').AsInteger:=empresa; qempleados.ParamByName('FILTRO').AsString:=filtro; qempleados.open; end; procedure Tbuscarempleado.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbgrid) then begin key:=','; end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tbuscarempleado.FormShow(Sender: TObject); begin dm.tempresa.open; empresa:=dm.tempresaid.asinteger; qempleados.Close; qempleados.prepare; qempleados.ParamByName('EMPRESA').AsInteger:=empresa; qempleados.ParamByName('FILTRO').AsString:=filtro; qempleados.Open; end; end. ======================================== FICHERO: fcargastratamientos.pas ======================================== unit fcargastratamientos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZDataset, ZAbstractRODataset, ZAbstractDataset, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.DBCtrls; type Tcargastratamientos = class(TForm) Panel2: TPanel; btAnuevo: TButton; btAborrar: TButton; btAmodificar: TButton; btAguardar: TButton; btAcancelar: TButton; Button1: TButton; qcargas: TZQuery; qmeteorologia: TZReadOnlyQuery; dscargas: TDataSource; dsqmeteorologia: TDataSource; qcargasid: TIntegerField; qcargaside: TIntegerField; qcargasidt: TIntegerField; qcargasfecha: TDateField; qcargashora_inicio: TTimeField; qcargashora_fin: TTimeField; qcargasid_emp: TIntegerField; qcargasoperario: TWideStringField; qcargasid_tractor: TWideStringField; qcargastractor: TWideStringField; qcargasid_fumigadora: TWideStringField; qcargasfumigadora: TWideStringField; qcargascondiciones_meteorologicas: TWideStringField; qcargascantidad: TIntegerField; dsqoperarios: TDataSource; qoperarios: TZReadOnlyQuery; dsqfumigadoras: TDataSource; qfumigadoras: TZReadOnlyQuery; dsqtractores: TDataSource; qtractores: TZReadOnlyQuery; dsqproductos: TDataSource; qproductos: TZReadOnlyQuery; qtractoresidempresa: TIntegerField; qtractoresid: TWideStringField; qtractoresdescripcion: TWideStringField; qfumigadorasidempresa: TIntegerField; qfumigadorasid: TWideStringField; qfumigadorasdescripcion: TWideStringField; qoperarioside: TIntegerField; qoperariosid: TSmallintField; qoperariosnif: TWideStringField; qoperariosnombre: TWideStringField; qmeteorologiaid: TIntegerField; qmeteorologiaide: TIntegerField; qmeteorologiadescripcion: TWideStringField; Panel1: TPanel; combooperarios: TDBLookupComboBox; combodepositos: TDBLookupComboBox; combotractores: TDBLookupComboBox; DBGrid1: TDBGrid; Panel3: TPanel; DBGrid2: TDBGrid; qproductoside: TIntegerField; qproductosidt: TIntegerField; qproductosidaf: TIntegerField; qproductosdescripcion_af: TWideStringField; qproductoscant_producto: TFloatField; combometeorologia: TDBLookupComboBox; updatehorafin: TZReadOnlyQuery; updatefincargas: TZReadOnlyQuery; updatefincargastratamiento: TZReadOnlyQuery; procedure qmeteorologiaBeforeOpen(DataSet: TDataSet); procedure qoperariosBeforeOpen(DataSet: TDataSet); procedure qfumigadorasBeforeOpen(DataSet: TDataSet); procedure qtractoresBeforeOpen(DataSet: TDataSet); procedure qcargasBeforeOpen(DataSet: TDataSet); procedure dscargasDataChange(Sender: TObject; Field: TField); procedure qproductosBeforeOpen(DataSet: TDataSet); procedure dscargasStateChange(Sender: TObject); procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure FormShow(Sender: TObject); procedure qcargasBeforePost(DataSet: TDataSet); procedure qcargasAfterInsert(DataSet: TDataSet); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure qcargasAfterPost(DataSet: TDataSet); procedure btAnuevoClick(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure btAmodificarClick(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } var vempresa,vtratamiento:integer; end; var cargastratamientos: Tcargastratamientos; implementation {$R *.dfm} procedure Tcargastratamientos.btAborrarClick(Sender: TObject); begin qcargas.Delete; end; procedure Tcargastratamientos.btAcancelarClick(Sender: TObject); begin qcargas.Cancel; end; procedure Tcargastratamientos.btAguardarClick(Sender: TObject); begin qcargas.Post; end; procedure Tcargastratamientos.btAmodificarClick(Sender: TObject); begin qcargas.Edit; end; procedure Tcargastratamientos.btAnuevoClick(Sender: TObject); begin qcargas.Append; dbgrid1.SetFocus; end; procedure Tcargastratamientos.Button1Click(Sender: TObject); begin updatefincargas.Prepare; updatefincargas.ParamByName('TRATAMIENTO').AsInteger:=qcargasidt.AsInteger; updatefincargas.ParamByName('EMPRESA').AsInteger:=qcargaside.AsInteger; updatefincargas.ParamByName('HORA').AsTime:=now(); updatefincargas.ExecSQL; updatefincargastratamiento.Prepare; updatefincargastratamiento.ParamByName('TRATAMIENTO').AsInteger:=qcargasidt.AsInteger; updatefincargastratamiento.ParamByName('EMPRESA').AsInteger:=qcargaside.AsInteger; updatefincargastratamiento.ExecSQL; qcargas.Refresh; end; procedure Tcargastratamientos.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); const IsChecked : array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED); var DrawState,imgindex,bmpwidth: Integer; DrawRect: TRect; begin DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State); if (gdFocused in State) then begin if (Column.Field.FieldName = combotractores.DataField) then with combotractores do begin Left := Rect.Left + DBGrid1.Left + 2; Top := Rect.Top + DBGrid1.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else combotractores.Visible:=false; if (Column.Field.FieldName = combodepositos.DataField) then with combodepositos do begin Left := Rect.Left + DBGrid1.Left + 2; Top := Rect.Top + DBGrid1.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else combodepositos.Visible:=false; if (Column.Field.FieldName = combooperarios.DataField) then with combooperarios do begin Left := Rect.Left + DBGrid1.Left + 2; Top := Rect.Top + DBGrid1.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else combooperarios.Visible:=false; if (Column.Field.FieldName = combometeorologia.DataField) then with combometeorologia do begin Left := Rect.Left + DBGrid1.Left + 2; Top := Rect.Top + DBGrid1.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else combometeorologia.Visible:=false; end; end; procedure Tcargastratamientos.dscargasDataChange(Sender: TObject; Field: TField); begin if qcargas.State in [dsbrowse] then begin combotractores.Visible:=false; combodepositos.Visible:=false; combooperarios.Visible:=false; combometeorologia.Visible:=false; end; qproductos.Close; qproductos.Open; end; procedure Tcargastratamientos.dscargasStateChange(Sender: TObject); begin if qcargas.State in [dsbrowse] then begin qproductos.Close; qproductos.Open; combotractores.Visible:=false; combodepositos.Visible:=false; combooperarios.Visible:=false; combometeorologia.Visible:=false; end end; procedure Tcargastratamientos.FormKeyPress(Sender: TObject; var Key: Char); begin key:=upcase(key); if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; // si presionamos ESC if (key=#$1B) and (activecontrol is tdblookupcombobox )then begin activecontrol.Visible:=false; end; end; procedure Tcargastratamientos.FormShow(Sender: TObject); begin qcargas.Open; qfumigadoras.Open; qmeteorologia.Open; qoperarios.Open; qtractores.open; end; procedure Tcargastratamientos.qcargasAfterInsert(DataSet: TDataSet); begin qcargasfecha.Value:=date(); qcargashora_inicio.Value:=time(); end; procedure Tcargastratamientos.qcargasAfterPost(DataSet: TDataSet); begin updatehorafin.Prepare; updatehorafin.ParamByName('TRATAMIENTO').AsInteger:=qcargasidt.AsInteger; updatehorafin.ParamByName('IDCARGA').AsInteger:=qcargasid.AsInteger; updatehorafin.ParamByName('EMPRESA').AsInteger:=qcargaside.AsInteger; updatehorafin.ParamByName('HORA').AsTime:=qcargashora_inicio.AsDateTime; updatehorafin.ExecSQL; qcargas.Refresh; abort; end; procedure Tcargastratamientos.qcargasBeforeOpen(DataSet: TDataSet); begin qcargas.Prepare; qcargas.ParamByName('EMPRESA').AsInteger:=vempresa; qcargas.ParamByName('TRATAMIENTO').AsInteger:=vtratamiento; end; procedure Tcargastratamientos.qcargasBeforePost(DataSet: TDataSet); begin qcargaside.Value:=vempresa; qcargasidt.Value:=vtratamiento; end; procedure Tcargastratamientos.qfumigadorasBeforeOpen(DataSet: TDataSet); begin qfumigadoras.Prepare; qfumigadoras.ParamByName('EMPRESA').AsInteger:=vempresa; end; procedure Tcargastratamientos.qmeteorologiaBeforeOpen(DataSet: TDataSet); begin qmeteorologia.Prepare; qmeteorologia.ParamByName('EMPRESA').AsInteger:=vempresa; end; procedure Tcargastratamientos.qoperariosBeforeOpen(DataSet: TDataSet); begin qoperarios.Prepare; qoperarios.ParamByName('EMPRESA').AsInteger:=vempresa; end; procedure Tcargastratamientos.qproductosBeforeOpen(DataSet: TDataSet); begin qproductos.Prepare; qproductos.ParamByName('EMPRESA').AsInteger:=vempresa; qproductos.ParamByName('TRATAMIENTO').AsInteger:=vtratamiento; qproductos.ParamByName('MEZCLA').Asfloat:=qcargascantidad.asfloat; end; procedure Tcargastratamientos.qtractoresBeforeOpen(DataSet: TDataSet); begin qtractores.Prepare; qtractores.ParamByName('EMPRESA').AsInteger:=vempresa; end; end. ======================================== FICHERO: fcc_basculas.pas ======================================== unit fcc_basculas; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractDataset, ZDataset, ZAbstractRODataset, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.DBCtrls, Vcl.ExtCtrls, frxClass, frxDBSet, frxExportBaseDialog, frxExportPDF; type Tcc_basculas = class(TForm) frxPDFExport1: TfrxPDFExport; gcrpagado: TDBCheckBox; informedb: TfrxDBDataset; informedbempresa: TfrxDBDataset; informedbencargado: TfrxDBDataset; informes: TfrxReport; Panel1: TPanel; Label1: TLabel; Label3: TLabel; combocampanyas: TDBLookupComboBox; comboencargado: TDBLookupComboBox; bteimprimir: TButton; Panel2: TPanel; DBGrid1: TDBGrid; qcampanyas: TZReadOnlyQuery; qcampanyasid: TIntegerField; qcampanyasidempresa: TIntegerField; qcampanyasid_anterior: TIntegerField; qcampanyasdescripcion: TWideStringField; qcampanyasfechainicio: TDateField; qcampanyasfechafin: TDateField; qcampanyasult_pesada: TIntegerField; qcc_basculas: TZQuery; qcontroladores: TZReadOnlyQuery; qcontroladoresnombre: TWideStringField; qcontroladoreside: TIntegerField; qcontroladoresid: TSmallintField; qcontroladoresfirma: TBlobField; qinsertar: TZQuery; qcc_basculaside: TIntegerField; qcc_basculasfecha: TDateField; qcc_basculasidb: TIntegerField; qcc_basculaspeso_muestra: TFloatField; qcc_basculaspeso_real: TFloatField; dsqcampanyas: TDataSource; dscontroladores: TDataSource; dsqccbasculas: TDataSource; qcc_basculasdescripcion: TWideStringField; qcc_basculasinf: TZQuery; dsqccbasculasinf: TDataSource; qcc_basculasinfide: TIntegerField; qcc_basculasinffecha: TDateField; qcc_basculasinfidb: TIntegerField; qcc_basculasinfdescripcion: TWideStringField; qcc_basculasinfpeso_muestra: TFloatField; qcc_basculasinfpeso_real: TFloatField; procedure dsqcampanyasDataChange(Sender: TObject; Field: TField); procedure FormShow(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure bteimprimirClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var cc_basculas: Tcc_basculas; const rojo=$00AAAAFF; amarillo=$00B9FFFF; verde=$00C7FBAA; azul=$00FFFFBB; implementation {$R *.dfm} procedure Tcc_basculas.bteimprimirClick(Sender: TObject); begin qcc_basculasinf.Close; qcc_basculasinf.Prepare; qcc_basculasinf.ParamByName('FECHAINICIO').AsDate:=qcampanyasfechainicio.AsDateTime; qcc_basculasinf.ParamByName('FECHAFIN').AsDate:=qcampanyasfechafin.AsDateTime; qcc_basculasinf.Open; informedb.Datasource:=dsqccbasculasinf; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\infccbasculas.fr3'); informes.Variables.Variables['CAMPANYA']:=QUOTEDSTR(qcampanyasdescripcion.asstring); informes.ShowReport(); end; procedure Tcc_basculas.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if (qcc_basculaspeso_real.AsString='') then begin DBGrid1.Canvas.brush.Color := rojo; end else DBGrid1.Canvas.brush.Color := verde; DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure Tcc_basculas.dsqcampanyasDataChange(Sender: TObject; Field: TField); begin qinsertar.Close; qinsertar.Prepare; qinsertar.ParamByName('FECHAINICIO').AsDate:=qcampanyasfechainicio.AsDateTime; qinsertar.ParamByName('FECHAFIN').AsDate:=qcampanyasfechafin.AsDateTime; qinsertar.ExecSQL; qcc_basculas.Close; qcc_basculas.Prepare; qcc_basculas.ParamByName('FECHAINICIO').AsDate:=qcampanyasfechainicio.AsDateTime; qcc_basculas.ParamByName('FECHAFIN').AsDate:=qcampanyasfechafin.AsDateTime; qcc_basculas.Open; end; procedure Tcc_basculas.FormKeyPress(Sender: TObject; var Key: Char); begin key:=upcase(key); if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; // si presionamos ESC if (key=#$1B) and (activecontrol is tdblookupcombobox )then begin activecontrol.Visible:=false; end; end; procedure Tcc_basculas.FormShow(Sender: TObject); begin qcampanyas.Open; qcontroladores.Open; combocampanyas.Keyvalue:=qcampanyasid.asstring; comboencargado.Keyvalue:=qcontroladoresnombre.asstring; end; end. ======================================== FICHERO: fcc_camaras.pas ======================================== unit fcc_camaras; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractDataset, ZDataset, ZAbstractRODataset, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.DBCtrls, Vcl.ExtCtrls, frxClass, frxDBSet, frxExportBaseDialog, frxExportPDF; type Tcc_camaras = class(TForm) frxPDFExport1: TfrxPDFExport; gcrpagado: TDBCheckBox; informedb: TfrxDBDataset; informedbempresa: TfrxDBDataset; informedbencargado: TfrxDBDataset; informes: TfrxReport; Panel1: TPanel; Label1: TLabel; Label3: TLabel; combocampanyas: TDBLookupComboBox; comboencargado: TDBLookupComboBox; bteimprimir: TButton; Panel2: TPanel; DBGrid1: TDBGrid; qcampanyas: TZReadOnlyQuery; qcampanyasid: TIntegerField; qcampanyasidempresa: TIntegerField; qcampanyasid_anterior: TIntegerField; qcampanyasdescripcion: TWideStringField; qcampanyasfechainicio: TDateField; qcampanyasfechafin: TDateField; qcampanyasult_pesada: TIntegerField; qcc_camaras: TZQuery; qcc_camarasinf: TZQuery; qcontroladores: TZReadOnlyQuery; qcontroladoresnombre: TWideStringField; qcontroladoreside: TIntegerField; qcontroladoresid: TSmallintField; qcontroladoresfirma: TBlobField; qinsertar: TZQuery; dsqcampanyas: TDataSource; dscontroladores: TDataSource; dsqcccamaras: TDataSource; dsqcccamarasinf: TDataSource; qcc_camaraside: TIntegerField; qcc_camarasfecha: TDateField; qcc_camarasidal: TIntegerField; qcc_camarasdescripcion: TWideStringField; qcc_camarastemperatura: TFloatField; qcc_camarasinfide: TIntegerField; qcc_camarasinffecha: TDateField; qcc_camarasinfidal: TIntegerField; qcc_camarasinfdescripcion: TWideStringField; qcc_camarasinftemperatura: TFloatField; qcc_camarastemperatura2: TFloatField; qcc_camarasinftemperatura2: TFloatField; qcc_camarastemperatura3: TFloatField; qcc_camarastemperatura4: TFloatField; qcc_camarasinftemperatura3: TFloatField; qcc_camarasinftemperatura4: TFloatField; procedure bteimprimirClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); procedure dsqcampanyasDataChange(Sender: TObject; Field: TField); procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); private { Private declarations } public { Public declarations } end; var cc_camaras: Tcc_camaras; const rojo=$00AAAAFF; amarillo=$00B9FFFF; verde=$00C7FBAA; azul=$00FFFFBB; implementation {$R *.dfm} procedure Tcc_camaras.bteimprimirClick(Sender: TObject); begin qcc_camarasinf.Close; qcc_camarasinf.Prepare; qcc_camarasinf.ParamByName('FECHAINICIO').AsDate:=qcampanyasfechainicio.AsDateTime; qcc_camarasinf.ParamByName('FECHAFIN').AsDate:=qcampanyasfechafin.AsDateTime; qcc_camarasinf.Open; informedb.Datasource:=dsqcccamarasinf; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\infcccamaras.fr3'); informes.Variables.Variables['CAMPANYA']:=QUOTEDSTR(qcampanyasdescripcion.asstring); informes.ShowReport(); end; procedure Tcc_camaras.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if (qcc_camarastemperatura.AsString='') then begin DBGrid1.Canvas.brush.Color := rojo; end else DBGrid1.Canvas.brush.Color := verde; DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure Tcc_camaras.dsqcampanyasDataChange(Sender: TObject; Field: TField); begin qinsertar.Close; qinsertar.Prepare; qinsertar.ParamByName('FECHAINICIO').AsDate:=qcampanyasfechainicio.AsDateTime; qinsertar.ParamByName('FECHAFIN').AsDate:=qcampanyasfechafin.AsDateTime; qinsertar.ExecSQL; qcc_camaras.Close; qcc_camaras.Prepare; qcc_camaras.ParamByName('FECHAINICIO').AsDate:=qcampanyasfechainicio.AsDateTime; qcc_camaras.ParamByName('FECHAFIN').AsDate:=qcampanyasfechafin.AsDateTime; qcc_camaras.Open; end; procedure Tcc_camaras.FormKeyPress(Sender: TObject; var Key: Char); begin key:=upcase(key); if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; // si presionamos ESC if (key=#$1B) and (activecontrol is tdblookupcombobox )then begin activecontrol.Visible:=false; end; end; procedure Tcc_camaras.FormShow(Sender: TObject); begin qcampanyas.Open; qcontroladores.Open; combocampanyas.Keyvalue:=qcampanyasid.asstring; comboencargado.Keyvalue:=qcontroladoresnombre.asstring; end; end. ======================================== FICHERO: fcc_controlproducto.pas ======================================== unit fcc_controlproducto; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractDataset, ZDataset, ZAbstractRODataset, Vcl.Grids, Vcl.DBGrids, Vcl.DBCtrls, Vcl.StdCtrls, Vcl.ExtCtrls, frxClass, frxDBSet, frxExportBaseDialog, frxExportPDF; type Tcc_controlproducto = class(TForm) frxPDFExport1: TfrxPDFExport; informedb: TfrxDBDataset; informedbempresa: TfrxDBDataset; informes: TfrxReport; Panel14: TPanel; btEcancelar: TButton; btEmodificar: TButton; btEborrar: TButton; btEnuevo: TButton; btEguardar: TButton; bteimprimir: TButton; Panel2: TPanel; Label3: TLabel; Label4: TLabel; comboencargado: TDBLookupComboBox; combocampanya: TDBLookupComboBox; Panel3: TPanel; DBGrid1: TDBGrid; qinsertar: TZReadOnlyQuery; qcampanyas: TZReadOnlyQuery; qcampanyasid: TIntegerField; qcampanyasidempresa: TIntegerField; qcampanyasid_anterior: TIntegerField; qcampanyasdescripcion: TWideStringField; qcampanyasfechainicio: TDateField; qcampanyasfechafin: TDateField; qcampanyasult_pesada: TIntegerField; qcc_productosacabados: TZQuery; qcontroladores: TZReadOnlyQuery; qcontroladoresnombre: TWideStringField; qcontroladoreside: TIntegerField; qcontroladoresid: TSmallintField; qcontroladoresfirma: TBlobField; qcc_productosacabadosinf: TZQuery; dsqcontroladores: TDataSource; dsqcampanyas: TDataSource; dsqccproductosacabados: TDataSource; qcc_productosacabadoside: TIntegerField; qcc_productosacabadosidp: TIntegerField; qcc_productosacabadosidpd: TIntegerField; qcc_productosacabadoscc_pedidocliente: TWideStringField; qcc_productosacabadoscc_producto: TWideStringField; qcc_productosacabadoscc_envase: TWideStringField; qcc_productosacabadoscc_acabado: TWideStringField; qcc_productosacabadoscc_calidad: TWideStringField; qcc_productosacabadosfecha: TDateField; qcc_productosacabadosidc: TIntegerField; qcc_productosacabadosnomcliente: TWideStringField; qcc_productosacabadoscantidad: TFloatField; qcc_productosacabadoscc_confeccion: TWideStringField; qcc_productosacabadoscc_peso: TWideStringField; qcc_productosacabadoscc_forma: TWideStringField; qcc_productosacabadoscc_aspecto: TWideStringField; qcc_productosacabadoscc_brix: TIntegerField; qcc_productosacabadoscc_plagas: TWideStringField; qcc_productosacabadoscc_golpes: TWideStringField; qcc_productosacabadoscc_sabor: TWideStringField; qcc_productosacabadoscc_cantidad: TWideStringField; qcc_productosacabadoscc_codigobarras: TWideStringField; qcc_productosacabadoscc_codigos: TWideStringField; qcc_productosacabadoscc_menciones: TWideStringField; qcc_productosacabadoscc_impresion: TWideStringField; qcc_productosacabadoscc_envasado: TWideStringField; qcc_productosacabadoscc_paletizado: TWideStringField; qcc_productosacabadoscc_ausenciacuerpos: TWideStringField; qcc_productosacabadoscc_antes: TWideStringField; qcc_productosacabadoscc_durante: TWideStringField; qcc_productosacabadoscc_final: TWideStringField; informedbencargado: TfrxDBDataset; dsqccproductosacabadosinf: TDataSource; qcc_productosacabadosinfide: TIntegerField; qcc_productosacabadosinfidp: TIntegerField; qcc_productosacabadosinfidpd: TIntegerField; qcc_productosacabadosinfcc_pedidocliente: TWideStringField; qcc_productosacabadosinfcc_producto: TWideStringField; qcc_productosacabadosinfcc_envase: TWideStringField; qcc_productosacabadosinfcc_acabado: TWideStringField; qcc_productosacabadosinfcc_calidad: TWideStringField; qcc_productosacabadosinffecha: TDateField; qcc_productosacabadosinfidc: TIntegerField; qcc_productosacabadosinfnomcliente: TWideStringField; qcc_productosacabadosinfcantidad: TFloatField; qcc_productosacabadosinfcc_confeccion: TWideStringField; qcc_productosacabadosinfcc_peso: TWideStringField; qcc_productosacabadosinfcc_forma: TWideStringField; qcc_productosacabadosinfcc_aspecto: TWideStringField; qcc_productosacabadosinfcc_brix: TIntegerField; qcc_productosacabadosinfcc_plagas: TWideStringField; qcc_productosacabadosinfcc_golpes: TWideStringField; qcc_productosacabadosinfcc_sabor: TWideStringField; qcc_productosacabadosinfcc_cantidad: TWideStringField; qcc_productosacabadosinfcc_codigobarras: TWideStringField; qcc_productosacabadosinfcc_codigos: TWideStringField; qcc_productosacabadosinfcc_menciones: TWideStringField; qcc_productosacabadosinfcc_impresion: TWideStringField; qcc_productosacabadosinfcc_envasado: TWideStringField; qcc_productosacabadosinfcc_paletizado: TWideStringField; qcc_productosacabadosinfcc_ausenciacuerpos: TWideStringField; qcc_productosacabadosinfcc_antes: TWideStringField; qcc_productosacabadosinfcc_durante: TWideStringField; qcc_productosacabadosinfcc_final: TWideStringField; procedure FormShow(Sender: TObject); procedure dsqcampanyasDataChange(Sender: TObject; Field: TField); procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure bteimprimirClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } end; var cc_controlproducto: Tcc_controlproducto; const rojo=$00AAAAFF; amarillo=$00B9FFFF; verde=$00C7FBAA; azul=$00FFFFBB; implementation {$R *.dfm} procedure Tcc_controlproducto.bteimprimirClick(Sender: TObject); begin qcc_productosacabadosinf.Close; qcc_productosacabadosinf.Prepare; qcc_productosacabadosinf.ParamByName('FECHAINICIO').AsDate:=qcampanyasfechainicio.AsDateTime; qcc_productosacabadosinf.ParamByName('FECHAFIN').AsDate:=qcampanyasfechafin.AsDateTime; qcc_productosacabadosinf.ParamByName('EMPRESA').Asinteger:=qcampanyasidempresa.Asinteger; qcc_productosacabadosinf.Open; informedb.Datasource:=dsqccproductosacabadosinf; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\infccproductoacabado.fr3'); informes.Variables.Variables['CAMPANYA']:=QUOTEDSTR(qcampanyasdescripcion.asstring); informes.ShowReport(); end; procedure Tcc_controlproducto.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if (qcc_productosacabadoscc_brix.AsString='') then begin DBGrid1.Canvas.brush.Color := rojo; end else DBGrid1.Canvas.brush.Color := verde; DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure Tcc_controlproducto.dsqcampanyasDataChange(Sender: TObject; Field: TField); begin qinsertar.Close; qinsertar.Prepare; qinsertar.ParamByName('FECHAINICIO').AsDate:=qcampanyasfechainicio.AsDateTime; qinsertar.ParamByName('FECHAFIN').AsDate:=qcampanyasfechafin.AsDateTime; qinsertar.ExecSQL; qcc_productosacabados.Close; qcc_productosacabados.Prepare; qcc_productosacabados.ParamByName('FECHAINICIO').AsDate:=qcampanyasfechainicio.AsDateTime; qcc_productosacabados.ParamByName('FECHAFIN').AsDate:=qcampanyasfechafin.AsDateTime; qcc_productosacabados.ParamByName('EMPRESA').Asinteger:=qcampanyasidempresa.Asinteger; qcc_productosacabados.Open; end; procedure Tcc_controlproducto.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tcc_controlproducto.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is 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 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 Tcc_controlproducto.FormShow(Sender: TObject); begin qcampanyas.Open; combocampanya.KeyValue:=qcampanyasdescripcion.AsString; qcontroladores.Open; comboencargado.KeyValue:=qcontroladoresnombre.AsString; end; end. ======================================== FICHERO: fcc_expediciones.pas ======================================== unit fcc_expediciones; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZDataset, Vcl.StdCtrls, wgssSTU_TLB,SignatureForm, Vcl.ExtCtrls, ZAbstractTable, ZAbstractRODataset, ZAbstractDataset, Vcl.Grids, Vcl.DBGrids, Vcl.DBCtrls, Vcl.Mask, frxClass, frxExportPDF, frxDBSet, frxExportBaseDialog; type Tcc_expediciones = class(TForm) Panel2: TPanel; Panel3: TPanel; DBGrid1: TDBGrid; dsqexpediciones: TDataSource; qcc_expediciones: TZQuery; tfirmas: TImage; btfirmar: TButton; qalbaranes: TZReadOnlyQuery; qcontroladores: TZReadOnlyQuery; qcontroladoresnombre: TWideStringField; qalbaranesidempresa: TIntegerField; qalbaranesserie: TWideStringField; qalbaranesid: TIntegerField; qcontroladoreside: TIntegerField; qvariedades: TZReadOnlyQuery; qalbaranesfecha: TDateField; comboencargado: TDBLookupComboBox; dsqvariedades: TDataSource; dsqalbaranes: TDataSource; dscontroladores: TDataSource; Panel14: TPanel; btEcancelar: TButton; btEmodificar: TButton; btEborrar: TButton; btEnuevo: TButton; btEguardar: TButton; bteimprimir: TButton; Label3: TLabel; Label1: TLabel; comboalbaran: TDBLookupComboBox; qcc_expedicioneside: TIntegerField; qcc_expedicionesserie: TWideStringField; qcc_expedicionesfecha: TDateField; qcc_expedicionesvariedad: TWideStringField; qcc_expedicionesausencia: TWideStringField; qcc_expedicioneslimpieza: TWideStringField; qcc_expedicionesestado_vehiculo: TWideStringField; qcc_expedicionesestado_carga: TWideStringField; qcc_expedicionesetiquetado: TWideStringField; qcc_expedicionestemp_camion: TIntegerField; qcc_expedicionestemp_producto: TIntegerField; qcc_expedicionessabotaje: TWideStringField; qcc_expedicionesnomresponsable: TWideStringField; Label2: TLabel; combovariedad: TDBLookupComboBox; qvariedadesdescripcion: TWideStringField; qvariedadesidempresa: TIntegerField; DBCheckBox4: TDBCheckBox; DBCheckBox1: TDBCheckBox; DBCheckBox2: TDBCheckBox; DBCheckBox3: TDBCheckBox; DBCheckBox5: TDBCheckBox; DBCheckBox6: TDBCheckBox; Label4: TLabel; combocampanya: TDBLookupComboBox; dscampanyas: TDataSource; qcampanyas: TZReadOnlyQuery; qcampanyasid: TIntegerField; qcampanyasidempresa: TIntegerField; qcampanyasid_anterior: TIntegerField; qcampanyasdescripcion: TWideStringField; qcampanyasfechainicio: TDateField; qcampanyasfechafin: TDateField; qcampanyasult_pesada: TIntegerField; qcontroladoresid: TSmallintField; qcontroladoresfirma: TBlobField; DBText1: TDBText; DBText2: TDBText; Label5: TLabel; Label6: TLabel; qcc_expedicionesfirma: TBlobField; Label7: TLabel; Label8: TLabel; DBEdit1: TDBEdit; DBEdit2: TDBEdit; informedb: TfrxDBDataset; informes: TfrxReport; frxPDFExport1: TfrxPDFExport; qaux: TZReadOnlyQuery; qcc_expedicionesida: TIntegerField; dsqexpedicionesinf: TDataSource; qexpedicionesinf: TZQuery; qexpedicionesinfide: TIntegerField; qexpedicionesinfserie: TWideStringField; qexpedicionesinfida: TIntegerField; qexpedicionesinffecha: TDateField; qexpedicionesinfvariedad: TWideStringField; qexpedicionesinfausencia: TWideStringField; qexpedicionesinflimpieza: TWideStringField; qexpedicionesinfestado_vehiculo: TWideStringField; qexpedicionesinfestado_carga: TWideStringField; qexpedicionesinfetiquetado: TWideStringField; qexpedicionesinftemp_camion: TIntegerField; qexpedicionesinftemp_producto: TIntegerField; qexpedicionesinfsabotaje: TWideStringField; qexpedicionesinfnomresponsable: TWideStringField; qexpedicionesinffirma: TBlobField; Label9: TLabel; DBEdit3: TDBEdit; informedbempresa: TfrxDBDataset; qcc_expedicionesbrix: TIntegerField; qexpedicionesinfbrix: TIntegerField; informedbencargado: TfrxDBDataset; procedure btfirmarClick(Sender: TObject); procedure dsqexpedicionesStateChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure dscampanyasDataChange(Sender: TObject; Field: TField); procedure btEnuevoClick(Sender: TObject); procedure btEborrarClick(Sender: TObject); procedure btEmodificarClick(Sender: TObject); procedure btEguardarClick(Sender: TObject); procedure btEcancelarClick(Sender: TObject); procedure qcc_expedicionesBeforePost(DataSet: TDataSet); procedure dsqexpedicionesDataChange(Sender: TObject; Field: TField); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure bteimprimirClick(Sender: TObject); procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure qcc_expedicionesBeforeDelete(DataSet: TDataSet); private { Private declarations } hWndC,hWndC2 : THandle; public { Public declarations } end; var cc_expediciones: Tcc_expediciones; const 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 datos; procedure Tcc_expediciones.btEborrarClick(Sender: TObject); begin qcc_expediciones.Delete; qalbaranes.Refresh; qalbaranes.First; comboalbaran.keyvalue:=qalbaranesid.AsString; end; procedure Tcc_expediciones.btEcancelarClick(Sender: TObject); begin qcc_expediciones.Cancel; end; procedure Tcc_expediciones.btEguardarClick(Sender: TObject); begin if qcc_expediciones.State in [dsinsert] then begin qcc_expedicionesserie.Value:=qalbaranesserie.AsString; qcc_expedicionesida.Value:=qalbaranesid.Asinteger; qcc_expedicioneside.Value:=qalbaranesidempresa.Asinteger; qcc_expedicionesfecha.Value:=qalbaranesfecha.Asdatetime; qcc_expedicionesvariedad.Value:=qvariedadesdescripcion.Asstring; qcc_expedicionesnomresponsable.Value:=qcontroladoresnombre.Asstring; qcc_expediciones.Post; end else begin if combovariedad.keyvalue<>null then qcc_expedicionesvariedad.Value:=qvariedadesdescripcion.Asstring; if comboencargado.KeyValue<>null then qcc_expedicionesnomresponsable.Value:=qcontroladoresnombre.Asstring; if qcontroladoresfirma.AsString='' then begin qcc_expedicionesfirma.Value:=nil; end else begin btfirmar.Click; end; qcc_expediciones.Post; end; qalbaranes.Refresh; qalbaranes.First; comboalbaran.keyvalue:=qalbaranesid.AsString; end; procedure Tcc_expediciones.bteimprimirClick(Sender: TObject); begin qexpedicionesinf.SQL.Clear; qexpedicionesinf.SQL.Add('select * from ('+qcc_expediciones.sql.text+') as expediciones where firma is not null and temp_camion is not null and temp_producto is not null order by serie,ida'); qexpedicionesinf.Open; informedb.Datasource:=dsqexpedicionesinf; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\infccexpediciones.fr3'); informes.Variables.Variables['CAMPANYA']:=QUOTEDSTR(qcampanyasdescripcion.asstring); informes.ShowReport(); end; procedure Tcc_expediciones.btEmodificarClick(Sender: TObject); begin qcc_expediciones.Edit; end; procedure Tcc_expediciones.btEnuevoClick(Sender: TObject); begin qcc_expediciones.Append; qcc_expedicionesausencia.Value:='C'; qcc_expedicioneslimpieza.Value:='C'; qcc_expedicionesestado_vehiculo.Value:='C'; qcc_expedicionesestado_carga.Value:='C'; qcc_expedicionesetiquetado.Value:='C'; qcc_expedicionessabotaje.Value:='NO'; end; procedure Tcc_expediciones.btfirmarClick(Sender: TObject); var usbDevices : IUsbDevices; usbDevice : IUsbDevice; vcontrolador:string; begin vcontrolador:=qcc_expedicionesnomresponsable.asstring; if vcontrolador='' then begin comboencargado.KeyValue:=null; end else begin qaux.close; qaux.sql.clear; qaux.sql.add('select id from trabajadores where nombre='+''''+vcontrolador+''''); qaux.open; if qaux.RecordCount>0 then begin qcontroladores.Locate('nombre',vcontrolador,[locaseinsensitive]); comboencargado.KeyValue:=qcontroladoresnombre.AsString; end; end; tfirmas.Picture:=nil; 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; if qcc_expediciones.State in [dsedit,dsinsert] then begin qcc_expedicionesfirma.LoadFromFile('c:\agrigest\tmp\firma.bmp'); // bteguardar.Click; end else begin qcc_expediciones.edit; qcc_expedicionesfirma.LoadFromFile('c:\agrigest\tmp\firma.bmp'); // bteguardar.Click; end; // tfirmas.Picture.LoadFromFile('c:\agrigest\tmp\firma.bmp'); // Deletefile('c:\agrigest\informes\firma.bmp'); end else begin qcontroladoresfirma.SaveToFile('c:\agrigest\tmp\firma.bmp'); if qcc_expediciones.State in [dsedit,dsinsert] then begin qcc_expedicionesfirma.LoadFromFile('c:\agrigest\tmp\firma.bmp'); // bteguardar.Click; end else begin qcc_expediciones.edit; qcc_expedicionesfirma.LoadFromFile('c:\agrigest\tmp\firma.bmp'); qcc_expediciones.Post;//.Click; end; // tfirmas.Picture.LoadFromFile('c:\agrigest\tmp\firma.bmp'); // Deletefile('c:\agrigest\informes\firma.bmp'); // ShowMessage('Dispositivo de firmas no conectado'); end; end; procedure Tcc_expediciones.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if (qcc_expedicionesfirma.AsString='') or (qcc_expedicionestemp_camion.AsString='') or (qcc_expedicionestemp_producto.AsString='') then begin DBGrid1.Canvas.brush.Color := rojo; end else DBGrid1.Canvas.brush.Color := verde; DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure Tcc_expediciones.dscampanyasDataChange(Sender: TObject; Field: TField); var anyo,mes,dia:word; vanyo,vmes,vdia,vmessig,vfechainicio,vfechafin,variedades:string; begin decodedate(qcampanyasfechainicio.AsDateTime,anyo,mes,dia); vanyo:=floattostr(anyo); vmes:=floattostr(mes); vdia:=floattostr(dia); vfechainicio:=''''+vanyo+'-'+vmes+'-'+vdia+''''; decodedate(qcampanyasfechafin.AsDateTime,anyo,mes,dia); vanyo:=floattostr(anyo); vmes:=floattostr(mes); vdia:=floattostr(dia); vfechafin:=''''+vanyo+'-'+vmes+'-'+vdia+''''; qalbaranes.SQL.Clear; qalbaranes.SQL.Add('select idempresa,serie,id,fecha from albaranes where fecha>='+vfechainicio+' and fecha<='+vfechafin+' and (idempresa,serie,id) not in (select ide,serie,ida from cc_expediciones) order by serie,id desc'); qalbaranes.Open; qcc_expediciones.SQL.Clear; qcc_expediciones.SQL.Add('select * from cc_expediciones where fecha>='+vfechainicio+' and fecha<='+vfechafin+' order by serie,ida'); qcc_expediciones.Open; if qalbaranes.RecordCount>0 then begin while not qalbaranes.Eof do begin variedades:=''; qcc_expediciones.Append; qcc_expedicioneside.value:=qalbaranesidempresa.AsInteger; qcc_expedicionesserie.value:=qalbaranesserie.Asstring; qcc_expedicionesida.value:=qalbaranesid.Asinteger; qcc_expedicionesfecha.value:=qalbaranesfecha.Asdatetime; qaux.close; qaux.ParamByName('ALBARAN').AsString:=qalbaranesserie.AsString+'/'+qalbaranesid.AsString; qaux.Prepare; qaux.Open; while not qaux.Eof do begin variedades:=variedades+qaux.Fields[0].AsString+'/'; qaux.Next; end; qcc_expedicionesvariedad.value:=variedades; qcc_expedicionesausencia.value:='C'; qcc_expedicioneslimpieza.value:='C'; qcc_expedicionesestado_vehiculo.value:='C'; qcc_expedicionesestado_carga.value:='C'; qcc_expedicionesetiquetado.value:='C'; qcc_expedicionessabotaje.value:='NO'; qcc_expediciones.Post; qalbaranes.Next; end; end; end; procedure Tcc_expediciones.dsqexpedicionesDataChange(Sender: TObject; Field: TField); begin // Deletefile('c:\agrigest\tmp\firma.bmp'); if qcc_expediciones.State in [dsbrowse] then begin if qcc_expedicionesfirma.AsString<>'' then begin qcc_expedicionesfirma.savetoFile('c:\agrigest\tmp\firma.bmp'); tfirmas.Picture.LoadFromFile('c:\agrigest\tmp\firma.bmp'); Deletefile('c:\agrigest\tmp\firma.bmp'); end else begin tfirmas.Picture:=nil; end; end; end; procedure Tcc_expediciones.dsqexpedicionesStateChange(Sender: TObject); var vcontrolador,vvariedad:string; begin if qcc_expediciones.State in [dsedit] then begin vcontrolador:=qcc_expedicionesnomresponsable.asstring; vvariedad:=qcc_expedicionesvariedad.AsString; if vcontrolador='' then begin comboencargado.KeyValue:=null; end else begin qaux.close; qaux.sql.clear; qaux.sql.add('select id from trabajadores where nombre='+''''+vcontrolador+''''); qaux.open; if qaux.RecordCount>0 then begin qcontroladores.Locate('nombre',vcontrolador,[locaseinsensitive]); comboencargado.KeyValue:=qcontroladoresnombre.AsString; end; end; if vvariedad='' then begin combovariedad.KeyValue:=null; end else begin qaux.sql.clear; qaux.sql.add('select * from materias_primas where descripcion='+''''+vvariedad+''''); qaux.open; if qaux.RecordCount>0 then begin qvariedades.Locate('descripcion',vcontrolador,[locaseinsensitive]); combovariedad.KeyValue:=qvariedadesdescripcion.AsString; end else begin combovariedad.KeyValue:=null; end; end; end; if qcc_expediciones.State in [dsedit,dsinsert] then begin btenuevo.Enabled:=false; btemodificar.Enabled:=false; bteborrar.Enabled:=false; btecancelar.Enabled:=true; bteguardar.Enabled:=true; end else begin btenuevo.Enabled:=true; btemodificar.Enabled:=true; bteborrar.Enabled:=true; btecancelar.Enabled:=false; bteguardar.Enabled:=false; end; end; procedure Tcc_expediciones.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tcc_expediciones.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is 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 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 Tcc_expediciones.FormShow(Sender: TObject); begin qcampanyas.Open; combocampanya.KeyValue:=qcampanyasdescripcion.AsString; qalbaranes.Open; comboalbaran.keyvalue:=qalbaranesid.AsString; qcontroladores.Open; comboencargado.KeyValue:=qcontroladoresnombre.AsString; qvariedades.Open; combovariedad.KeyValue:=qvariedadesdescripcion.AsString; qcc_expediciones.open; end; procedure Tcc_expediciones.qcc_expedicionesBeforeDelete(DataSet: TDataSet); begin case dm.PedirConfirmacion('¿Confirma que desea borrar este registro?',true,true,false) of mrno:Abort; end; end; procedure Tcc_expediciones.qcc_expedicionesBeforePost(DataSet: TDataSet); begin if qcc_expedicionesserie.asstring='' then begin qcc_expedicionesserie.Value:=qalbaranesserie.AsString; qcc_expedicioneside.Value:=qalbaranesidempresa.Asinteger; end; end; end. ======================================== FICHERO: fcc_materiasprimas.pas ======================================== unit fcc_materiasprimas; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.DBCtrls, ZAbstractDataset, ZDataset, ZAbstractRODataset, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.StdCtrls, frxClass, frxExportPDF, frxDBSet, frxExportBaseDialog; type Tcc_materiasprimas = class(TForm) Panel1: TPanel; Panel2: TPanel; DBGrid1: TDBGrid; qcampanyas: TZReadOnlyQuery; qlotes: TZQuery; dsqcampanyas: TDataSource; combocampanyas: TDBLookupComboBox; qcampanyasid: TIntegerField; qcampanyasidempresa: TIntegerField; qcampanyasid_anterior: TIntegerField; qcampanyasdescripcion: TWideStringField; qcampanyasfechainicio: TDateField; qcampanyasfechafin: TDateField; qcampanyasult_pesada: TIntegerField; Label1: TLabel; qlotesidempresa: TIntegerField; qlotescodigo: TIntegerField; qlotesfecha: TDateField; qlotesmprima: TWideStringField; qcc_materiasprimas: TZQuery; dsqccmateriasprimas: TDataSource; dsqccmateriasprimasinf: TDataSource; qcc_materiasprimasinf: TZQuery; qcc_materiasprimaside: TIntegerField; qcc_materiasprimaslote: TIntegerField; qcc_materiasprimasfecha: TDateField; qcc_materiasprimastamanyo: TWideStringField; qcc_materiasprimasaspecto: TWideStringField; qcc_materiasprimascolor: TWideStringField; qcc_materiasprimasausencia_golpes: TWideStringField; qcc_materiasprimaslimpieza: TWideStringField; qcc_materiasprimasausencia_plagas: TWideStringField; qcc_materiasprimasausencia_insectos: TWideStringField; qcc_materiasprimasausencia_cuerpos: TWideStringField; qcc_materiasprimassabotaje: TWideStringField; qcc_materiasprimasresultado: TWideStringField; qcc_materiasprimasobservaciones: TWideStringField; qcc_materiasprimasbrix: TIntegerField; qcc_materiasprimasinfide: TIntegerField; qcc_materiasprimasinflote: TIntegerField; qcc_materiasprimasinffecha: TDateField; qcc_materiasprimasinftamanyo: TWideStringField; qcc_materiasprimasinfaspecto: TWideStringField; qcc_materiasprimasinfcolor: TWideStringField; qcc_materiasprimasinfausencia_golpes: TWideStringField; qcc_materiasprimasinflimpieza: TWideStringField; qcc_materiasprimasinfausencia_plagas: TWideStringField; qcc_materiasprimasinfausencia_insectos: TWideStringField; qcc_materiasprimasinfausencia_cuerpos: TWideStringField; qcc_materiasprimasinfsabotaje: TWideStringField; qcc_materiasprimasinfresultado: TWideStringField; qcc_materiasprimasinfobservaciones: TWideStringField; qcc_materiasprimasinfbrix: TIntegerField; Label3: TLabel; comboencargado: TDBLookupComboBox; qcontroladores: TZReadOnlyQuery; qcontroladoresnombre: TWideStringField; qcontroladoreside: TIntegerField; qcontroladoresid: TSmallintField; qcontroladoresfirma: TBlobField; dscontroladores: TDataSource; bteimprimir: TButton; informedb: TfrxDBDataset; frxPDFExport1: TfrxPDFExport; informes: TfrxReport; informedbencargado: TfrxDBDataset; informedbempresa: TfrxDBDataset; procedure FormShow(Sender: TObject); procedure dsqcampanyasDataChange(Sender: TObject; Field: TField); procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure bteimprimirClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var cc_materiasprimas: Tcc_materiasprimas; const rojo=$00AAAAFF; amarillo=$00B9FFFF; verde=$00C7FBAA; azul=$00FFFFBB; implementation {$R *.dfm} procedure Tcc_materiasprimas.bteimprimirClick(Sender: TObject); begin qcc_materiasprimasinf.SQL.Clear; qcc_materiasprimasinf.SQL.Add('select * from ('+qcc_materiasprimas.sql.text+') as materiasprimas where brix is not null order by lote'); qcc_materiasprimasinf.Open; informedb.Datasource:=dsqccmateriasprimasinf; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\infccmateriasprimas.fr3'); informes.Variables.Variables['CAMPANYA']:=QUOTEDSTR(qcampanyasdescripcion.asstring); informes.ShowReport(); end; procedure Tcc_materiasprimas.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if (qcc_materiasprimasbrix.AsString='') then begin DBGrid1.Canvas.brush.Color := rojo; end else DBGrid1.Canvas.brush.Color := verde; DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure Tcc_materiasprimas.dsqcampanyasDataChange(Sender: TObject; Field: TField); var anyo,mes,dia:word; vanyo,vmes,vdia,vmessig,vfechainicio,vfechafin,variedades:string; begin decodedate(qcampanyasfechainicio.AsDateTime,anyo,mes,dia); vanyo:=floattostr(anyo); vmes:=floattostr(mes); vdia:=floattostr(dia); vfechainicio:=''''+vanyo+'-'+vmes+'-'+vdia+''''; decodedate(qcampanyasfechafin.AsDateTime,anyo,mes,dia); vanyo:=floattostr(anyo); vmes:=floattostr(mes); vdia:=floattostr(dia); vfechafin:=''''+vanyo+'-'+vmes+'-'+vdia+''''; qlotes.SQL.Clear; qlotes.SQL.Add('select idempresa,codigo,fecha,mprima from lotes where fecha>='+vfechainicio+' and fecha<='+vfechafin+' and (idempresa,codigo) not in (select ide,lote from cc_materiasprimas) order by idempresa,codigo desc'); qlotes.Open; qcc_materiasprimas.SQL.Clear; qcc_materiasprimas.SQL.Add('select * from cc_materiasprimas where fecha>='+vfechainicio+' and fecha<='+vfechafin+' order by lote desc'); qcc_materiasprimas.Open; if qlotes.RecordCount>0 then begin while not qlotes.Eof do begin qcc_materiasprimas.Append; qcc_materiasprimaside.value:=qlotesidempresa.AsInteger; qcc_materiasprimaslote.value:=qlotescodigo.Asinteger; qcc_materiasprimasobservaciones.value:=qlotesmprima.Asstring; qcc_materiasprimasfecha.value:=qlotesfecha.Asdatetime; qcc_materiasprimastamanyo.value:='C'; qcc_materiasprimasaspecto.value:='C'; qcc_materiasprimascolor.value:='C'; qcc_materiasprimasausencia_golpes.value:='C'; qcc_materiasprimaslimpieza.value:='C'; qcc_materiasprimasausencia_plagas.value:='C'; qcc_materiasprimasausencia_insectos.value:='C'; qcc_materiasprimasausencia_cuerpos.value:='C'; qcc_materiasprimassabotaje.value:='C'; qcc_materiasprimasresultado.value:='C'; qcc_materiasprimas.Post; qlotes.Next; end; end; end; procedure Tcc_materiasprimas.FormShow(Sender: TObject); begin qcampanyas.Open; qcontroladores.Open; qlotes.Open; combocampanyas.Keyvalue:=qcampanyasid.asstring; comboencargado.Keyvalue:=qcontroladoresnombre.asstring; end; end. ======================================== FICHERO: fcc_utensilios.pas ======================================== unit fcc_utensilios; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, frxClass, frxExportBaseDialog, frxExportPDF, frxDBSet, ZAbstractDataset, ZDataset, Data.DB, ZAbstractRODataset, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.DBCtrls, Vcl.ExtCtrls; type Tcc_utensilios = class(TForm) Panel1: TPanel; Label1: TLabel; Label3: TLabel; combocampanyas: TDBLookupComboBox; comboencargado: TDBLookupComboBox; bteimprimir: TButton; Panel2: TPanel; DBGrid1: TDBGrid; dscontroladores: TDataSource; qcontroladores: TZReadOnlyQuery; qcontroladoresnombre: TWideStringField; qcontroladoreside: TIntegerField; qcontroladoresid: TSmallintField; qcontroladoresfirma: TBlobField; qcampanyas: TZReadOnlyQuery; qcampanyasid: TIntegerField; qcampanyasidempresa: TIntegerField; qcampanyasid_anterior: TIntegerField; qcampanyasdescripcion: TWideStringField; qcampanyasfechainicio: TDateField; qcampanyasfechafin: TDateField; qcampanyasult_pesada: TIntegerField; dsqcampanyas: TDataSource; qcc_utensilios: TZQuery; dsqccutensilios: TDataSource; informedb: TfrxDBDataset; informedbempresa: TfrxDBDataset; informedbencargado: TfrxDBDataset; frxPDFExport1: TfrxPDFExport; informes: TfrxReport; qcc_utensilioside: TIntegerField; qcc_utensiliosfecha: TDateField; qcc_utensiliosidut: TWideStringField; qcc_utensiliosidt: TIntegerField; qcc_utensiliosentrega_mañana: TTimeField; qcc_utensiliosentrega_tarde: TTimeField; qcc_utensiliosdevolucion_mañana: TTimeField; qcc_utensiliosdevolucion_tarde: TTimeField; qcc_utensilioslimpieza: TIntegerField; qcc_utensiliosobservaciones: TWideStringField; gcrpagado: TDBCheckBox; qinsertar: TZQuery; qcc_utensiliosnombre: TWideStringField; qcc_utensiliosdescripcion: TWideStringField; Button1: TButton; procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); procedure dsqcampanyasDataChange(Sender: TObject; Field: TField); procedure DBGrid1CellClick(Column: TColumn); procedure bteimprimirClick(Sender: TObject); procedure DBGrid1TitleClick(Column: TColumn); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var cc_utensilios: Tcc_utensilios; implementation {$R *.dfm} procedure Tcc_utensilios.bteimprimirClick(Sender: TObject); begin informedb.Datasource:=dsqccutensilios; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\infccutensilios.fr3'); informes.Variables.Variables['CAMPANYA']:=QUOTEDSTR(qcampanyasdescripcion.asstring); informes.ShowReport(); end; procedure Tcc_utensilios.Button1Click(Sender: TObject); begin qcc_utensilios.Delete; end; procedure Tcc_utensilios.DBGrid1CellClick(Column: TColumn); begin if column.Field.FieldName ='limpieza' then begin if qcc_utensilioslimpieza.asinteger=1 then begin qcc_utensilios.Edit; qcc_utensilioslimpieza.Value:=0; qcc_utensilios.Post; dbgrid1.selectedIndex:=1; end else begin qcc_utensilios.Edit; qcc_utensilioslimpieza.Value:=1; qcc_utensilios.Post; qcc_utensilios.Refresh; dbgrid1.SelectedIndex:=1; end; end; end; procedure Tcc_utensilios.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); const IsChecked : array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED); var DrawState,imgindex,bmpwidth: Integer; DrawRect: TRect; fixRect:TRect; begin if (gdFocused in State) then begin if (Column.Field.FieldName = 'limpieza') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'limpieza') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; // DrawState := ISChecked[Column.Field.Asboolean]; DBgrid1.Canvas.FillRect(Rect); DrawFrameControl(DBgrid1.Canvas.Handle, DrawRect,DFC_BUTTON, DrawState); end; end; gcrpagado.visible:=false; end; procedure Tcc_utensilios.DBGrid1TitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=qcc_utensilios.SortType; qcc_utensilios.SortedFields:=Column.FieldName; If st = stAscending then qcc_utensilios.SortType:=stDescending else qcc_utensilios.SortType:=stAscending; dsqccutensilios.DataSet.First; end; procedure Tcc_utensilios.dsqcampanyasDataChange(Sender: TObject; Field: TField); begin qinsertar.Close; qinsertar.Prepare; qinsertar.ParamByName('FECHAINICIO').AsDate:=qcampanyasfechainicio.AsDateTime; qinsertar.ParamByName('FECHAFIN').AsDate:=qcampanyasfechafin.AsDateTime; qinsertar.ExecSQL; qcc_utensilios.Close; qcc_utensilios.Prepare; qcc_utensilios.ParamByName('FECHAINICIO').AsDate:=qcampanyasfechainicio.AsDateTime; qcc_utensilios.ParamByName('FECHAFIN').AsDate:=qcampanyasfechafin.AsDateTime; qcc_utensilios.Open; end; procedure Tcc_utensilios.FormKeyPress(Sender: TObject; var Key: Char); begin key:=upcase(key); if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; // si presionamos ESC if (key=#$1B) and (activecontrol is tdblookupcombobox )then begin activecontrol.Visible:=false; end; end; procedure Tcc_utensilios.FormShow(Sender: TObject); begin qcampanyas.Open; qcontroladores.Open; combocampanyas.Keyvalue:=qcampanyasid.asstring; comboencargado.Keyvalue:=qcontroladoresnombre.asstring; end; end. ======================================== FICHERO: fcc_vidacomercial.pas ======================================== unit fcc_vidacomercial; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, frxClass, frxExportPDF, frxDBSet, Data.DB, ZAbstractDataset, ZDataset, ZAbstractRODataset, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.DBCtrls, Vcl.ExtCtrls, frxExportBaseDialog; type Tcc_vidacomercial = class(TForm) Panel1: TPanel; Label1: TLabel; Label3: TLabel; combocampanyas: TDBLookupComboBox; comboencargado: TDBLookupComboBox; bteimprimir: TButton; Panel2: TPanel; DBGrid1: TDBGrid; dscontroladores: TDataSource; qcontroladores: TZReadOnlyQuery; dsqcampanyas: TDataSource; qlotes: TZQuery; qcampanyas: TZReadOnlyQuery; qcc_vidacomercial: TZQuery; dsqccvidacomercial: TDataSource; dsqccvidacomercialinf: TDataSource; informedbencargado: TfrxDBDataset; informedbempresa: TfrxDBDataset; informedb: TfrxDBDataset; frxPDFExport1: TfrxPDFExport; informes: TfrxReport; qcc_vidacomercialinf: TZQuery; qcampanyasid: TIntegerField; qcampanyasidempresa: TIntegerField; qcampanyasid_anterior: TIntegerField; qcampanyasdescripcion: TWideStringField; qcampanyasfechainicio: TDateField; qcampanyasfechafin: TDateField; qcampanyasult_pesada: TIntegerField; qcontroladoreside: TIntegerField; qcontroladoresid: TSmallintField; qcontroladoresnombre: TWideStringField; qcontroladoresfirma: TBlobField; qcc_vidacomercialide: TIntegerField; qcc_vidacomerciallote: TIntegerField; qcc_vidacomercialidenvase: TWideStringField; qcc_vidacomercialidformato: TIntegerField; qcc_vidacomercialalbaran: TWideStringField; qcc_vidacomercialfecha: TDateField; qcc_vidacomercialcliente: TWideStringField; qcc_vidacomercialdescenvase: TWideStringField; qcc_vidacomercialdescformato: TWideStringField; qcc_vidacomercialproducto: TWideStringField; qcc_vidacomercialdia_1: TWideStringField; qcc_vidacomercialdia_2: TWideStringField; qcc_vidacomercialdia_3: TWideStringField; qcc_vidacomercialdia_4: TWideStringField; qcc_vidacomercialdia_5: TWideStringField; qcc_vidacomercialdia_6: TWideStringField; qcc_vidacomercialdia_7: TWideStringField; qalbaran: TZQuery; qalbaranidalbaran: TWideStringField; qalbarannomcliente: TWideStringField; qlotesid_envase: TWideStringField; qlotesdesc_envase: TWideStringField; qlotesid_formato: TIntegerField; qlotesdesc_formato: TWideStringField; qlotesfecha: TDateField; qlotesidempresa: TIntegerField; qlotesmprima: TWideStringField; qloteslote: TIntegerField; qcc_vidacomercialinfide: TIntegerField; qcc_vidacomercialinflote: TIntegerField; qcc_vidacomercialinfidenvase: TWideStringField; qcc_vidacomercialinfidformato: TIntegerField; qcc_vidacomercialinffecha: TDateField; qcc_vidacomercialinfalbaran: TWideStringField; qcc_vidacomercialinfcliente: TWideStringField; qcc_vidacomercialinfdescenvase: TWideStringField; qcc_vidacomercialinfdescformato: TWideStringField; qcc_vidacomercialinfproducto: TWideStringField; qcc_vidacomercialinfdia_1: TWideStringField; qcc_vidacomercialinfdia_2: TWideStringField; qcc_vidacomercialinfdia_3: TWideStringField; qcc_vidacomercialinfdia_4: TWideStringField; qcc_vidacomercialinfdia_5: TWideStringField; qcc_vidacomercialinfdia_6: TWideStringField; qcc_vidacomercialinfdia_7: TWideStringField; procedure FormShow(Sender: TObject); procedure dsqcampanyasDataChange(Sender: TObject; Field: TField); procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure bteimprimirClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var cc_vidacomercial: Tcc_vidacomercial; const rojo=$00AAAAFF; amarillo=$00B9FFFF; verde=$00C7FBAA; azul=$00FFFFBB; implementation {$R *.dfm} procedure Tcc_vidacomercial.bteimprimirClick(Sender: TObject); begin qcc_vidacomercialinf.SQL.Clear; qcc_vidacomercialinf.SQL.Add('select * from ('+qcc_vidacomercial.sql.text+') as vidacomercial where dia_7 is not null order by fecha'); qcc_vidacomercialinf.Open; informedb.Datasource:=dsqccvidacomercialinf; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\infccvidacomercial.fr3'); informes.Variables.Variables['CAMPANYA']:=QUOTEDSTR(qcampanyasdescripcion.asstring); informes.ShowReport(); end; procedure Tcc_vidacomercial.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if (qcc_vidacomercialdia_7.AsString='') then begin DBGrid1.Canvas.brush.Color := rojo; end else DBGrid1.Canvas.brush.Color := verde; DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure Tcc_vidacomercial.dsqcampanyasDataChange(Sender: TObject; Field: TField); var anyo,mes,dia:word; vanyo,vmes,vdia,vmessig,vfechainicio,vfechafin,variedades:string; begin decodedate(qcampanyasfechainicio.AsDateTime,anyo,mes,dia); vanyo:=floattostr(anyo); vmes:=floattostr(mes); vdia:=floattostr(dia); vfechainicio:=''''+vanyo+'-'+vmes+'-'+vdia+''''; decodedate(qcampanyasfechafin.AsDateTime,anyo,mes,dia); vanyo:=floattostr(anyo); vmes:=floattostr(mes); vdia:=floattostr(dia); vfechafin:=''''+vanyo+'-'+vmes+'-'+vdia+''''; qlotes.SQL.Clear; // qlotes.SQL.Add('select distinct(lp.lote),ide,lp.id_envase,lp.desc_envase,id_formato,lp.desc_formato,ea.fecha,ea.idalbaran,al.nomcliente,ea.mprima from lotes_pesadas lp,ea_pesadas ea,albaranes al where lp.idea2=0'); // qlotes.SQL.Add(' and lp.mprima not in (select id from materias_primas where desechos=1) and ea.fecha>='+vfechainicio+' and ea.fecha<='+vfechafin+' and lp.lote=ea.lote and lp.ide=ea.idempresa and ea.idalbaran in (select concat(serie,'+''''+'/'+''''+',id) from albaranes) and ea.idempresa=al.idempresa and ea.idalbaran=concat(al.serie,'+''''+'/'+''''+',al.id)'); // qlotes.SQL.Add(' and (lp.lote,ide,lp.id_envase,lp.id_formato,ea.fechaaran) not in (select ide,lote,idenvase,idformato,albaran from cc_vidacomercial) order by lp.lote desc'); // qlotes.Open; qlotes.SQL.Add('select distinct(lp.id_envase),lp.desc_envase,lp.id_formato,lp.desc_formato,ea.fecha,ea.idempresa,lp.mprima,lp.lote from ea_pesadas ea,lotes_pesadas lp,albaranes al where ea.idea=0 and'); qlotes.SQL.Add(' ea.mprima not in (select id from materias_primas where desechos=1 or compuesto=1) and ea.fecha>='+vfechainicio+' and ea.fecha<='+vfechafin+' and lp.idea=ea.id and lp.idea2=ea.idea and lp.ide=ea.idempresa and '); qlotes.SQL.Add(' ea.idalbaran in (select concat(serie,'+''''+'/'+''''+',id) from albaranes) and ea.idempresa=al.idempresa and ea.idalbaran=concat(al.serie,'+''''+'/'+''''+',al.id) and'); qlotes.SQL.Add(' (lp.lote,lp.ide,lp.id_envase,lp.id_formato,ea.fecha) not in (select lote,ide,idenvase,idformato,fecha from cc_vidacomercial) order by ea.fecha,lp.id_envase,lp.id_formato,lp.lote'); qlotes.Open; qcc_vidacomercial.SQL.Clear; qcc_vidacomercial.SQL.Add('select * from cc_vidacomercial where fecha>='+vfechainicio+' and fecha<='+vfechafin+' order by lote desc'); qcc_vidacomercial.Open; qalbaran.prepare; if qlotes.RecordCount>0 then begin while not qlotes.Eof do begin qalbaran.Close; qalbaran.ParamByName('FECHA').AsDate:=qlotesfecha.AsDatetime; qalbaran.ParamByName('PRODUCTO').Asstring:=qlotesmprima.Asstring; qalbaran.ParamByName('LOTE').Asinteger:=qloteslote.Asinteger; qalbaran.ParamByName('EMPRESA').Asinteger:=qlotesidempresa.Asinteger; qalbaran.ParamByName('ENVASE').Asstring:=qlotesid_envase.Asstring; qalbaran.ParamByName('FORMATO').Asinteger:=qlotesid_formato.Asinteger; qalbaran.Open; qcc_vidacomercial.Append; qcc_vidacomercialide.value:=qlotesidempresa.AsInteger; qcc_vidacomerciallote.value:=qloteslote.Asinteger; qcc_vidacomercialidenvase.value:=qlotesid_envase.Asstring; qcc_vidacomercialfecha.value:=qlotesfecha.Asdatetime; qcc_vidacomercialdescenvase.value:=qlotesdesc_envase.Asstring; qcc_vidacomercialidformato.value:=qlotesid_formato.Asinteger; qcc_vidacomercialdescformato.value:=qlotesdesc_formato.Asstring; qcc_vidacomercialalbaran.value:=qalbaranidalbaran.Asstring; qcc_vidacomercialcliente.value:=qalbarannomcliente.Asstring; qcc_vidacomercialproducto.value:=qlotesmprima.Asstring; qcc_vidacomercialdia_1.value:='C'; qcc_vidacomercialdia_2.value:='C'; qcc_vidacomercialdia_3.value:='C'; qcc_vidacomercialdia_4.value:='C'; qcc_vidacomercialdia_5.value:='C'; qcc_vidacomercialdia_6.Value:='C'; qcc_vidacomercial.Post; qlotes.Next; end; end; end; procedure Tcc_vidacomercial.FormShow(Sender: TObject); begin qcampanyas.Open; qcontroladores.Open; qlotes.Open; combocampanyas.Keyvalue:=qcampanyasid.asstring; comboencargado.Keyvalue:=qcontroladoresnombre.asstring; end; end. ======================================== FICHERO: fclientes.pas ======================================== unit fclientes; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,principal,datosclientes, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.Mask, Vcl.DBCtrls,Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, Vcl.CheckLst; type Tclientes = class(TForm) Panel1: TPanel; Panel2: TPanel; Panel5: TPanel; DBGrid1: TDBGrid; todosclientes: TCheckBox; tbuscar: TEdit; Label1: TLabel; dsqformaspago: TDataSource; qformaspago: TZQuery; qformaspagoide: TIntegerField; qformaspagoid: TIntegerField; qformaspagocodigo: TWideStringField; qformaspagodescripcion: TWideStringField; qformaspagodias: TIntegerField; qaux: TZReadOnlyQuery; SaveDialog1: TSaveDialog; dsqfacturasclientes: TDataSource; qfacturasclientes: TZReadOnlyQuery; qfacturasclientesserie: TWideStringField; qfacturasclientesid: TIntegerField; qfacturasclientesidempresa: TIntegerField; qfacturasclientesidcliente: TIntegerField; qfacturasclientesiddestino: TWideStringField; qfacturasclientesnif: TWideStringField; qfacturasclientesdireccion: TWideStringField; qfacturasclientespoblacion: TWideStringField; qfacturasclientesprovincia: TWideStringField; qfacturasclientescodpost: TWideStringField; qfacturasclientesfecha: TDateField; qfacturasclientesreferencia: TWideStringField; qfacturasclientestelefono: TWideStringField; qfacturasclientesnomcliente: TWideStringField; qfacturasclientespaiscliente: TWideStringField; qfacturasclientesnomdestino: TWideStringField; qfacturasclientesdirecciondestino: TWideStringField; qfacturasclientespoblaciondestino: TWideStringField; qfacturasclientescodpostdestino: TWideStringField; qfacturasclientesprovinciadestino: TWideStringField; qfacturasclientespaisdestino: TWideStringField; qfacturasclientesneto: TFloatField; qfacturasclientestotal: TFloatField; qfacturasclientesdocumento: TWideStringField; qfacturasclientesdescuento_lin: TFloatField; qfacturasclientesdescuento_com: TFloatField; qfacturasclientesdescuento_pp: TFloatField; qfacturasclientesdescuento_total: TFloatField; qfacturasclientestotaliva: TFloatField; qfacturasclientesobservaciones: TWideStringField; qfacturasclientesbultos: TFloatField; qfacturasclienteskilos: TFloatField; qfacturasclientesidformapago: TIntegerField; qfacturasclientesserie_1: TWideStringField; qfacturasclientesidfactura: TIntegerField; qfacturasclienteside: TIntegerField; qfacturasclientesbase: TFloatField; qfacturasclientestipo: TFloatField; qfacturasclientesiva: TFloatField; qfacturasclientescobrado: TIntegerField; qcuentas: TZReadOnlyQuery; qcuentaside: TIntegerField; qcuentasid: TIntegerField; qcuentasbanco: TWideStringField; qcuentascciban: TWideStringField; qcuentasccentidad: TWideStringField; qcuentasccoficina: TWideStringField; qcuentasccdc: TWideStringField; qcuentascccc: TWideStringField; dsqcuentas: TDataSource; dsqtiposiva: TDataSource; qtipos_iva: TZReadOnlyQuery; qtipos_ivaid: TIntegerField; qtipos_ivadescripcion: TWideStringField; qtipos_ivatipo: TIntegerField; qtipos_ivatipo_req: TFloatField; qclientesexcel: TZReadOnlyQuery; qclientesexcelid: TIntegerField; qclientesexcelIdempresa: TIntegerField; qclientesexcelnif: TWideStringField; qclientesexcelnombre: TWideStringField; qclientesexcelnombre_corto: TWideStringField; qclientesexceldireccion: TWideStringField; qclientesexcelpoblacion: TWideStringField; qclientesexcelcodpost: TWideStringField; qclientesexcelprovincia: TWideStringField; qclientesexceltelefono: TWideStringField; qclientesexceltelefono2: TWideStringField; qclientesexcelmovil: TWideStringField; qclientesexcelemail: TWideStringField; qclientesexcelpersonacontacto: TWideStringField; qclientesexcelcodigomercado: TIntegerField; qclientesexcelactivo: TIntegerField; qclientesexcelobservaciones: TWideStringField; qclientesexcelccontable: TIntegerField; qclientesexceldescuento: TFloatField; qclientesexcelpais: TWideStringField; qclientesexcelidformapago: TIntegerField; qclientesexcelexento_iva: TIntegerField; qclientesexcelcomision: TFloatField; qclientesexcelidcp: TIntegerField; qclientesexcelcodigo: TWideStringField; qclientesexcelidcliente: TIntegerField; qclientesexcelidempresa_1: TIntegerField; qclientesexceldescripcion: TWideStringField; qclientesexcelseleccionado: TIntegerField; qclientesexcelactivo_1: TIntegerField; qclientesexceldireccion_1: TWideStringField; qclientesexcelpoblacion_1: TWideStringField; qclientesexcelcodpost_1: TWideStringField; qclientesexcelprovincia_1: TWideStringField; qclientesexcelpais_1: TWideStringField; dsqclientesexcel: TDataSource; Panel3: TPanel; DatosClientes: TPageControl; TDatosClientes: TTabSheet; Panel14: TPanel; Label10: TLabel; Label11: TLabel; Label12: TLabel; Label13: TLabel; Label14: TLabel; Label15: TLabel; Label2: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; Label22: TLabel; Label23: TLabel; Label25: TLabel; Label27: TLabel; Label28: TLabel; Label38: TLabel; DBText1: TDBText; DBText2: TDBText; DBText16: TDBText; DBText17: TDBText; DBText18: TDBText; Label33: TLabel; Label39: TLabel; DBCheckBox2: TDBCheckBox; DBEdit1: TDBEdit; DBEdit10: TDBEdit; DBEdit11: TDBEdit; DBEdit12: TDBEdit; DBEdit13: TDBEdit; DBEdit3: TDBEdit; DBEdit4: TDBEdit; DBEdit5: TDBEdit; DBEdit6: TDBEdit; DBEdit7: TDBEdit; DBEdit8: TDBEdit; DBEdit9: TDBEdit; DBMemo1: TDBMemo; DBEdit21: TDBEdit; DBEdit22: TDBEdit; DBEdit23: TDBEdit; comboformapago: TDBLookupComboBox; DBEdit25: TDBEdit; combocuenta: TDBLookupComboBox; DBLookupComboBox1: TDBLookupComboBox; gridclientesexcel: TDBGrid; listadatos: TCheckListBox; DBEdit26: TDBEdit; Panel6: TPanel; Label37: TLabel; BtCcancelar: TButton; btCmodificar: TButton; BtCborrar: TButton; BtCNuevo: TButton; BtCguardar: TButton; Button2: TButton; TDatosDestinos: TTabSheet; Panel12: TPanel; Label36: TLabel; btDcancelar: TButton; btDmodificar: TButton; btDborrar: TButton; btDnuevo: TButton; btDguardar: TButton; Panel15: TPanel; Panel18: TPanel; DBGrid4: TDBGrid; Panel20: TPanel; todosdestinos: TCheckBox; Panel19: TPanel; Label16: TLabel; Label17: TLabel; Label19: TLabel; Label21: TLabel; Label29: TLabel; Label30: TLabel; Label26: TLabel; DBCheckBox4: TDBCheckBox; DBEdit14: TDBEdit; DBEdit15: TDBEdit; DBEdit16: TDBEdit; DBEdit17: TDBEdit; DBEdit18: TDBEdit; DBEdit20: TDBEdit; DBEdit24: TDBEdit; TDatosArticulos: TTabSheet; Panel7: TPanel; Panel17: TPanel; Panel22: TPanel; Panel23: TPanel; DBGrid2: TDBGrid; Panel24: TPanel; Label18: TLabel; btADcancelar: TButton; btADmodificar: TButton; btADborrar: TButton; btADnuevo: TButton; btADguardar: TButton; TabSheet1: TTabSheet; Detallesclientes: TPageControl; TabPedidos: TTabSheet; Panel8: TPanel; Label34: TLabel; DBGrid5: TDBGrid; TAbalbaranes: TTabSheet; Panel10: TPanel; Label32: TLabel; Button8: TButton; DBGrid7: TDBGrid; gridalbaranesaexcel: TDBGrid; TabFacturas: TTabSheet; Panel11: TPanel; Label31: TLabel; Button1: TButton; DBGrid8: TDBGrid; gridfacturasaexcel: TDBGrid; Panel4: TPanel; Label35: TLabel; btAcancelar: TButton; btAguardar: TButton; btAmodificar: TButton; btAborrar: TButton; btAnuevo: TButton; Panel9: TPanel; Label3: TLabel; btClcancelar: TButton; btClguardar: TButton; btClmodificar: TButton; btClborrar: TButton; btClnuevo: TButton; Panel16: TPanel; DBGrid9: TDBGrid; Panel21: TPanel; Label20: TLabel; btCAcancelar: TButton; btCAmodificar: TButton; btCAborrar: TButton; btCAnuevo: TButton; btCAguardar: TButton; Panel25: TPanel; DBGrid6: TDBGrid; Panel26: TPanel; DBGrid3: TDBGrid; DBCheckBox1: TDBCheckBox; Label24: TLabel; DBLookupComboBox2: TDBLookupComboBox; Label40: TLabel; DBEdit2: TDBEdit; Label41: TLabel; DBEdit19: TDBEdit; Label42: TLabel; DBEdit27: TDBEdit; Label43: TLabel; DBEdit28: TDBEdit; Label44: TLabel; DBEdit29: TDBEdit; procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure BtCguardarClick(Sender: TObject); procedure BtCcancelarClick(Sender: TObject); procedure BtCNuevoClick(Sender: TObject); procedure btCmodificarClick(Sender: TObject); procedure todosclientesClick(Sender: TObject); procedure BtCborrarClick(Sender: TObject); procedure btDnuevoClick(Sender: TObject); procedure btDborrarClick(Sender: TObject); procedure btDmodificarClick(Sender: TObject); procedure btDguardarClick(Sender: TObject); procedure btDcancelarClick(Sender: TObject); procedure todosdestinosClick(Sender: TObject); procedure todosarticulosClick(Sender: TObject); procedure btAnuevoClick(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure btAmodificarClick(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DBEdit19Exit(Sender: TObject); procedure btADcancelarClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); procedure tbuscarChange(Sender: TObject); procedure btADmodificarClick(Sender: TObject); procedure btADguardarClick(Sender: TObject); procedure btADborrarClick(Sender: TObject); procedure btADnuevoClick(Sender: TObject); procedure DBGrid5DblClick(Sender: TObject); procedure DBGrid5TitleClick(Column: TColumn); procedure DBGrid7TitleClick(Column: TColumn); procedure DBGrid7DblClick(Sender: TObject); procedure DBGrid8DblClick(Sender: TObject); procedure DBGrid8TitleClick(Column: TColumn); procedure DBGrid1TitleClick(Column: TColumn); procedure Button1Click(Sender: TObject); procedure Button8Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure DBEdit26Enter(Sender: TObject); procedure listadatosClick(Sender: TObject); procedure listadatosExit(Sender: TObject); procedure btClnuevoClick(Sender: TObject); procedure btClborrarClick(Sender: TObject); procedure btClmodificarClick(Sender: TObject); procedure btClguardarClick(Sender: TObject); procedure btClcancelarClick(Sender: TObject); procedure btCAnuevoClick(Sender: TObject); procedure btCAborrarClick(Sender: TObject); procedure btCAmodificarClick(Sender: TObject); procedure btCAcancelarClick(Sender: TObject); procedure btCAguardarClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var clientes: Tclientes; implementation {$R *.dfm} uses fpedidos, falbaranes, ffacturas, datos; procedure Tclientes.btAborrarClick(Sender: TObject); begin dmclientes.qarticulos.delete; end; procedure Tclientes.btAcancelarClick(Sender: TObject); begin dmclientes.qarticulos.Cancel; Panel25.Enabled:=false; end; procedure Tclientes.btADborrarClick(Sender: TObject); begin dmclientes.dtarticulosformato.delete; end; procedure Tclientes.btADcancelarClick(Sender: TObject); begin dmclientes.dtarticulosformato.Cancel; dmclientes.dtarticulosformato.MasterSource:=dmclientes.dsqclientes; end; procedure Tclientes.btADguardarClick(Sender: TObject); var id,ide,idcliente:string; begin id:=dmclientes.dtarticulosformatoid.AsString; ide:=dmclientes.dtarticulosformatoidempresa.AsString; idcliente:=dmclientes.dtarticulosformatoidcliente.AsString; dmclientes.dtarticulosformato.Post; dmclientes.dtarticulosformato.MasterSource:=dmclientes.dsqclientes; dmclientes.dtarticulosformato.Refresh; dmclientes.dtarticulosformato.Locate('idempresa,id,idcliente',vararrayof([ide,id,idcliente]),[locaseinsensitive]); end; procedure Tclientes.btADmodificarClick(Sender: TObject); begin // dmclientes.dtarticulosformato.MasterSource:=nil; dmclientes.dtarticulosformato.edit; dbgrid2.SetFocus; end; procedure Tclientes.btADnuevoClick(Sender: TObject); begin qaux.SQL.Clear; qaux.SQL.Add('select count(*)+1 from clientes_formatoarticulos'); qaux.Open; dmclientes.dtarticulosformato.append; dmclientes.dtarticulosformatoid.value:=qaux.Fields[0].AsString; dmclientes.dtarticulosformatoidempresa.value:=dmclientes.qclientesIdempresa.AsInteger; dmclientes.dtarticulosformatoidcliente.value:=dmclientes.qclientesId.AsInteger; dbgrid2.SetFocus; end; procedure Tclientes.btAguardarClick(Sender: TObject); var id,ide,idcliente:string; begin dmclientes.qarticulos.Post; id:=dmclientes.qarticulosid.AsString; ide:=dmclientes.qarticulosidempresa.AsString; idcliente:=dmclientes.qarticulosidcliente.AsString; dmclientes.qarticulos.MasterSource:=dmclientes.dsqclientes; dmclientes.qarticulos.refresh; dmclientes.qarticulos.Locate('idempresa,id,idcliente',vararrayof([ide,id,idcliente]),[locaseinsensitive]); Panel25.Enabled:=false; end; procedure Tclientes.btAmodificarClick(Sender: TObject); begin // dmclientes.dtarticulos.MasterSource:=nil; clientes.Panel25.Enabled:=false; dmclientes.qarticulos.edit; end; procedure Tclientes.btAnuevoClick(Sender: TObject); begin // dmclientes.qarticulosx.MasterSource:=nil; clientes.Panel25.Enabled:=true; qaux.SQL.Clear; qaux.SQL.Add('select count(*)+1 from clientes_articulos'); qaux.Open; dmclientes.qarticulos.append; dmclientes.qarticulosid.value:=qaux.Fields[0].AsString; dmclientes.qarticulosidempresa.value:=dmclientes.qclientesIdempresa.AsInteger; dmclientes.qarticulosidcliente.value:=dmclientes.qclientesId.AsInteger; dbgrid6.SetFocus; end; procedure Tclientes.btCAborrarClick(Sender: TObject); begin dmclientes.qclientesacabados.delete; end; procedure Tclientes.btCAcancelarClick(Sender: TObject); begin dmclientes.qclientesacabados.Cancel; end; procedure Tclientes.btCAguardarClick(Sender: TObject); var id,ide,idcliente:string; begin id:=dmclientes.qclientesacabadosid.AsString; ide:=dmclientes.qclientesacabadosidempresa.AsString; idcliente:=dmclientes.qclientesacabadosidcliente.AsString; dmclientes.qclientesacabados.Post; dmclientes.qclientesacabados.MasterSource:=dmclientes.dsqclientes; dmclientes.qclientesacabados.Refresh; dmclientes.qclientesacabados.Locate('idempresa,id,idcliente',vararrayof([ide,id,idcliente]),[locaseinsensitive]); end; procedure Tclientes.btCAmodificarClick(Sender: TObject); begin dmclientes.qclientesacabados.Edit; dbgrid9.SetFocus; end; procedure Tclientes.btCAnuevoClick(Sender: TObject); begin qaux.SQL.Clear; qaux.SQL.Add('select count(*)+1 from clientes_acabados'); qaux.Open; dmclientes.qclientesacabados.append; dmclientes.qclientesacabadosid.value:=qaux.Fields[0].AsString; dmclientes.qclientesacabadosidempresa.value:=dmclientes.qclientesIdempresa.AsInteger; dmclientes.qclientesacabadosidcliente.value:=dmclientes.qclientesId.AsInteger; dbgrid9.SetFocus; end; procedure Tclientes.BtCborrarClick(Sender: TObject); begin dmclientes.dtclientes.delete; end; procedure Tclientes.BtCcancelarClick(Sender: TObject); begin dmclientes.dtclientes.cancel; dmclientes.dtclientes.MasterSource:=dmclientes.dsqclientes; end; procedure Tclientes.BtCguardarClick(Sender: TObject); begin dmclientes.dtclientesactivo.value:=1; dmclientes.dtclientes.Post; dmclientes.qclientes.Refresh; dmclientes.dtclientes.MasterSource:=dmclientes.dsqclientes; end; procedure Tclientes.btClborrarClick(Sender: TObject); begin dmclientes.qclientescalidad.delete; end; procedure Tclientes.btClcancelarClick(Sender: TObject); begin dmclientes.qclientescalidad.Cancel; end; procedure Tclientes.btClguardarClick(Sender: TObject); var id,ide,idcliente:string; begin id:=dmclientes.qclientescalidadid.AsString; ide:=dmclientes.qclientescalidadidempresa.AsString; idcliente:=dmclientes.qclientescalidadidcliente.AsString; dmclientes.qclientescalidad.Post; dmclientes.qclientescalidad.MasterSource:=dmclientes.dsqclientes; dmclientes.qclientescalidad.refresh; dmclientes.qclientescalidad.Locate('idempresa,id,idcliente',vararrayof([ide,id,idcliente]),[locaseinsensitive]); end; procedure Tclientes.btClmodificarClick(Sender: TObject); begin // dmclientes.qclientescalidad.MasterSource:=nil; dmclientes.qclientescalidad.edit; end; procedure Tclientes.btClnuevoClick(Sender: TObject); begin dmclientes.qclientescalidad.MasterSource:=nil; qaux.SQL.Clear; qaux.SQL.Add('select count(*)+1 from clientes_calidad'); qaux.Open; dmclientes.qclientescalidad.append; dmclientes.qclientescalidadid.value:=qaux.Fields[0].AsString; dmclientes.qclientescalidadidempresa.value:=dmclientes.qclientesIdempresa.AsInteger; dmclientes.qclientescalidadidcliente.value:=dmclientes.qclientesId.AsInteger; dbgrid3.SetFocus; end; procedure Tclientes.btCmodificarClick(Sender: TObject); begin dmclientes.dtclientes.MasterSource:=nil; dmclientes.dtclientes.edit; dbedit1.SetFocus; end; procedure Tclientes.BtCNuevoClick(Sender: TObject); begin qaux.close; qaux.sql.clear; qaux.sql.add('select max(id+1) from clientes '); qaux.Open; dmclientes.dtclientes.MasterSource:=nil; dmclientes.dtclientes.append; dmclientes.dtclientesid.Value:=qaux.Fields[0].AsInteger; dbedit1.SetFocus; end; procedure Tclientes.btDcancelarClick(Sender: TObject); begin dmclientes.dtdestinos.cancel; end; procedure Tclientes.btDmodificarClick(Sender: TObject); begin dmclientes.dtdestinos.MasterSource:=nil; dmclientes.dtdestinos.edit; dbedit15.SetFocus; end; procedure Tclientes.btDborrarClick(Sender: TObject); begin dmclientes.dtdestinos.delete; dmclientes.qdestinos.Refresh; end; procedure Tclientes.btDnuevoClick(Sender: TObject); begin dmclientes.dtdestinos.MasterSource:=nil; dmclientes.dtdestinos.append; dbedit15.SetFocus; end; procedure Tclientes.Button1Click(Sender: TObject); var archivo:string; begin qfacturasclientes.Close; qfacturasclientes.SQL.Clear; qfacturasclientes.SQL.Add('select * from facturas f,facturas_iva fi where f.idcliente='+dmclientes.dtclientesid.asstring+' and f.idempresa='+dmclientes.dtclientesidempresa.asstring+' and f.idempresa=fi.ide and f.serie=fi.serie and f.id=fi.idfactura order by f.serie,fecha desc,f.id desc'); qfacturasclientes.open; savedialog1.FileName:='FACTURAS CLIENTES.xls'; savedialog1.Execute(); archivo:=savedialog1.FileName; try base.Exportaraexcel(archivo,'facturas',gridfacturasaexcel); finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure Tclientes.Button2Click(Sender: TObject); var archivo:string; begin qclientesexcel.Close; qclientesexcel.open; savedialog1.FileName:='CLIENTES.xls'; savedialog1.Execute(); archivo:=savedialog1.FileName; try base.Exportaraexcel(archivo,'clientes',gridclientesexcel); finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure Tclientes.Button8Click(Sender: TObject); var archivo:string; begin savedialog1.FileName:='ALBARANES CLIENTES.xls'; savedialog1.Execute(); archivo:=savedialog1.FileName; try base.Exportaraexcel(archivo,'ALBARANES',gridalbaranesaexcel); finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure Tclientes.DBEdit19Exit(Sender: TObject); begin if dmclientes.dsarticulos.State in [dsedit,dsinsert] then btAguardar.Click; end; procedure Tclientes.DBEdit26Enter(Sender: TObject); var x,y:integer; tipo,tipocli:string; begin tipo:=''; tipocli:=dmclientes.dtclientestipocliente.AsString; if length(tipocli)>0 then begin for x := 1 to length(tipocli) do begin if tipocli[x]<>',' then begin tipo:=tipo+tipocli[x]; end; if (tipocli[x]=',') or (x=length(tipocli)) then begin for y := 0 to listadatos.Items.Count-1 do begin if listadatos.Items[y]=tipo then listadatos.Checked[y]:=true; end; tipo:=''; end; end; end; listadatos.Visible:=true; end; procedure Tclientes.DBGrid1TitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=dmclientes.qclientes.SortType; dmclientes.qclientes.SortedFields:=Column.FieldName; If st = stAscending then dmclientes.qclientes.SortType:=stDescending else dmclientes.qclientes.SortType:=stAscending; dmclientes.dsqclientes.DataSet.First; end; procedure Tclientes.DBGrid5DblClick(Sender: TObject); begin pedidos.showmodal(); end; procedure Tclientes.DBGrid5TitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=dmclientes.qpedidos.SortType; dmclientes.qpedidos.SortedFields:=Column.FieldName; If st = stAscending then dmclientes.qpedidos.SortType:=stDescending else dmclientes.qpedidos.SortType:=stAscending; dmclientes.dsqpedidos.DataSet.First; end; procedure Tclientes.DBGrid7DblClick(Sender: TObject); var tserie,tid,tidempresa,tidcliente:string; begin tserie:=dmclientes.qalbaranesserie.AsString; tid:=dmclientes.qalbaranesid.AsString; tidempresa:=dmclientes.qalbaranesidempresa.AsString; tidcliente:=dmclientes.qalbaranesidcliente.AsString; albaranes := Talbaranes.Create(nil); try albaranes.albaranes.filter:='id='+tid+'and idempresa='+tidempresa+' and idcliente='+tidcliente+' and serie='+''''+tserie+''''; albaranes.albaranes.filtered:=true; albaranes.showmodal(); finally albaranes.albaranes.filtered:=false; albaranes.Free; end; end; procedure Tclientes.DBGrid7TitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=dmclientes.qalbaranes.SortType; dmclientes.qalbaranes.SortedFields:=Column.FieldName; If st = stAscending then dmclientes.qalbaranes.SortType:=stDescending else dmclientes.qalbaranes.SortType:=stAscending; dmclientes.dsqalbaranes.DataSet.First; end; procedure Tclientes.DBGrid8DblClick(Sender: TObject); var tserie,tid,tidempresa,tidcliente:string; begin tserie:=dmclientes.qfacturasserie.AsString; tid:=dmclientes.qfacturasid.AsString; tidempresa:=dmclientes.qfacturasidempresa.AsString; tidcliente:=dmclientes.qfacturasidcliente.AsString; facturas := Tfacturas.Create(nil); try facturas.facturas.filter:='id='+tid+'and idempresa='+tidempresa+' and idcliente='+tidcliente+' and serie='+''''+tserie+''''; facturas.facturas.filtered:=true; facturas.showmodal(); finally facturas.facturas.filtered:=false; facturas.facturas.Filter:=''; facturas.Free; end; end; procedure Tclientes.DBGrid8TitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=dmclientes.qfacturas.SortType; dmclientes.qfacturas.SortedFields:=Column.FieldName; If st = stAscending then dmclientes.qfacturas.SortType:=stDescending else dmclientes.qfacturas.SortType:=stAscending; dmclientes.dsqfacturas.DataSet.First; end; procedure Tclientes.todosdestinosClick(Sender: TObject); begin if todosdestinos.Checked=true then begin dmclientes.qdestinos.Close; dmclientes.qdestinos.SQL.Clear; dmclientes.qdestinos.SQL.add('select * from clientes_destinos order by descripcion asc'); dmclientes.qdestinos.Open; end else begin dmclientes.qdestinos.Close; dmclientes.qdestinos.SQL.Clear; dmclientes.qdestinos.SQL.add('select * from clientes_destinos where activo=1 order by descripcion asc'); dmclientes.qdestinos.Open; end; end; procedure Tclientes.btDguardarClick(Sender: TObject); begin dmclientes.dtdestinosidcliente.Value:=dmclientes.dtclientesid.AsInteger; dmclientes.dtdestinosidempresa.Value:=dmclientes.dtclientesidempresa.AsInteger; dmclientes.dtdestinos.Post; dmclientes.qdestinos.close; dmclientes.qdestinos.Open; dmclientes.dtdestinos.MasterSource:=dmclientes.dsqdestinos; end; procedure Tclientes.FormClose(Sender: TObject; var Action: TCloseAction); begin dmclientes.qclientes.close; end; procedure Tclientes.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tclientes.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is tdbgrid) then begin key:=','; end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tclientes.FormShow(Sender: TObject); begin detallesclientes.ActivePageIndex:=0; datosclientes.activepageindex:=0; dm.tempresa.open; dmclientes.qclientes.close; dmclientes.qpedidosclientes.Close; dmclientes.qalbaranes.close; dmclientes.qfacturas.close; dmclientes.qarticulosx.Close; dmclientes.qarticulos.Close; dmclientes.qclientescalidad.Close; dmclientes.dtarticulosformato.Close; dmclientes.qclientesacabados.close; dmclientes.qdestinos.Close; dmclientes.dtdestinos.Close; qformaspago.Close; qcuentas.close; qtipos_iva.close; qformaspago.Open; qcuentas.Open; qtipos_iva.open; dmclientes.qarticulosx.open; dmclientes.qarticulos.open; dmclientes.qclientes.Open; dmclientes.dtclientes.Open; if dmclientes.qclientes.RecordCount>0 then begin dmclientes.qdestinos.open; dmclientes.qclientescalidad.open; dmclientes.dtarticulosformato.open; dmclientes.qclientesacabados.open; dmclientes.dtdestinos.open; dmclientes.qalbaranes.Open; dmclientes.qfacturas.open; end; end; procedure Tclientes.listadatosClick(Sender: TObject); var tipocli:string; x:integer; begin for x:=0 to listadatos.Items.Count-1 do begin if listadatos.Checked[x] then if tipocli='' then tipocli:=listadatos.Items[x] else tipocli:=tipocli+','+listadatos.Items[x]; end; dmclientes.dtclientestipocliente.Value:=tipocli; end; procedure Tclientes.listadatosExit(Sender: TObject); begin listadatos.Visible:=false; dbedit9.SetFocus; end; procedure Tclientes.tbuscarChange(Sender: TObject); begin dmclientes.filtro:='%'+tbuscar.Text+'%'; if todosclientes.Checked then dmclientes.vertodos:=1 else dmclientes.vertodos:=0; dmclientes.qclientes.Close; dmclientes.qclientes.open; end; procedure Tclientes.todosarticulosClick(Sender: TObject); begin dmclientes.qarticulos.Close; dmclientes.qarticulos.SQL.Clear; dmclientes.qarticulos.SQL.add('select * from clientes_articulos order by desc_cliente asc'); dmclientes.qarticulos.Open; end; procedure Tclientes.todosclientesClick(Sender: TObject); begin if todosclientes.Checked=true then begin dmclientes.vertodos:=1; dmclientes.qclientes.Close; dmclientes.qclientes.SQL.Clear; dmclientes.qclientes.SQL.add('select * from clientes order by nombre asc'); dmclientes.qclientes.Open; end else begin dmclientes.vertodos:=0; dmclientes.qclientes.Close; dmclientes.qclientes.SQL.Clear; dmclientes.qclientes.SQL.add('select * from clientes where activo=1 order by nombre asc'); dmclientes.qclientes.Open; end; end; end. ======================================== FICHERO: fconfiguracionalmacen.pas ======================================== unit fconfiguracionalmacen; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.DBCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.ExtCtrls, Data.DB, ZAbstractDataset, ZDataset, ZAbstractRODataset; type Tconfiguracionalmacen = class(TForm) Panel1: TPanel; Panel9: TPanel; btscancelar: TButton; btsmodificar: TButton; btsborrar: TButton; btsnuevo: TButton; btsguardar: TButton; listaimpresion: TComboBox; Panel2: TPanel; DBGrid1: TDBGrid; qalmacenes: TZReadOnlyQuery; qsectores: TZQuery; qalmacenesidempresa: TIntegerField; qalmacenesid: TIntegerField; qalmacenesnombre: TWideStringField; dsqalmacenes: TDataSource; qsectoreside: TIntegerField; qsectoresid: TIntegerField; qsectoresdescripcion: TWideStringField; qsectoresidalmacen: TIntegerField; dsqsectores: TDataSource; DBLookupComboBox1: TDBLookupComboBox; Panel3: TPanel; Panel4: TPanel; btpcancelar: TButton; btpmodificar: TButton; btpborrar: TButton; btpnuevo: TButton; btpguardar: TButton; ComboBox1: TComboBox; Panel5: TPanel; DBGrid2: TDBGrid; qpuestos: TZQuery; dsqpuestos: TDataSource; qaux: TZQuery; qsectoresdescalmacen: TWideStringField; DBLookupComboBox2: TDBLookupComboBox; qpuestoside: TIntegerField; qpuestosidsector: TIntegerField; qpuestosid: TIntegerField; qpuestosdescripcion: TWideStringField; qpuestosdescsector: TWideStringField; procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btsnuevoClick(Sender: TObject); procedure dsqsectoresStateChange(Sender: TObject); procedure btsmodificarClick(Sender: TObject); procedure btsguardarClick(Sender: TObject); procedure btscancelarClick(Sender: TObject); procedure btsborrarClick(Sender: TObject); procedure DBGrid1KeyPress(Sender: TObject; var Key: Char); procedure DBGrid1ColExit(Sender: TObject); procedure DBGrid2ColExit(Sender: TObject); procedure DBGrid2DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBGrid2KeyPress(Sender: TObject; var Key: Char); procedure dsqpuestosStateChange(Sender: TObject); procedure btpnuevoClick(Sender: TObject); procedure btpborrarClick(Sender: TObject); procedure btpmodificarClick(Sender: TObject); procedure btpguardarClick(Sender: TObject); procedure btpcancelarClick(Sender: TObject); procedure qpuestosAfterPost(DataSet: TDataSet); procedure qsectoresAfterPost(DataSet: TDataSet); private { Private declarations } public { Public declarations } procedure AppMessage(var Msg: Tmsg; var Handled:Boolean); end; var configuracionalmacen: Tconfiguracionalmacen; implementation {$R *.dfm} uses datos; procedure Tconfiguracionalmacen.AppMessage(var Msg: Tmsg; var Handled: Boolean); var actual : TWincontrol; begin if Msg.message = WM_KEYDOWN then begin // esto es para controlar que con la flecha abajo se desplegen las // listas if Msg.wParam = VK_DOWN then begin Actual := Screen.ActiveControl; if Actual is TDBLookupComboBox then if not TDBLookupComboBox(Screen.ActiveForm.ActiveControl).listVisible then TDBLookupComboBox(Screen.ActiveForm.ActiveControl).DropDown; // si utilizas las RX { if Actual is TRxDBLookupCombo then if not TRxDBLookupCombo(Screen.ActiveForm.ActiveControl).listVisible then TRxDBLookupCombo(Screen.ActiveForm.ActiveControl).DropDown; } if Actual is TComboBox then SendMessage(TComboBox(Screen.ActiveForm.ActiveControl).Handle,CB_SHOWDROPDOWN,-1,0); if (Actual is TCustomEdit) then Msg.wParam := VK_TAB; // se pueden añadir mas controles.... end; // y aqui es el control del intro. if Msg.wParam = VK_RETURN THEN begin Actual := Screen.ActiveControl; // para los edit. if (Actual is TCustomEdit) and not (Actual is TCustomMemo) then Msg.wParam := VK_TAB; // para los memo. Con ctrl + enter se salta de linea dentro del // memo, si solo es intro salta al siguiente control if (Actual is TCustomMemo) and (HiWord(GetKeyState(VK_CONTROL)) = 0)then Msg.wParam := VK_TAB; // para los lookup if Actual is TDBLookupComboBox then if not TDBLookupComboBox(Actual).listVisible then Msg.wParam := VK_TAB; // Si utilizas las RX { if Actual is TRxDBLookupCombo then if not TRxDBLookupCombo(Actual).listVisible then Msg.wParam := VK_TAB; } // Los combobox if Actual is TCustomComboBox then if not TCustomComboBox(Actual).DroppedDown then Msg.wParam := VK_TAB; // el radiobutton if Actual is TRadioButton then Msg.wParam := VK_TAB; // en el grid if Actual is TDBGrid then if (TDBGrid(Actual).ReadOnly) or (HiWord(GetKeyState(VK_CONTROL)) = 1)then Msg.wParam := VK_TAB; // o esto otro Con Ctrl + intro siguiente celda con // ctrl + shift + intro celda anterior // es complicado pero es por no liar con el intro solo // que siempre pasa de un control a otro. if Actual is TDBGrid then begin if (TDBGrid(Actual).ReadOnly) or (HiWord(GetKeyState(VK_CONTROL)) = 0) then Msg.wParam := VK_TAB else if not(HiWord(GetKeyState(VK_SHIFT)) = 0) then begin if TDBGrid(Actual).selectedindex > 0 then { increment the field } TDBGrid(Actual).selectedindex := TDBGrid(Actual).selectedindex -1 else TDBGrid(Actual).selectedindex := TDBGrid(Actual).fieldcount -1; end else begin if TDBGrid(Actual).selectedindex < (TDBGrid(Actual).fieldcount -1) then { increment the field } TDBGrid(Actual).selectedindex := TDBGrid(Actual).selectedindex +1 else TDBGrid(Actual).selectedindex := 0; end; end; // ListBox // if Actual is TCustomListBox then // Msg.wParam := VK_TAB; // TabControl // if Actual is TCustomTabControl then // Msg.wParam := VK_TAB; // Aqui se pondrían todos los controles que usamos en la // aplicación y necesitamos cambiar el tab por intro. // de esta forma te despreocupas de cuantos añades y es más // limpio el código end; end; end; procedure Tconfiguracionalmacen.btpborrarClick(Sender: TObject); begin qpuestos.Delete; end; procedure Tconfiguracionalmacen.btpcancelarClick(Sender: TObject); begin qpuestos.cancel; end; procedure Tconfiguracionalmacen.btpguardarClick(Sender: TObject); begin qpuestos.post; end; procedure Tconfiguracionalmacen.btpmodificarClick(Sender: TObject); begin qpuestos.edit; end; procedure Tconfiguracionalmacen.btpnuevoClick(Sender: TObject); begin qpuestos.Append; qpuestoside.Value:=dm.tempresaid.AsInteger; dbgrid2.ReadOnly:=false; dbgrid2.SetFocus; end; procedure Tconfiguracionalmacen.btsborrarClick(Sender: TObject); begin qsectores.Delete; end; procedure Tconfiguracionalmacen.btscancelarClick(Sender: TObject); begin qsectores.Cancel; end; procedure Tconfiguracionalmacen.btsguardarClick(Sender: TObject); begin qsectores.Post; end; procedure Tconfiguracionalmacen.btsmodificarClick(Sender: TObject); begin qsectores.Edit; end; procedure Tconfiguracionalmacen.btsnuevoClick(Sender: TObject); begin qsectores.Append; qsectoreside.Value:=dm.tempresaid.AsInteger; dbgrid1.ReadOnly:=false; dbgrid1.SetFocus; end; procedure Tconfiguracionalmacen.DBGrid1ColExit(Sender: TObject); begin if (DBGrid1.SelectedField.FieldName = DBLookupComboBox2.DataField) and (qsectores.State in [dsedit,dsinsert]) then begin DBLookupComboBox2.Visible := false; qsectoresdescalmacen.Value:=qalmacenesnombre.AsString; end; end; procedure Tconfiguracionalmacen.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if (gdFocused in State) then begin if (Column.Field.FieldName = DBLookupComboBox2.DataField) and (qsectores.State in [dsedit,dsinsert]) then begin with DBLookupComboBox2 do begin visible:= true; Left := Rect.Left + DBGrid1.Left + 2; Top := Rect.Top + DBGrid1.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; end; dblookupcombobox2.SetFocus; dblookupcombobox2.DropDown; end else dblookupcombobox2.Visible:=false; end end; procedure Tconfiguracionalmacen.DBGrid1KeyPress(Sender: TObject; var Key: Char); begin if (DBGrid1.SelectedField.FieldName = DBLookupComboBox2.DataField) then begin SendMessage(DBLookupComboBox2.Handle, WM_Char, word(Key), 0); // DBLookupComboBox2.SetFocus; end end; procedure Tconfiguracionalmacen.DBGrid2ColExit(Sender: TObject); begin if (DBGrid2.SelectedField.FieldName = DBLookupComboBox1.DataField) and (qpuestos.State in [dsedit,dsinsert]) then begin DBLookupComboBox1.Visible := false; qpuestosdescsector.Value:=qsectoresdescripcion.AsString; end; end; procedure Tconfiguracionalmacen.DBGrid2DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if (gdFocused in State) then begin if (Column.Field.FieldName = DBLookupComboBox1.DataField) and (qpuestos.State in [dsedit,dsinsert]) then begin with DBLookupComboBox1 do begin visible:= true; Left := Rect.Left + DBGrid1.Left + 2; Top := Rect.Top + DBGrid1.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; end; dblookupcombobox1.SetFocus; dblookupcombobox1.DropDown; end else dblookupcombobox1.Visible:=false; end end; procedure Tconfiguracionalmacen.DBGrid2KeyPress(Sender: TObject; var Key: Char); begin if (DBGrid2.SelectedField.FieldName = DBLookupComboBox1.DataField) then begin SendMessage(DBLookupComboBox1.Handle, WM_Char, word(Key), 0); end; end; procedure Tconfiguracionalmacen.dsqpuestosStateChange(Sender: TObject); begin if qpuestos.State in [dsedit,dsinsert] then begin btpnuevo.enabled:=false; btpborrar.enabled:=false; btpmodificar.enabled:=false; btpguardar.enabled:=true; btpcancelar.enabled:=true; dbgrid2.readonly:=false; end; if qpuestos.State in [dsbrowse] then begin btpnuevo.enabled:=true; btpborrar.enabled:=true; btpmodificar.enabled:=true; btpguardar.enabled:=false; btpcancelar.enabled:=false; dbgrid2.readonly:=true; end; end; procedure Tconfiguracionalmacen.dsqsectoresStateChange(Sender: TObject); begin if qsectores.State in [dsedit,dsinsert] then begin btsnuevo.enabled:=false; btsborrar.enabled:=false; btsmodificar.enabled:=false; btsguardar.enabled:=true; btscancelar.enabled:=true; dbgrid1.readonly:=false; end; if qsectores.State in [dsbrowse] then begin btsnuevo.enabled:=true; btsborrar.enabled:=true; btsmodificar.enabled:=true; btsguardar.enabled:=false; btscancelar.enabled:=false; dbgrid1.readonly:=true; end; end; procedure Tconfiguracionalmacen.FormCreate(Sender: TObject); begin with DBLookupComboBox2 do begin DataSource := dsqsectores; // -> AdoTable1 -> DBGrid1 ListSource := dsqalmacenes; DataField := 'idalmacen'; // from AdoTable1 - displayed in the DBGrid KeyField := 'id'; ListField := 'id;nombre'; dropdownwidth := 150; Visible := False; end; with DBLookupComboBox1 do begin DataSource := dsqpuestos; // -> AdoTable1 -> DBGrid1 ListSource := dsqsectores; DataField := 'idsector'; // from AdoTable1 - displayed in the DBGrid KeyField := 'id'; ListField := 'id;descripcion'; dropdownwidth := 150; Visible := False; end; end; procedure Tconfiguracionalmacen.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tconfiguracionalmacen.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is tdbgrid) then begin key:=','; end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tconfiguracionalmacen.FormShow(Sender: TObject); begin dm.tempresa.open; qalmacenes.Open; qsectores.Open; qpuestos.Open; end; procedure Tconfiguracionalmacen.qpuestosAfterPost(DataSet: TDataSet); begin btpnuevo.SetFocus; end; procedure Tconfiguracionalmacen.qsectoresAfterPost(DataSet: TDataSet); begin btsnuevo.SetFocus; end; end. ======================================== FICHERO: fconfirmar.pas ======================================== unit fconfirmar; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls; type TConfirmar = class(TForm) Bevel1: TBevel; LMensaje: TLabel; Image1: TImage; BSI: TBitBtn; BNO: TBitBtn; BCANCELAR: TBitBtn; private { Private declarations } public { Public declarations } end; var Confirmar: TConfirmar; implementation {$R *.dfm} end. ======================================== FICHERO: fconsumos.pas ======================================== unit fconsumos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZDataset, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ComCtrls, ZAbstractDataset, Vcl.DBCtrls, Vcl.Mask, ZSqlUpdate, frxClass, frxDBSet; type Tconsumos_gastos = class(TForm) Panel1: TPanel; btEnuevo: TButton; btEborrar: TButton; btEmodificar: TButton; btEguardar: TButton; btEcancelar: TButton; bteimprimir: TButton; Panel2: TPanel; qgrupos: TZReadOnlyQuery; qfamilias: TZReadOnlyQuery; qgruposidempresa: TIntegerField; qgruposid: TIntegerField; qgruposdescripcion: TWideStringField; qgruposactivo: TIntegerField; qfamiliasidempresa: TIntegerField; qfamiliasid: TIntegerField; qfamiliasdescripcion: TWideStringField; qfamiliasactivo: TIntegerField; qfamiliasgrupo: TIntegerField; qfamiliasCOMUN: TIntegerField; qfamiliasABONOS: TIntegerField; qfamiliasFITOSANITARIOS: TIntegerField; qfamiliasSUMINISTROS: TIntegerField; qfamiliasGENERADORES: TIntegerField; qparcelas: TZReadOnlyQuery; qparcelascodpar: TWideStringField; qparcelasempresa: TIntegerField; qparcelasnombre: TWideStringField; qparcelasvariedad: TWideStringField; qparcelasnum_plantas: TIntegerField; qparcelasfecha_plantacion: TDateField; qparcelasmarco_plantacion: TWideStringField; qparcelasnum_goteros: TFloatField; qparcelasgastosgenerales: TIntegerField; qparcelasref_catastro: TWideStringField; qparcelassigpac_prov: TIntegerField; qparcelassigpac_muni: TIntegerField; qparcelassigpac_agre: TIntegerField; qparcelassigpac_zona: TIntegerField; qparcelassigpac_poli: TIntegerField; qparcelassigpac_pacr: TIntegerField; qparcelasx: TWideStringField; qparcelasy: TWideStringField; qparcelasdatum: TWideStringField; qparcelashuso: TIntegerField; qparcelaspropiedad: TWideStringField; qparcelasactivo: TIntegerField; qparcelasseleccionado: TIntegerField; qparcelassuperficie: TFloatField; qparcelasest_meteo: TWideStringField; qparcelascoste_kg_ref: TFloatField; qparcelasactivo_almacen: TIntegerField; qparcelasporc_desperdicio: TFloatField; qparcelasporc_merma: TFloatField; qparcelases_centrotrabajo: TIntegerField; qparcelassigpac_recinto: TIntegerField; qparcelaspie_planta: TWideStringField; qparcelasnumero: TWideStringField; qparcelastiene_gg: TIntegerField; qparcelastiene_dop: TIntegerField; qparcelasc_calidad: TIntegerField; qparcelasc_espcliente: TIntegerField; qparcelasc_etiquetado: TIntegerField; qparcelassello_gg: TWideStringField; qparcelassello_dop: TWideStringField; qparcelassello_igp: TWideStringField; qparcelastiene_igp: TIntegerField; qparcelastiene_ifs: TIntegerField; qparcelassello_ifs: TWideStringField; qparcelaspropietario: TIntegerField; combocentrocoste: TDBLookupComboBox; dsparcelas: TDataSource; Label1: TLabel; Label4: TLabel; combofamilia: TDBLookupComboBox; dsqgrupos: TDataSource; dsqfamilias: TDataSource; Label3: TLabel; ffecha: TDateTimePicker; dsqresponsables: TDataSource; qresponsables: TZReadOnlyQuery; qresponsablesnombre: TWideStringField; qconsumos: TZQuery; PageControl1: TPageControl; Listado: TTabSheet; Detalles: TTabSheet; Panel4: TPanel; Panel5: TPanel; Panel6: TPanel; Panel7: TPanel; Panel8: TPanel; Panel9: TPanel; checkfechas: TCheckBox; checkcc: TCheckBox; checkgrupos: TCheckBox; checkfamilias: TCheckBox; DBGrid1: TDBGrid; dsqconsumos: TDataSource; btbuscar: TButton; Panel10: TPanel; qparcelas2: TZReadOnlyQuery; dsqparcelas2: TDataSource; dsqgrupos2: TDataSource; qgrupos2: TZReadOnlyQuery; qfamilias2: TZReadOnlyQuery; dsqfamilias2: TDataSource; qfamilias2idempresa: TIntegerField; qfamilias2id: TIntegerField; qfamilias2descripcion: TWideStringField; qfamilias2activo: TIntegerField; qfamilias2grupo: TIntegerField; qfamilias2COMUN: TIntegerField; qfamilias2ABONOS: TIntegerField; qfamilias2FITOSANITARIOS: TIntegerField; qfamilias2SUMINISTROS: TIntegerField; qfamilias2GENERADORES: TIntegerField; qlistadoconsumos: TZReadOnlyQuery; dsqlistadoconsumos: TDataSource; DBGrid2: TDBGrid; qgrupos2idempresa: TIntegerField; qgrupos2id: TIntegerField; qgrupos2descripcion: TWideStringField; qgrupos2activo: TIntegerField; qparcelas2codpar: TWideStringField; qparcelas2empresa: TIntegerField; qparcelas2nombre: TWideStringField; qparcelas2variedad: TWideStringField; qparcelas2num_plantas: TIntegerField; qparcelas2fecha_plantacion: TDateField; qparcelas2marco_plantacion: TWideStringField; qparcelas2num_goteros: TFloatField; qparcelas2gastosgenerales: TIntegerField; qparcelas2ref_catastro: TWideStringField; qparcelas2sigpac_prov: TIntegerField; qparcelas2sigpac_muni: TIntegerField; qparcelas2sigpac_agre: TIntegerField; qparcelas2sigpac_zona: TIntegerField; qparcelas2sigpac_poli: TIntegerField; qparcelas2sigpac_pacr: TIntegerField; qparcelas2x: TWideStringField; qparcelas2y: TWideStringField; qparcelas2datum: TWideStringField; qparcelas2huso: TIntegerField; qparcelas2propiedad: TWideStringField; qparcelas2activo: TIntegerField; qparcelas2seleccionado: TIntegerField; qparcelas2superficie: TFloatField; qparcelas2est_meteo: TWideStringField; qparcelas2coste_kg_ref: TFloatField; qparcelas2activo_almacen: TIntegerField; qparcelas2porc_desperdicio: TFloatField; qparcelas2porc_merma: TFloatField; qparcelas2es_centrotrabajo: TIntegerField; qparcelas2sigpac_recinto: TIntegerField; qparcelas2pie_planta: TWideStringField; qparcelas2numero: TWideStringField; qparcelas2tiene_gg: TIntegerField; qparcelas2tiene_dop: TIntegerField; qparcelas2c_calidad: TIntegerField; qparcelas2c_espcliente: TIntegerField; qparcelas2c_etiquetado: TIntegerField; qparcelas2sello_gg: TWideStringField; qparcelas2sello_dop: TWideStringField; qparcelas2sello_igp: TWideStringField; qparcelas2tiene_igp: TIntegerField; qparcelas2tiene_ifs: TIntegerField; qparcelas2sello_ifs: TWideStringField; qparcelas2propietario: TIntegerField; qresponsablesnif: TWideStringField; qresponsablesfirma: TBlobField; Panel11: TPanel; DBGrid3: TDBGrid; qaux: TZReadOnlyQuery; Panel14: TPanel; checkcampanyas: TCheckBox; dsqcampanyas: TDataSource; qcampanyas: TZReadOnlyQuery; qcampanyasid: TIntegerField; qcampanyasidempresa: TIntegerField; qcampanyasid_anterior: TIntegerField; qcampanyasdescripcion: TWideStringField; qcampanyasfechainicio: TDateField; qcampanyasfechafin: TDateField; qcampanyasult_pesada: TIntegerField; pcentros: TPanel; combocc2: TDBLookupComboBox; pgrupos: TPanel; combogrupos2: TDBLookupComboBox; pfamilias: TPanel; combofamilia2: TDBLookupComboBox; pfechas: TPanel; Label6: TLabel; Label7: TLabel; fdesde: TDateTimePicker; fhasta: TDateTimePicker; pcampanyas: TPanel; combocampanya: TDBLookupComboBox; Label11: TLabel; DBText1: TDBText; gcrcheck: TDBCheckBox; Label8: TLabel; comboamortizacion: TComboBox; tnumperiodos: TEdit; Label9: TLabel; Label10: TLabel; comboperiodicidad: TComboBox; Label2: TLabel; Label5: TLabel; Label12: TLabel; Label13: TLabel; Label14: TLabel; DBText6: TDBText; DBEdit1: TDBEdit; DBEdit2: TDBEdit; DBEdit3: TDBEdit; DBEdit4: TDBEdit; Panel12: TPanel; quconsumos_gastos: TZQuery; qconsumosid: TIntegerField; qconsumoside: TIntegerField; qconsumosidcc: TWideStringField; qconsumosidgrupo: TIntegerField; qconsumosidfamilia: TIntegerField; qconsumosidaf: TIntegerField; qconsumoscodigo: TWideStringField; qconsumosdescripcion: TWideStringField; qconsumosregistro: TWideStringField; qconsumosprecio: TFloatField; qconsumoscantidad: TFloatField; qconsumostotal: TFloatField; qconsumostotal_amortizado: TFloatField; qconsumosnumplazos: TIntegerField; qconsumoslote: TWideStringField; qconsumosidentrada: TIntegerField; qconsumosfecha: TDateField; qconsumosidfraccionado: TIntegerField; qconsumosamortizacion: TIntegerField; qlistadoconsumoside: TIntegerField; qlistadoconsumosid: TIntegerField; qlistadoconsumosfecha: TDateField; qlistadoconsumosgrupo: TWideStringField; qlistadoconsumosfamilia: TWideStringField; qlistadoconsumosparcela: TWideStringField; qlistadoconsumosamortizacion: TIntegerField; qlistadoconsumosdescripcion: TWideStringField; qlistadoconsumostotal_amortizado: TFloatField; qlistadoconsumosidfraccionado: TIntegerField; informedb: TfrxDBDataset; informes: TfrxReport; Button1: TButton; procedure FormShow(Sender: TObject); procedure DBGrid3KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DBGrid3KeyPress(Sender: TObject; var Key: Char); procedure btEnuevoClick(Sender: TObject); procedure dsqconsumosStateChange(Sender: TObject); procedure btEcancelarClick(Sender: TObject); procedure btEguardarClick(Sender: TObject); procedure btEmodificarClick(Sender: TObject); procedure btEborrarClick(Sender: TObject); procedure checkcampanyasClick(Sender: TObject); procedure checkfechasClick(Sender: TObject); procedure checkccClick(Sender: TObject); procedure checkgruposClick(Sender: TObject); procedure checkfamiliasClick(Sender: TObject); procedure dsqcampanyasDataChange(Sender: TObject; Field: TField); procedure btbuscarClick(Sender: TObject); procedure dsqconsumosDataChange(Sender: TObject; Field: TField); procedure DBGrid2DblClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure DBGrid3DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBGrid2DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBEdit4Enter(Sender: TObject); procedure DBGrid2TitleClick(Column: TColumn); procedure qconsumosBeforePost(DataSet: TDataSet); procedure qconsumosAfterPost(DataSet: TDataSet); procedure qconsumosBeforeDelete(DataSet: TDataSet); procedure ffechaExit(Sender: TObject); procedure bteimprimirClick(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var consumos_gastos: Tconsumos_gastos; const rojo=$00AAAAFF; amarillo=$00B9FFFF; verde=$00C7FBAA; azul=$00FFFFBB; implementation {$R *.dfm} uses fbuscararticulos, datos, principal; procedure Tconsumos_gastos.btEborrarClick(Sender: TObject); begin qconsumos.Close; qconsumos.ParamByName('IDENTRADA').AsString:=qlistadoconsumosidfraccionado.AsString; qconsumos.Open; qconsumos.Locate('ID',qlistadoconsumosid.AsString,[locaseinsensitive]); qconsumos.Delete; qlistadoconsumos.Refresh; end; procedure Tconsumos_gastos.btEcancelarClick(Sender: TObject); begin qconsumos.Cancel; panel2.Enabled:=false; end; procedure Tconsumos_gastos.btEguardarClick(Sender: TObject); var vidfraccionado,vperiodos,vdias,vidgrupo,vidfamilia,vide,vamortizacion:integer; x: Integer; vcantidad,vtotal,vprecio:real; vidcc,vdescripcion:string; vfecha:tdatetime; begin qaux.Close; if qconsumos.State in [dsinsert] then begin vfecha:=ffecha.Date; vperiodos:=strtoint(tnumperiodos.Text); vamortizacion:=1; vdescripcion:=qconsumosdescripcion.AsString; vcantidad:=qconsumoscantidad.AsFloat; vtotal:=qconsumostotal.AsFloat; vprecio:=qconsumosprecio.AsFloat; vidfamilia:=combofamilia.Keyvalue; vidcc:=combocentrocoste.KeyValue; vidgrupo:=qgruposid.AsInteger; if comboamortizacion.ItemIndex=1 then begin case comboperiodicidad.ItemIndex of 0: begin vdias:=365; end; 1: begin vdias:=30; end; end; end else begin vdias:=1; vperiodos:=1; vamortizacion:=0; end; qaux.Open; if qaux.Fields[0].AsString='' then vidfraccionado:=1 else vidfraccionado:=qaux.Fields[0].asinteger; for x := 0 to vperiodos-1 do begin if qconsumos.State in [dsbrowse] then qconsumos.Append; qaux.Open; qconsumosid.Value:=qaux.Fields[0].asinteger; qconsumosidfraccionado.Value:=vidfraccionado; qconsumoside.Value:=dm.tempresaid.asinteger; qconsumosnumplazos.value:=vperiodos; qconsumosdescripcion.Value:=vdescripcion; qconsumoscantidad.Value:=vcantidad; qconsumosprecio.Value:=vprecio; qconsumostotal.Value:=vtotal; qconsumostotal_amortizado.value:=vtotal/vperiodos; qconsumosfecha.Value:=vfecha+(x*vdias); qconsumosidcc.Value:=vidcc; qconsumosidgrupo.Value:=vidgrupo; qconsumosidfamilia.Value:=vidfamilia; qconsumosamortizacion.Value:=vamortizacion; qconsumos.Post; qaux.Close; end; pagecontrol1.ActivePageIndex:=0; end; if qconsumos.State in [dsedit] then begin if qconsumosfecha.AsDateTime<>ffecha.date then begin ffecha.Date:=qconsumosfecha.AsDateTime; end; vfecha:=ffecha.Date; vperiodos:=strtoint(tnumperiodos.Text); vdescripcion:=qconsumosdescripcion.AsString; vcantidad:=qconsumoscantidad.AsFloat; vtotal:=qconsumostotal.AsFloat; vprecio:=qconsumosprecio.AsFloat; vidfamilia:=combofamilia.Keyvalue; vidcc:=combocentrocoste.KeyValue; vidgrupo:=qgruposid.AsInteger; qconsumosdescripcion.Value:=vdescripcion; qconsumoscantidad.Value:=vcantidad; qconsumosprecio.Value:=vprecio; qconsumostotal.Value:=vtotal; qconsumosfecha.Value:=vfecha; qconsumosidcc.Value:=combocentrocoste.KeyValue; qconsumosidfamilia.Value:=combofamilia.KeyValue; qconsumosidgrupo.Value:=qgruposid.AsInteger; qconsumos.Post; pagecontrol1.ActivePageIndex:=0; end; vidgrupo:=qconsumosid.Asinteger; vide:=qconsumoside.AsInteger; qlistadoconsumos.Refresh; qlistadoconsumos.Locate('ide,id',vararrayof([vide,vidgrupo]),[locaseinsensitive]); panel2.Enabled:=false; end; procedure Tconsumos_gastos.bteimprimirClick(Sender: TObject); begin informedb.DataSource := dsqlistadoconsumos; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\informecgastos.fr3'); informes.ShowReport(); informes.Clear end; procedure Tconsumos_gastos.btEmodificarClick(Sender: TObject); var videntrada:string; begin videntrada:=qlistadoconsumosidfraccionado.AsString; pagecontrol1.ActivePageIndex:=1; qconsumos.Close; qconsumos.ParamByName('IDENTRADA').AsString:=videntrada; qconsumos.Open; panel2.Enabled:=true; qconsumos.Edit; end; procedure Tconsumos_gastos.btEnuevoClick(Sender: TObject); begin pagecontrol1.ActivePageIndex:=1; panel2.Enabled:=true; qconsumos.Append; ffecha.Date:=date; ffecha.SetFocus; combofamilia.KeyValue:=dm.tempresaidfamilia.AsInteger; end; procedure Tconsumos_gastos.Button1Click(Sender: TObject); var archivo: string; begin base.SaveDialog1.FileName := 'CONSUMOS Y GASTOS.xlsx'; base.SaveDialog1.Execute(); archivo := base.SaveDialog1.FileName; try BASE.ExportaraExcel(archivo, 'CONSUMOS Y GASTOS', DBGrid2); finally showmessage('Los datos han sido exportados correctamente a ' + archivo); end; end; procedure Tconsumos_gastos.btbuscarClick(Sender: TObject); var vcc,vgrupo,vfamilia,videntrada:string; begin videntrada:='%'; if checkcc.Checked then vcc:=qparcelas2codpar.AsString else vcc:='%'; if checkgrupos.Checked then vgrupo:=qgrupos2id.AsString else vgrupo:='%'; if checkfamilias.Checked then vfamilia:=qfamilias2id.AsString else vfamilia:='%'; qlistadoconsumos.Close; qlistadoconsumos.Prepare; if checkfechas.Checked or checkcampanyas.Checked then begin qlistadoconsumos.ParamByName('FDESDE').AsDate:=fdesde.Date; qlistadoconsumos.ParamByName('FHASTA').AsDate:=fhasta.Date; end else begin qlistadoconsumos.ParamByName('FDESDE').AsDate:=strtodate('01/01/2000'); qlistadoconsumos.ParamByName('FHASTA').AsDate:=strtodate('31/12/2100'); end; qlistadoconsumos.ParamByName('CC').Asstring:=vcc; qlistadoconsumos.ParamByName('GRUPO').Asstring:=vgrupo; qlistadoconsumos.ParamByName('FAMILIA').Asstring:=vfamilia; qlistadoconsumos.open; videntrada:=qlistadoconsumosidfraccionado.AsString; qconsumos.Close; qconsumos.ParamByName('IDENTRADA').Asstring:=videntrada; qconsumos.open; end; procedure Tconsumos_gastos.checkcampanyasClick(Sender: TObject); begin if checkcampanyas.Checked=true then begin pcampanyas.Visible:=true; panel14.Height:=55; end else begin pcampanyas.visible:=false; panel14.Height:=20; end; end; procedure Tconsumos_gastos.checkccClick(Sender: TObject); begin if checkcc.Checked=true then begin pcentros.Visible:=true; panel7.Height:=55; combocc2.KeyValue:=qparcelas2codpar.Asstring; end else begin pcentros.visible:=false; panel7.Height:=20; end; end; procedure Tconsumos_gastos.checkfamiliasClick(Sender: TObject); begin if checkfamilias.Checked=true then begin pfamilias.Visible:=true; panel6.Height:=55; combofamilia2.KeyValue:=qfamilias2id.AsInteger; end else begin pfamilias.visible:=false; panel6.Height:=20; end; end; procedure Tconsumos_gastos.checkfechasClick(Sender: TObject); begin if checkfechas.Checked=true then begin pfechas.Visible:=true; panel8.Height:=75; end else begin pfechas.visible:=false; panel8.Height:=20; end; end; procedure Tconsumos_gastos.checkgruposClick(Sender: TObject); begin if checkgrupos.Checked=true then begin pgrupos.Visible:=true; panel5.Height:=55; combogrupos2.KeyValue:=qgrupos2id.AsInteger end else begin pgrupos.visible:=false; panel5.Height:=20; end; end; procedure Tconsumos_gastos.DBEdit4Enter(Sender: TObject); begin if qconsumos.State in [dsedit,dsinsert] then qconsumostotal.Value:=qconsumoscantidad.AsFloat*qconsumosprecio.AsFloat; end; procedure Tconsumos_gastos.DBGrid2DblClick(Sender: TObject); var videntrada:string; begin videntrada:=qlistadoconsumosidfraccionado.AsString; pagecontrol1.ActivePageIndex:=1; qconsumos.Close; qconsumos.ParamByName('IDENTRADA').AsString:=videntrada; qconsumos.Open; end; procedure Tconsumos_gastos.DBGrid2DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); const IsChecked : array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED); var DrawState: Integer; DrawRect: TRect; begin if qlistadoconsumosamortizacion.Asinteger=1 then begin dbgrid2.Canvas.brush.Color := azul; end; if qlistadoconsumosamortizacion.Asinteger=0 then begin dbgrid2.Canvas.brush.Color := clwindow; end; dbgrid2.DefaultDrawColumnCell(Rect, DataCol, Column, State); if (gdFocused in State) then begin if (Column.Field.FieldName = 'amortizacion') then begin gcrcheck.Left := Rect.Left + DBgrid2.Left + 2; gcrcheck.Top := Rect.Top + DBgrid2.top + 2; gcrcheck.Width := Rect.Right - Rect.Left; gcrcheck.Height := Rect.Bottom - Rect.Top; gcrcheck.Visible := True; end; end else begin if (Column.Field.FieldName = 'amortizacion') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; // DrawState := ISChecked[Column.Field.Asboolean]; DBgrid2.Canvas.FillRect(Rect); DrawFrameControl(DBgrid2.Canvas.Handle, DrawRect, DFC_BUTTON, DrawState); end; end; gcrcheck.visible:=false; end; procedure Tconsumos_gastos.DBGrid2TitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=qlistadoconsumos.SortType; qlistadoconsumos.SortedFields:=Column.FieldName; If st = stAscending then qlistadoconsumos.SortType:=stDescending else qlistadoconsumos.SortType:=stAscending; dsqlistadoconsumos.DataSet.First; end; procedure Tconsumos_gastos.DBGrid3DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); const IsChecked : array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED); var DrawState: Integer; DrawRect: TRect; begin if (gdFocused in State) then begin if (Column.Field.FieldName = 'amortizacion') then begin gcrcheck.Left := Rect.Left + DBgrid3.Left + 2; gcrcheck.Top := Rect.Top + DBgrid3.top + 2; gcrcheck.Width := Rect.Right - Rect.Left; gcrcheck.Height := Rect.Bottom - Rect.Top; gcrcheck.Visible := True; end; end else begin if (Column.Field.FieldName = 'amortizacion') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; // DrawState := ISChecked[Column.Field.Asboolean]; DBgrid3.Canvas.FillRect(Rect); DrawFrameControl(DBgrid3.Canvas.Handle, DrawRect, DFC_BUTTON, DrawState); end; end; gcrcheck.visible:=false; end; procedure Tconsumos_gastos.DBGrid3KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (key=115) then begin buscararticulos := Tbuscararticulos.Create(nil); try fbuscararticulos.filtro:=qconsumosdescripcion.AsString; buscararticulos.Edit1.Text:=qconsumosdescripcion.AsString; buscararticulos.showmodal(); finally if qconsumos.State in [dsbrowse] then qconsumos.Edit; qconsumosidaf.Value:=buscararticulos.qarticulosid.Asinteger; qconsumoscodigo.Value:=buscararticulos.qarticuloscodigo.Asstring; qconsumosregistro.Value:=buscararticulos.qarticulosregistro.Asstring; qconsumosdescripcion.value:=buscararticulos.qarticulosdescripcion.AsString; qconsumosprecio.Value:=buscararticulos.qarticulosult_preciocompra.Asfloat; buscararticulos.Free; end; end; end; procedure Tconsumos_gastos.DBGrid3KeyPress(Sender: TObject; var Key: Char); begin if (key = Chr(9)) then Exit; end; procedure Tconsumos_gastos.dsqcampanyasDataChange(Sender: TObject; Field: TField); begin fdesde.Date:=qcampanyasfechainicio.asdatetime; fhasta.Date:=qcampanyasfechafin.asdatetime; end; procedure Tconsumos_gastos.dsqconsumosDataChange(Sender: TObject; Field: TField); begin if qconsumos.State in [dsbrowse] then ffecha.Date:=qconsumosfecha.AsDateTime; end; procedure Tconsumos_gastos.dsqconsumosStateChange(Sender: TObject); begin if qconsumos.State in [dsedit,dsinsert] then begin btenuevo.Enabled:=false; btemodificar.Enabled:=false; bteborrar.Enabled:=false; btecancelar.Enabled:=true; bteguardar.Enabled:=true; end else begin btenuevo.Enabled:=true; btemodificar.Enabled:=true; bteborrar.Enabled:=true; btecancelar.Enabled:=false; bteguardar.Enabled:=false; end; end; procedure Tconsumos_gastos.ffechaExit(Sender: TObject); begin if qconsumos.State in [dsinsert,dsedit] then begin qconsumosfecha.Value:=ffecha.Date; end; end; procedure Tconsumos_gastos.FormKeyPress(Sender: TObject; var Key: Char); begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tconsumos_gastos.FormShow(Sender: TObject); begin qparcelas.close; qparcelas2.Close; qgrupos.Close; qgrupos2.close; qfamilias.Close; qfamilias2.Close; qlistadoconsumos.close; qconsumos.Close; qresponsables.close; qparcelas.open; qparcelas2.open; qgrupos.open; qgrupos2.open; qfamilias.open; qfamilias2.open; qlistadoconsumos.prepare; qresponsables.open; qcampanyas.Open; combocampanya.KeyValue:=qcampanyasid.AsInteger; qconsumos.prepare; pagecontrol1.ActivePageIndex:=0; ffecha.Date:=date; btbuscar.Click; end; procedure Tconsumos_gastos.qconsumosAfterPost(DataSet: TDataSet); begin if qconsumosamortizacion.AsInteger=1 then begin quconsumos_gastos.ParamByName('IDCC').AsString:=qconsumosidcc.AsString; quconsumos_gastos.ParamByName('IDCC').Asstring:=qconsumosidcc.Asstring; quconsumos_gastos.ParamByName('IDGRUPO').AsInteger:=qconsumosidgrupo.AsInteger; quconsumos_gastos.ParamByName('IDFAMILIA').AsInteger:=qconsumosidfamilia.AsInteger; quconsumos_gastos.ParamByName('AF').Asinteger:=qconsumosidaf.AsInteger; quconsumos_gastos.ParamByName('DESCRIPCION').Asstring:=qconsumosdescripcion.Asstring; quconsumos_gastos.ParamByName('REGISTRO').Asstring:=qconsumosregistro.AsString; quconsumos_gastos.ParamByName('PRECIO').Asfloat:=qconsumosprecio.Asfloat; quconsumos_gastos.ParamByName('CANTIDAD').Asfloat:=qconsumoscantidad.AsFloat; quconsumos_gastos.ParamByName('TOTAL').Asfloat:=qconsumostotal.Asfloat; quconsumos_gastos.ParamByName('TOTALAMORTIZADO').Asfloat:=qconsumostotal_amortizado.AsFloat; quconsumos_gastos.ParamByName('NUMPLAZOS').AsInteger:=qconsumosnumplazos.AsInteger; quconsumos_gastos.ParamByName('LOTE').Asstring:=qconsumoslote.Asstring; quconsumos_gastos.ParamByName('IDENTRADA').AsInteger:=qconsumosidentrada.AsInteger; quconsumos_gastos.ParamByName('IDFRACCIONADO').AsInteger:=qconsumosidfraccionado.AsInteger; quconsumos_gastos.ParamByName('ID').AsInteger:=qconsumosid.AsInteger; quconsumos_gastos.ExecSQL; qconsumos.refresh; qlistadoconsumos.Refresh; end; end; procedure Tconsumos_gastos.qconsumosBeforeDelete(DataSet: TDataSet); begin case dm.PedirConfirmacion('¿Confirma que desea borrar este consumo/gasto?',true,true,false) of mrno:Abort; end; end; procedure Tconsumos_gastos.qconsumosBeforePost(DataSet: TDataSet); var x:integer; begin qconsumostotal.Value:=qconsumosprecio.AsFloat*qconsumoscantidad.AsFloat; qconsumostotal_amortizado.Value:=qconsumostotal.AsFloat/qconsumosnumplazos.AsInteger; if qconsumos.state=dsinsert then x:=dm.PedirConfirmacion('¿Confirma que desea dar de alta esta consumo/gasto?',true,true,true) else x:=dm.PedirConfirmacion('¿Confirma que desea modificar esta consumo/gasto?',true,true,true); case x of mrno: begin qconsumos.cancel; abort; end; mrcancel:BEGIN abort; END; end; end; end. ======================================== FICHERO: fconsumosfito.pas ======================================== unit fconsumosfito; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.DBCtrls, Data.DB, ZAbstractDataset, ZDataset, ZAbstractRODataset, Vcl.Grids, Vcl.DBGrids, Vcl.ComCtrls, comobj,excel2000,Vcl.ExtCtrls; type Tconsumosfito = class(TForm) Panel1: TPanel; finicio: TDateTimePicker; ffin: TDateTimePicker; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Panel2: TPanel; Panel3: TPanel; DBGrid1: TDBGrid; DBGrid2: TDBGrid; qconsumostratamientos: TZQuery; qultimoinventario: TZReadOnlyQuery; qultimoinventarioide: TIntegerField; qultimoinventariofecha: TDateField; qultimoinventarioregularizado: TIntegerField; dsqultimoinventario: TDataSource; Panel4: TPanel; Button2: TButton; Button1: TButton; Button3: TButton; Button4: TButton; dsqconsumostratamientos: TDataSource; GroupBox1: TGroupBox; checkinventario: TRadioButton; checkhistorico: TRadioButton; qconsumos: TZReadOnlyQuery; qconsumosidaf: TIntegerField; qconsumoside: TIntegerField; qconsumosdescripcion: TWideStringField; qconsumosregistro: TWideStringField; qconsumosfamilia: TWideStringField; qconsumosconsumo: TFloatField; qconsumoscompras: TFloatField; qconsumosPM_stock: TFloatField; qconsumosunidad_medida: TWideStringField; Panel5: TPanel; Panel6: TPanel; qstockinventario: TZReadOnlyQuery; qstockhistorico: TZReadOnlyQuery; comboinventarios: TDBLookupComboBox; qidconsumo: TZReadOnlyQuery; qidconsumoid: TLargeintField; dsqstockinventario: TDataSource; qstockhistoricostock_final: TFloatField; qstockinventariostock_final: TFloatField; qconsumostratamientosid: TIntegerField; qconsumostratamientoside: TIntegerField; qconsumostratamientosidaf: TIntegerField; qconsumostratamientosdescripcion_af: TWideStringField; qconsumostratamientosregistro: TWideStringField; qconsumostratamientosstock_anterior: TFloatField; qconsumostratamientosconsumo_periodo: TFloatField; qconsumostratamientoscompras_periodo: TFloatField; qconsumostratamientosregularizacion: TFloatField; qconsumostratamientosstock_final: TFloatField; qconsumostratamientosunidades: TWideStringField; qconsumostratamientosprecio_medio: TFloatField; qconsumostratamientosvalor_stock: TFloatField; qconsumostratamientosfecha_inicio: TDateField; qconsumostratamientosfecha_fin: TDateField; qhistoricoconsumos: TZReadOnlyQuery; dsqhistoricoconsumos: TDataSource; combohistoricos: TDBLookupComboBox; dsqhistoricoconsumos2: TDataSource; qhistoricoconsumos2: TZReadOnlyQuery; qhistoricoconsumosfecha_inicio: TDateField; qhistoricoconsumosfecha_fin: TDateField; qhistoricoconsumosid: TIntegerField; qhistoricoconsumoside: TIntegerField; qhistoricoconsumos2fecha_inicio: TDateField; qhistoricoconsumos2fecha_fin: TDateField; qhistoricoconsumos2id: TIntegerField; qhistoricoconsumos2ide: TIntegerField; qborrar: TZReadOnlyQuery; qconsumoscodigo: TWideStringField; qconsumostratamientoscodigo: TWideStringField; qconsumostratamientosfamilia: TWideStringField; SaveDialog1: TSaveDialog; procedure Button4Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure dsqhistoricoconsumosDataChange(Sender: TObject; Field: TField); procedure Button3Click(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } procedure ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar = nil); end; var consumosfito: Tconsumosfito; implementation {$R *.dfm} procedure tconsumosfito.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 Tconsumosfito.Button1Click(Sender: TObject); var archivo:string; begin SaveDialog1.FileName := 'ESTADO DE STOCKS.xlsx'; SaveDialog1.Execute(); archivo := SaveDialog1.FileName; if dbgrid2.Visible then begin try Exportaraexcel(archivo,'ESTADO DE STOCKS',dbgrid2); finally showmessage('Los datos han sido exportados correctamente'); end; end; end; procedure Tconsumosfito.Button3Click(Sender: TObject); begin qborrar.Prepare; qborrar.ParamByName('ID').AsInteger:=qhistoricoconsumosid.asinteger; qborrar.ExecSQL; qhistoricoconsumos.Refresh; qhistoricoconsumos2.Refresh; end; procedure Tconsumosfito.Button4Click(Sender: TObject); var vstock:real; begin qidconsumo.Close; qidconsumo.Open; qstockhistorico.Close; qstockhistorico.Prepare; qstockhistorico.ParamByName('IDANTERIOR').AsInteger:=0; qstockhistorico.ParamByName('IDAF').AsInteger:=0; qstockhistorico.open; qstockinventario.Close; qstockinventario.Prepare; qstockinventario.ParamByName('FECHA').AsDATE:=DATE(); qstockinventario.ParamByName('IDAF').AsInteger:=0; qstockinventario.open; qconsumos.Close; qconsumos.Prepare; qconsumos.ParamByName('FINICIO').AsDate:=finicio.Date; qconsumos.ParamByName('FFIN').AsDate:=ffin.Date; qconsumos.Open; while not qconsumos.Eof do begin if checkhistorico.Checked then begin qstockhistorico.Prepare; qstockhistorico.ParamByName('IDANTERIOR').AsInteger:=qhistoricoconsumos2id.AsInteger; qstockhistorico.ParamByName('IDAF').AsInteger:=qconsumosidaf.AsInteger; qstockhistorico.refresh; vstock:=qstockhistoricostock_final.asfloat; if qstockhistorico.RecordCount=0 then begin qstockinventario.Prepare; qstockinventario.ParamByName('FECHA').Asdate:=qultimoinventariofecha.AsDateTime; qstockinventario.ParamByName('IDAF').AsInteger:=qconsumosidaf.AsInteger; qstockinventario.refresh; vstock:=qstockinventariostock_final.asfloat; end; end; if checkinventario.Checked then begin qstockinventario.Prepare; qstockinventario.ParamByName('FECHA').Asdate:=qultimoinventariofecha.AsDateTime; qstockinventario.ParamByName('IDAF').AsInteger:=qconsumosidaf.AsInteger; qstockinventario.refresh; vstock:=qstockinventariostock_final.asfloat; if qstockinventario.RecordCount=0 then begin qstockhistorico.Prepare; qstockhistorico.ParamByName('IDANTERIOR').AsInteger:=qhistoricoconsumos2id.AsInteger; qstockhistorico.ParamByName('IDAF').AsInteger:=qconsumosidaf.AsInteger; qstockhistorico.refresh; vstock:=qstockhistoricostock_final.asfloat; end; end; qconsumostratamientos.Open; qconsumostratamientos.Append; qconsumostratamientosid.value:=qidconsumoid.AsInteger; qconsumostratamientoside.value:=qconsumoside.AsInteger; qconsumostratamientosidaf.value:=qconsumosidaf.AsInteger; qconsumostratamientoscodigo.value:=qconsumoscodigo.Asstring; qconsumostratamientosdescripcion_af.value:=qconsumosdescripcion.AsString; qconsumostratamientosfamilia.value:=qconsumosfamilia.AsString; qconsumostratamientosregistro.value:=qconsumosregistro.AsString; qconsumostratamientosstock_anterior.value:=vstock; qconsumostratamientosconsumo_periodo.value:=qconsumosconsumo.AsFloat; qconsumostratamientoscompras_periodo.value:=qconsumoscompras.AsFloat; qconsumostratamientosregularizacion.value:=0; qconsumostratamientosprecio_medio.value:=qconsumospm_stock.AsFloat; qconsumostratamientosfecha_inicio.value:=finicio.Date; qconsumostratamientosfecha_fin.value:=ffin.Date; qconsumostratamientosunidades.value:=qconsumosunidad_medida.AsString; qconsumostratamientos.Post; qconsumos.next; end; // qconsumostratamientos.Refresh; qhistoricoconsumos.Refresh; qhistoricoconsumos2.Refresh; end; procedure Tconsumosfito.dsqhistoricoconsumosDataChange(Sender: TObject; Field: TField); begin qconsumostratamientos.Close; qconsumostratamientos.Prepare; qconsumostratamientos.ParamByName('ID').AsInteger:=qhistoricoconsumosid.AsInteger; qconsumostratamientos.Open; end; procedure Tconsumosfito.FormShow(Sender: TObject); begin finicio.Date:=date(); ffin.Date:=date(); qstockhistorico.Open; qultimoinventario.Open; qhistoricoconsumos2.Open; qhistoricoconsumos.Open; comboinventarios.KeyValue:=qultimoinventariofecha.AsDateTime; combohistoricos.KeyValue:=qhistoricoconsumos2fecha_inicio.AsDateTime; end; end. ======================================== FICHERO: fconsumosfitoparcelas.pas ======================================== unit fconsumosfitoparcelas; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls, Data.DB, ZAbstractRODataset, ZDataset, Vcl.Grids, Vcl.DBGrids; type Tconsumosfitoparcelas = class(TForm) Panel1: TPanel; Panel2: TPanel; fdesde: TDateTimePicker; fhasta: TDateTimePicker; Label1: TLabel; Label2: TLabel; Button1: TButton; Button2: TButton; Button3: TButton; DBGrid1: TDBGrid; dsqconsumos: TDataSource; qconsumos: TZReadOnlyQuery; qconsumosidaf: TIntegerField; qconsumosdescripcion_af: TWideStringField; qconsumoscantidad: TFloatField; qconsumosid_cc: TWideStringField; qconsumosparcela: TWideStringField; qconsumosfamilia: TWideStringField; SaveDialog1: TSaveDialog; procedure FormShow(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var consumosfitoparcelas: Tconsumosfitoparcelas; implementation uses principal; {$R *.dfm} procedure Tconsumosfitoparcelas.Button1Click(Sender: TObject); var archivo: string; begin SaveDialog1.FileName :='CONSUMOS FITOSANITARIOS-ABONOS POR PARCELA.xlsx'; SaveDialog1.Execute(); archivo := SaveDialog1.FileName; try base.ExportaraExcel(archivo, 'CONSUMOS', DBGrid1); finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure Tconsumosfitoparcelas.Button3Click(Sender: TObject); begin qconsumos.close; qconsumos.prepare; qconsumos.Parambyname('DESDE').asdate:=fdesde.date; qconsumos.Parambyname('HASTA').asdate:=fhasta.date; qconsumos.open; end; procedure Tconsumosfitoparcelas.FormShow(Sender: TObject); begin fdesde.Date:=date(); fhasta.Date:=date(); end; end. ======================================== FICHERO: fcontrolcalidad.pas ======================================== unit fcontrolcalidad; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.DBCtrls, ZAbstractDataset, ZDataset, ZAbstractRODataset, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.StdCtrls; type TForm3 = class(TForm) Panel1: TPanel; Panel2: TPanel; DBGrid1: TDBGrid; qcampanyas: TZReadOnlyQuery; qpesadas: TZQuery; dsqcampanyas: TDataSource; dsqpesadas: TDataSource; DBLookupComboBox1: TDBLookupComboBox; qpesadaside: TIntegerField; qpesadasid: TIntegerField; qpesadasidea: TIntegerField; qpesadasfecha: TDateField; qpesadasfechasalida: TDateField; qpesadasidenvase: TWideStringField; qpesadasdescenvase: TWideStringField; qpesadasidformato: TWideStringField; qpesadasdescformato: TWideStringField; qpesadasvariedad: TIntegerField; qpesadassocio: TIntegerField; qpesadasetiqueta: TWideStringField; qpesadasidalbaran: TWideStringField; qpesadaslote: TIntegerField; qpesadasespecificacionescliente: TIntegerField; qpesadasetiquetadodestino: TIntegerField; qpesadasetiquetaggn: TIntegerField; qpesadasapto: TIntegerField; qaux: TZQuery; qcampanyasid: TIntegerField; qcampanyasidempresa: TIntegerField; qcampanyasid_anterior: TIntegerField; qcampanyasdescripcion: TWideStringField; qcampanyasfechainicio: TDateField; qcampanyasfechafin: TDateField; qcampanyasult_pesada: TIntegerField; Label1: TLabel; procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form3: TForm3; implementation {$R *.dfm} procedure TForm3.FormShow(Sender: TObject); begin qcampanyas.Open; qpesadas.Open; qaux.sql.Clear; qaux.SQL.Add('select distinct(idempresa),id,idea from ea_pesadas where (idempresa,id,idea) not in (select ide,id,idea from ea_controlcalidad) and idea<=0'); qaux.Open; end; end. ======================================== FICHERO: fcontrolminimos.pas ======================================== unit fcontrolminimos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZDataset, Vcl.Grids, Vcl.DBGrids, ZAbstractDataset, frxClass, frxExportPDF, frxDBSet, Vcl.StdCtrls, Vcl.ExtCtrls, frxExportBaseDialog; type Tcontrolminimos = class(TForm) DBGrid1: TDBGrid; qminimos: TZReadOnlyQuery; qminimosid: TIntegerField; qminimoscodigo: TWideStringField; qminimosdescripcion: TWideStringField; qminimosstock: TFloatField; qminimosstock_minimo: TFloatField; DataSource1: TDataSource; qactualizar_stocks: TZQuery; Panel1: TPanel; Button3: TButton; btaimprimir: TButton; dbinfstock: TfrxDBDataset; infstock: TfrxReport; frxPDFExport1: TfrxPDFExport; procedure FormShow(Sender: TObject); procedure btaimprimirClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var controlminimos: Tcontrolminimos; implementation {$R *.dfm} procedure Tcontrolminimos.btaimprimirClick(Sender: TObject); var fecha:string; dia,mes,anyo:word; begin if (qminimos.RecordCount>0) and (qminimos.State in [dsbrowse]) then begin infstock.DataSet:=dbinfstock; infstock.Report.Clear; infstock.LoadFromFile('c:\agrigest\informes\listadostocksminimos.fr3'); infstock.ShowReport(); end; end; procedure Tcontrolminimos.FormShow(Sender: TObject); begin qactualizar_stocks.ExecSQL; qminimos.Open; end; end. ======================================== FICHERO: fcontrolproduccion.pas ======================================== unit fcontrolproduccion; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZDataset, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, frxClass,frxDBSet,Excel2000, ComObj, Vcl.DBCtrls, frxExportCSV, frxExportPDF, frxExportBaseDialog; type Tcontrolproduccion = class(TForm) Panel1: TPanel; Panel4: TPanel; btimprimir: TButton; btexcel: TButton; Button1: TButton; Panel3: TPanel; Label1: TLabel; Label3: TLabel; Label4: TLabel; fdesde: TDateTimePicker; comboarticulos: TDBLookupComboBox; controlproduccion: TRadioGroup; chkarticulos: TRadioButton; Panel2: TPanel; DBGrid1: TDBGrid; qarticulos: TZReadOnlyQuery; dsarticulos: TDataSource; dsqentradas: TDataSource; qentradas: TZReadOnlyQuery; informes: TfrxReport; informedb: TfrxDBDataset; qentradasid: TLargeintField; qentradasfecha: TDateField; qentradashora: TTimeField; qentradasmesa: TWideStringField; qentradasbascula: TWideStringField; qentradasidt: TIntegerField; qentradasembasadora: TWideStringField; qentradasmateria_prima: TWideStringField; qentradasproducto: TWideStringField; qentradastara: TFloatField; qentradaspeso_teorico: TFloatField; qentradaspeso_real: TFloatField; qentradasdescripcion: TWideStringField; frxPDFExport1: TfrxPDFExport; frxCSVExport1: TfrxCSVExport; qarticuloscodigo: TWideStringField; qarticulosdescripcion: TWideStringField; SaveDialog1: TSaveDialog; Label2: TLabel; fhasta: TDateTimePicker; RadioButton1: TRadioButton; Panel120: TPanel; Button43: TButton; Panel130: TPanel; Panel121: TPanel; Button44: TButton; Panel141: TPanel; DBGrid62: TDBGrid; qentradas2: TZReadOnlyQuery; qsalidas2: TZReadOnlyQuery; dsqentradas2: TDataSource; dsqsalidas2: TDataSource; Panel5: TPanel; DBGrid63: TDBGrid; Panel6: TPanel; qentradas2fechatrabajo: TDateField; qentradas2lote: TIntegerField; qentradas2origen: TWideStringField; qentradas2mprima: TWideStringField; qentradas2num_palets: TLargeintField; qentradas2envases: TLargeintField; qentradas2pesoneto: TFloatField; qentradas2peso_neto_venta: TFloatField; qentradas2iddestino: TIntegerField; qsalidas2fecha: TDateField; qsalidas2lote: TIntegerField; qsalidas2id_envase: TWideStringField; qsalidas2num_palets: TLargeintField; qsalidas2num_envases: TLargeintField; qsalidas2peso_neto: TFloatField; qsalidas2peso_neto_venta: TFloatField; qsalidas2idorigen: TIntegerField; qentradas2DESTINO: TWideStringField; qsalidas2ORIGEN: TWideStringField; procedure DBGrid1TitleClick(Column: TColumn); procedure chkarticulosClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btimprimirClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure btexcelClick(Sender: TObject); procedure fdesdeChange(Sender: TObject); procedure RadioButton1Click(Sender: TObject); procedure Button43Click(Sender: TObject); procedure Button44Click(Sender: TObject); private { Private declarations } public { Public declarations } procedure ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar = nil); end; var controlproduccion: Tcontrolproduccion; implementation {$R *.dfm} procedure Tcontrolproduccion.ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar); 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 // 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 Tcontrolproduccion.fdesdeChange(Sender: TObject); begin qarticulos.Close; qarticulos.Prepare; qarticulos.ParamByName('PDESDE').AsDate:=fdesde.Date; qarticulos.ParamByName('PHASTA').AsDate:=fhasta.Date; qarticulos.Open; qentradas2.Close; qentradas2.Prepare; qentradas2.ParamByName('PDESDE').AsDate:=fdesde.Date; qentradas2.ParamByName('PHASTA').AsDate:=fhasta.Date; qentradas2.Open; qsalidas2.Close; qsalidas2.Prepare; qsalidas2.ParamByName('PDESDE').AsDate:=fdesde.Date; qsalidas2.ParamByName('PHASTA').AsDate:=fhasta.Date; qsalidas2.Open; end; procedure Tcontrolproduccion.btexcelClick(Sender: TObject); var archivo:string; begin savedialog1.FileName:='ENTRADAS DE MATERIALES.xls'; savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'ENTRADAS',DBGRID1); finally showmessage('Los datos han sido exportados correctamente a '+archivo); end; end; procedure Tcontrolproduccion.btimprimirClick(Sender: TObject); begin informedb.Datasource:=dsqentradas; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\infcontrolproduccion.fr3'); informes.Variables.Variables['TITULO']:=QUOTEDSTR('Control de producción de Almacen a fecha: '+datetostr(fdesde.date)); informes.ShowReport(); informes.Clear end; procedure Tcontrolproduccion.Button1Click(Sender: TObject); var dia,mes,anyo:word; tdia,tmes,tanyo,tfdesde:string; begin decodedate(fdesde.Date,anyo,mes,dia); tfdesde:=''''+inttostr(anyo)+'/'+inttostr(mes)+'/'+inttostr(dia)+''''; qentradas.Close; qentradas.Prepare; qentradas.ParamByName('PDESDE').AsDate:=fdesde.Date; qentradas.ParamByName('PHASTA').AsDate:=fhasta.Date; qentradas.ParamByName('PPRODUCTO').Asstring:=qarticuloscodigo.AsString; qentradas.open; { qentradas.SQL.Clear; qentradas.SQL.Add('select p.*,pr.descripcion from produccion p,productos pr where p.producto=pr.codigo and fecha='+tfdesde+' and p.producto='+''''+qarticuloscodigo.AsString+''''); qentradas.SQL.Add(' order by fecha desc, hora desc'); qentradas.open;} end; procedure Tcontrolproduccion.Button43Click(Sender: TObject); var archivo:string; begin savedialog1.FileName:=stringreplace(('ENTRADAS.xlsx'),'/','-',[rfreplaceall]); savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'entradas',DBGRID63); finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure Tcontrolproduccion.Button44Click(Sender: TObject); var archivo:string; begin savedialog1.FileName:=stringreplace(('SALIDAS.xlsx'),'/','-',[rfreplaceall]); savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'entradas',DBGRID62); finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure Tcontrolproduccion.chkarticulosClick(Sender: TObject); begin comboarticulos.Visible:=true; panel5.Visible:=false; panel6.Visible:=true; panel6.BringToFront; panel4.Visible:=true; end; procedure Tcontrolproduccion.DBGrid1TitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=qentradas.SortType; qentradas.SortedFields:=Column.FieldName; If st = stAscending then qentradas.SortType:=stDescending else qentradas.SortType:=stAscending; dsqentradas.DataSet.First; end; procedure Tcontrolproduccion.FormShow(Sender: TObject); begin qentradas.Close; qarticulos.Close; fdesde.Date:=date(); fhasta.Date:=date(); end; procedure Tcontrolproduccion.RadioButton1Click(Sender: TObject); begin panel6.Visible:=false; panel5.Visible:=true; panel5.BringToFront; comboarticulos.Visible:=false; panel4.Visible:=false; end; end. ======================================== FICHERO: fcontrolstock.pas ======================================== unit fcontrolstock; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, Vcl.DBCtrls,datos, Vcl.Mask, Vcl.Grids, Vcl.DBGrids, Vcl.ComCtrls, frxClass, frxDBSet, ComObj, Excel2000, frxExportPDF, frxExportBaseDialog; type Tcontrolstock = class(TForm) Panel1: TPanel; Panel2: TPanel; DBGrid1: TDBGrid; SaveDialog1: TSaveDialog; Button3: TButton; btAnuevo: TButton; btaimprimir: TButton; btAguardar: TButton; qstockdetalle: TZQuery; qstockdetalleide: TIntegerField; qstockdetallefecha: TDateField; qstockdetallecodigo: TWideStringField; qstockdetalledescripcion: TWideStringField; qstockdetallestock: TFloatField; qstockdetallestock_real: TFloatField; gridstocks: TDBGrid; qstock: TZQuery; dsqstockdetalle: TDataSource; dsqstock: TDataSource; qstockide: TIntegerField; qstockfecha: TDateField; qstockregularizado: TIntegerField; frxPDFExport1: TfrxPDFExport; dbinfstock: TfrxDBDataset; infstock: TfrxReport; DBEdit1: TDBEdit; btAmodificar: TButton; btAborrar: TButton; btAcancelar: TButton; Label5: TLabel; qentradasdetalle: TZQuery; btregularizar: TButton; DBCheckBox1: TDBCheckBox; qaux2: TZQuery; qauxentradas: TZQuery; qauxentradasdetalle: TZQuery; qauxentradasid: TIntegerField; qauxentradasidempresa: TIntegerField; qauxentradasidproveedor: TIntegerField; qauxentradasfecha: TDateField; qauxentradasdocumento: TWideStringField; qauxentradasbase: TFloatField; qauxentradastotaliva: TFloatField; qauxentradastotalentrada: TFloatField; qauxentradasdetalleid: TIntegerField; qauxentradasdetalleidempresa: TIntegerField; qauxentradasdetalleidentrada: TIntegerField; qauxentradasdetalleidproveedor: TIntegerField; qauxentradasdetallecodigo: TWideStringField; qauxentradasdetalleid_propio: TWideStringField; qauxentradasdetalledescripcion: TWideStringField; qauxentradasdetallelote: TWideStringField; qauxentradasdetallecantidad: TFloatField; qauxentradasdetallestock: TFloatField; qauxentradasdetalleprecio: TFloatField; qauxentradasdetalletipo_iva: TIntegerField; qauxentradasdetallebase: TFloatField; qauxentradasdetalletotal: TFloatField; qstockdetallefamilia: TWideStringField; qfamilias: TZReadOnlyQuery; dsqfamilias: TDataSource; combofamilia: TDBLookupComboBox; Label1: TLabel; qfamiliasidempresa: TIntegerField; qfamiliasid: TIntegerField; qfamiliasdescripcion: TWideStringField; qfamiliasactivo: TIntegerField; qaux: TZQuery; qupdateentradasdetalle: TZQuery; qupdate0entradasdetalle: TZQuery; qdetalle: TZQuery; qentradas2: TZQuery; qentradas2id: TIntegerField; qentradas2idempresa: TIntegerField; qentradas2fecha: TDateField; chkactivos: TCheckBox; qentradasdetalleid: TIntegerField; qentradasdetalleidempresa: TIntegerField; qentradasdetalleidentrada: TIntegerField; qentradasdetalleidproveedor: TIntegerField; qentradasdetallecodigo: TWideStringField; qentradasdetalleid_propio: TWideStringField; qentradasdetalledescripcion: TWideStringField; qentradasdetallelote: TWideStringField; qentradasdetallecantidad: TFloatField; qentradasdetallestock: TFloatField; qentradasdetalleprecio: TFloatField; qentradasdetalletipo_iva: TIntegerField; qentradasdetallebase: TFloatField; qentradasdetalletotal: TFloatField; qentradasdetallefecha: TDateField; qdetalleid: TIntegerField; qdetalleidempresa: TIntegerField; qdetalleidentrada: TIntegerField; qdetalleidproveedor: TIntegerField; qdetallecodigo: TWideStringField; qdetalleid_propio: TWideStringField; qdetalledescripcion: TWideStringField; qdetallelote: TWideStringField; qdetallecantidad: TFloatField; qdetallestock: TFloatField; qdetalleprecio: TFloatField; qdetalletipo_iva: TIntegerField; qdetallebase: TFloatField; qdetalletotal: TFloatField; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure dsqstockStateChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure btAnuevoClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure dsqstockDataChange(Sender: TObject; Field: TField); procedure btaimprimirClick(Sender: TObject); procedure Button3Click(Sender: TObject); procedure btregularizarClick(Sender: TObject); procedure dsqfamiliasDataChange(Sender: TObject; Field: TField); procedure combofamiliaClick(Sender: TObject); procedure chkactivosClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar = nil); end; var controlstock: Tcontrolstock; implementation {$R *.dfm} procedure Tcontrolstock.ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar); 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 // 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 Tcontrolstock.btAborrarClick(Sender: TObject); begin qstock.delete; end; procedure Tcontrolstock.btAcancelarClick(Sender: TObject); begin qstock.Cancel; end; procedure Tcontrolstock.btAguardarClick(Sender: TObject); var fecha,tanyo,tmes,tdia:string; anyo,mes,dia:word; begin qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('update articulosf af set stock=(select sum(stock) as stock from entradas_detalle where id_propio=af.codigo and idempresa=af.idempresa group by id_propio )'); qaux.ExecSQL; if qstock.State in [dsinsert] then begin qstockregularizado.Value:=0; qstock.Post; decodedate(qstockfecha.AsDateTime,anyo,mes,dia); fecha:=''''+floattostr(anyo)+'/'+floattostr(mes)+'/'+floattostr(dia)+''''; qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('insert into control_stock_detalle select a.idempresa,'+fecha+',codigo,a.descripcion,sum(stock),0,f.descripcion from articulosf a, familias f where a.idempresa=f.idempresa and f.id=a.familia and a.activo=1 and inventariable=1 group by codigo'); qaux.execsql; qstockdetalle.Close; qstockdetalle.Open; end; if qstock.State in [dsedit] then begin qstock.Post; decodedate(qstockfecha.AsDateTime,anyo,mes,dia); fecha:=''''+floattostr(anyo)+'/'+floattostr(mes)+'/'+floattostr(dia)+''''; qstockdetalle.Close; qstockdetalle.Open; end; qstock.Refresh; end; procedure Tcontrolstock.btaimprimirClick(Sender: TObject); var fecha:string; dia,mes,anyo:word; begin if (qstock.RecordCount>0) and (qstock.State in [dsbrowse]) then begin { decodedate(qstockfecha.AsDateTime,anyo,mes,dia); fecha:=''''+floattostr(anyo)+'/'+floattostr(mes)+'/'+floattostr(dia)+''''; qstockdetalle.Close; qstockdetalle.SQL.Clear; qstockdetalle.SQL.Add('select * from control_stock_detalle where ide='+qstockide.asstring+' and fecha='+fecha+' order by fecha desc,familia,descripcion'); qstockdetalle.open;} end; infstock.DataSet:=dbinfstock; infstock.Report.Clear; infstock.LoadFromFile('c:\agrigest\informes\listadodestocks.fr3'); fecha:=qstockfecha.AsString; infstock.Variables.Variables['FECHA']:=QUOTEDSTR(fecha); infstock.ShowReport(); end; procedure Tcontrolstock.btAnuevoClick(Sender: TObject); begin qstock.Append; qstockide.Value:=dm.tempresaid.AsInteger; qstockfecha.Value:=date(); dbedit1.SetFocus; end; procedure Tcontrolstock.btregularizarClick(Sender: TObject); var cantidad,resto:real; fecha,empresa,codigo:string; dia,mes,anyo:word; begin try while not qstockdetalle.eof do begin //while 1 //decodedate(qstockdetallefecha.AsDateTime,anyo,mes,dia); fecha:='2100-01-01';//''''+floattostr(anyo)+'-'+floattostr(mes)+'-'+floattostr(dia)+''''; resto:=qstockdetallestock_real.AsFloat; empresa:=qstockdetalleide.asstring; qentradasdetalle.Close; qentradasdetalle.Prepare; qentradasdetalle.ParamByName('EMPRESA').AsInteger:=qstockdetalleide.asinteger; qentradasdetalle.ParamByName('ARTICULO').Asstring:=qstockdetallecodigo.asstring; qentradasdetalle.ParamByName('FECHA').AsSTRING:=fecha; qentradasdetalle.Open; { qaux.Close; qaux.sql.Clear; qaux.sql.Add('select * from entradas_detalle where id_propio='+''''+qstockdetallecodigo.asstring+''''+' and idempresa='+qstockdetalleide.asstring+' order by id desc'); qaux.open; if qaux.RecordCount>0 then // if 1} if qentradasdetalle.RecordCount>0 then //if 1 begin //1 decodedate(qstockdetallefecha.AsDateTime,anyo,mes,dia); fecha:=''''+floattostr(anyo)+'-'+floattostr(mes)+'-'+floattostr(dia)+''''; qupdateentradasdetalle.close; qupdateentradasdetalle.Prepare; qupdateentradasdetalle.ParamByName('EMPRESA').AsInteger:=qstockdetalleide.asinteger; qupdateentradasdetalle.ParamByName('ARTICULO').Asstring:=qstockdetallecodigo.asstring; qupdateentradasdetalle.ParamByName('FECHA').Asdate:=qstockdetallefecha.AsDateTime; qupdateentradasdetalle.ExecSQL; qupdate0entradasdetalle.close; qupdate0entradasdetalle.Prepare; qupdate0entradasdetalle.ParamByName('EMPRESA').AsInteger:=qstockdetalleide.asinteger; qupdate0entradasdetalle.ParamByName('ARTICULO').Asstring:=qstockdetallecodigo.asstring; qupdate0entradasdetalle.ParamByName('FECHA').Asdate:=qstockdetallefecha.AsDateTime; qupdate0entradasdetalle.ExecSQL; qentradasdetalle.Close; qentradasdetalle.Prepare; qentradasdetalle.ParamByName('EMPRESA').AsInteger:=qstockdetalleide.asinteger; qentradasdetalle.ParamByName('ARTICULO').Asstring:=qstockdetallecodigo.asstring; qentradasdetalle.ParamByName('FECHA').Asdate:=qstockdetallefecha.AsDateTime; qentradasdetalle.Open; end; //1 if resto<0 then begin //2 qdetalle.Close; qdetalle.Prepare; qdetalle.ParamByName('EMPRESA').AsInteger:=qentradasdetalleidempresa.AsInteger; qdetalle.ParamByName('ID').AsInteger:=qentradasdetalleid.AsInteger; qdetalle.Open; qdetalle.edit; qdetallestock.Value:=resto; qdetalle.post; resto:=0; end; //2 if resto>0 then begin //3 while resto>0 do // while 2 begin qdetalle.Close; qdetalle.Prepare; qdetalle.ParamByName('EMPRESA').AsInteger:=qentradasdetalleidempresa.AsInteger; qdetalle.ParamByName('ID').AsInteger:=qentradasdetalleid.AsInteger; qdetalle.Open; if qdetallecantidad.AsFloat>=resto then begin //4 if not qentradasdetalle.Eof then begin //5 qdetalle.edit; qdetallestock.Value:=resto; qdetalle.post; resto:=0; end else //5 begin //6 qdetalle.edit; qdetallestock.Value:=qdetallestock.asfloat+resto; qdetalle.post; resto:=0; end; //6 end; //4 if qdetallecantidad.asfloat<=resto then begin //7 if not qentradasdetalle.Eof then begin //8 qdetalle.edit; resto:=resto-qdetallecantidad.asfloat; qdetallestock.Value:=qdetallecantidad.asfloat; qdetalle.post; end else //8 begin //9 qdetalle.edit; qdetallestock.Value:=resto; qdetalle.post; resto:=0; end; //9 end; //7 qentradasdetalle.Next; end; // while 2 end;//3 if qentradasdetalle.RecordCount=0 then begin //10 decodedate(qstockfecha.AsDateTime,anyo,mes,dia); fecha:=''''+floattostr(anyo)+'/'+floattostr(mes)+'/'+floattostr(dia)+''''; qaux2.close; qaux2.SQL.Clear; qaux2.SQL.Add('select * from entradas where idproveedor=0 and fecha='+fecha+' and idempresa='+empresa); qaux2.Open; if qaux2.RecordCount=0 then begin //11 qauxentradas.Open; qauxentradas.Append; qauxentradasidempresa.Value:=dm.tempresaid.asinteger; qauxentradasidproveedor.Value:=0; qauxentradasfecha.Value:=qstockfecha.AsDateTime; qauxentradasdocumento.Value:='INV.'+qstockfecha.AsSTRING; qauxentradas.Post; end else //11 begin //12 qauxentradas.Open; qauxentradas.Locate('documento','INV.'+fecha,[locaseinsensitive]); end; //12 qauxentradasdetalle.Open; qauxentradasdetalle.Append; qauxentradasdetalleidempresa.Value:=qauxentradasidempresa.AsInteger; qauxentradasdetalleidentrada.Value:=qauxentradasid.AsInteger; qauxentradasdetalleidproveedor.Value:=qauxentradasidproveedor.AsInteger; qauxentradasdetallecodigo.Value:=qstockdetallecodigo.asstring; qauxentradasdetalleid_propio.Value:=qstockdetallecodigo.asstring; qauxentradasdetalledescripcion.Value:=qstockdetalledescripcion.asstring; qauxentradasdetallecantidad.Value:=qstockdetallestock_real.asfloat; qauxentradasdetallestock.Value:=qstockdetallestock_real.asfloat; qauxentradasdetalleprecio.Value:=0; qauxentradasdetalletipo_iva.Value:=0; qauxentradasdetalle.Post; end; //10 qstockdetalle.next; end; //while 1 if qstockdetalle.Eof then begin //13 qstock.Edit; qstockregularizado.Value:=1; qstock.post; qaux.SQL.Clear; qaux.SQL.Add('update articulosf af set stock=(select sum(stock) as stock from entradas_detalle where id_propio=af.codigo and idempresa=af.idempresa group by id_propio )'); qaux.ExecSQL; qaux.SQL.Clear; qaux.SQL.Add('update articulosf af set preciocoste=(SELECT SUM((SELECT PRECIO*STOCK FROM entradas_detalle WHERE ID=ed.id))/sum(stock) FROM `entradas_detalle` ed where id_propio=af.codigo) where idempresa=af.idempresa and codigo=af.codigo'); qaux.ExecSQL; qaux.SQL.Clear; qaux.SQL.Add('select * from articulosf where stock_minimo>stock and avisar_stock=1'); qaux.Open; end; //13 except showmessage('error en el codigo '+qstockdetallecodigo.AsString); end; end; procedure Tcontrolstock.Button3Click(Sender: TObject); var archivo:string; begin savedialog1.FileName:='INVENTARIO.xls'; savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'STOCK',gridstocks); finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure Tcontrolstock.chkactivosClick(Sender: TObject); var grupo,activos:string; begin if (qstock.RecordCount>0) and (qstock.State in [dsbrowse]) then begin if combofamilia.KeyValue=null then grupo:='%' else grupo:=combofamilia.KeyValue; if chkactivos.Checked then activos:='1' else activos:='%'; qstockdetalle.Close; qstockdetalle.Prepare; qstockdetalle.ParamByName('EMPRESA').AsInteger:=qstockide.AsInteger; qstockdetalle.ParamByName('FECHA').AsDate:=qstockfecha.AsDateTime; qstockdetalle.ParamByName('GRUPO').Asstring:=grupo; qstockdetalle.ParamByName('ACTIVO').Asstring:=activos; qstockdetalle.open; if qstockregularizado.asinteger=0 then btregularizar.Enabled:=true else btregularizar.Enabled:=false; end; if (qstock.RecordCount=0) then begin qstockdetalle.close; end; end; procedure Tcontrolstock.combofamiliaClick(Sender: TObject); begin combofamilia.KeyValue:=null; end; procedure Tcontrolstock.dsqfamiliasDataChange(Sender: TObject; Field: TField); var grupo:string; begin if combofamilia.KeyValue=null then grupo:='%' else grupo:=combofamilia.KeyValue; qstockdetalle.Close; qstockdetalle.Prepare; qstockdetalle.ParamByName('EMPRESA').AsInteger:=qstockide.AsInteger; qstockdetalle.ParamByName('FECHA').AsDate:=qstockfecha.AsDateTime; qstockdetalle.ParamByName('GRUPO').Asstring:=grupo; qstockdetalle.open; end; procedure Tcontrolstock.dsqstockDataChange(Sender: TObject; Field: TField); var grupo,activos:string; begin if (qstock.RecordCount>0) and (qstock.State in [dsbrowse]) then begin if combofamilia.KeyValue=null then grupo:='%' else grupo:=combofamilia.KeyValue; if chkactivos.Checked then activos:='1' else activos:='%'; qstockdetalle.Close; qstockdetalle.Prepare; qstockdetalle.ParamByName('EMPRESA').AsInteger:=qstockide.AsInteger; qstockdetalle.ParamByName('FECHA').AsDate:=qstockfecha.AsDateTime; qstockdetalle.ParamByName('GRUPO').Asstring:=grupo; qstockdetalle.ParamByName('ACTIVO').Asstring:=activos; qstockdetalle.open; if qstockregularizado.asinteger=0 then btregularizar.Enabled:=true else btregularizar.Enabled:=false; end; if (qstock.RecordCount=0) then begin qstockdetalle.close; end; end; procedure Tcontrolstock.dsqstockStateChange(Sender: TObject); begin if qstock.State in [dsedit,dsinsert] then begin btanuevo.Enabled:=false; btamodificar.Enabled:=false; btaborrar.Enabled:=false; btregularizar.Enabled:=false; btacancelar.Enabled:=true; btaguardar.Enabled:=true; end else begin btanuevo.Enabled:=true; btamodificar.Enabled:=true; btaborrar.Enabled:=true; btacancelar.Enabled:=false; btaguardar.Enabled:=false; end; end; procedure Tcontrolstock.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tcontrolstock.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbgrid) then begin key:=','; end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tcontrolstock.FormShow(Sender: TObject); begin dm.tempresa.open; qfamilias.Open; qstock.open; end; end. ======================================== FICHERO: fcostesrestos.pas ======================================== unit fcostesrestos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.Grids, Vcl.DBGrids; type Trestosdia = class(TForm) dsqcostesrestosdia: TDataSource; DBGrid1: TDBGrid; private { Private declarations } public { Public declarations } end; var restosdia: Trestosdia; implementation uses principal; {$R *.dfm} end. ======================================== FICHERO: fcrearalbaran.pas ======================================== unit fcrearalbaran; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZDataset, Vcl.StdCtrls, Vcl.Mask, Vcl.DBCtrls, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ComCtrls; type Tcrearalbaran = class(TForm) qtipoiva: TZReadOnlyQuery; qactualizarserie: TZReadOnlyQuery; qlineasalbaran: TZReadOnlyQuery; qinsertaralbaran: TZReadOnlyQuery; qdestinos: TZReadOnlyQuery; qclientes: TZReadOnlyQuery; DBGrid1: TDBGrid; Panel1: TPanel; comboserie: TDBLookupComboBox; Label1: TLabel; Label4: TLabel; Label5: TLabel; dsqseries: TDataSource; qseries: TZReadOnlyQuery; qserieside: TIntegerField; qseriesid: TWideStringField; qseriesfechainicio: TDateField; qseriesfechafin: TDateField; qseriesnum_pedcliente: TIntegerField; qseriesnum_albaran: TIntegerField; qseriesnum_factura: TIntegerField; qseriesnum_expedicion: TIntegerField; qseriesnum_pedproveedor: TIntegerField; qseriesimp_albaran: TWideStringField; qseriesimp_factura: TWideStringField; qseriesactivo: TIntegerField; qseriesnum_presupuesto: TIntegerField; qseriesseriecontable: TWideStringField; vfecha: TDateTimePicker; qclientesid: TIntegerField; qclientesIdempresa: TIntegerField; qclientesnif: TWideStringField; qclientesnombre: TWideStringField; qclientesnombre_corto: TWideStringField; qclientesdireccion: TWideStringField; qclientespoblacion: TWideStringField; qclientescodpost: TWideStringField; qclientesprovincia: TWideStringField; qclientestelefono: TWideStringField; qclientestelefono2: TWideStringField; qclientesmovil: TWideStringField; qclientesemail: TWideStringField; qclientespersonacontacto: TWideStringField; qclientescodigomercado: TIntegerField; qclientesactivo: TIntegerField; qclientesobservaciones: TWideStringField; qclientesccontable: TIntegerField; qclientesdescuento: TFloatField; qclientespais: TWideStringField; qclientesidformapago: TIntegerField; qclientesexento_iva: TIntegerField; qclientescomision: TFloatField; qclientesidcp: TIntegerField; qclientestipocliente: TWideStringField; qclientesusa_re: TIntegerField; qclientesean: TWideStringField; qdestinoscodigo: TWideStringField; qdestinosidcliente: TIntegerField; qdestinosidempresa: TIntegerField; qdestinosdescripcion: TWideStringField; qdestinosseleccionado: TIntegerField; qdestinosactivo: TIntegerField; qdestinosdireccion: TWideStringField; qdestinospoblacion: TWideStringField; qdestinoscodpost: TWideStringField; qdestinosprovincia: TWideStringField; qdestinospais: TWideStringField; qdestinosean: TWideStringField; Button1: TButton; Edit1: TEdit; qtipoivatipo: TIntegerField; dsqlineasalbaran: TDataSource; qlineasalbaranidempresa: TIntegerField; qlineasalbarandescripcion: TWideStringField; qlineasalbarancal: TWideStringField; qlineasalbaranlote: TIntegerField; qlineasalbaranbultos: TIntegerField; qlineasalbarancantidad: TFloatField; qlineasalbarandescuento: TWideStringField; qlineasalbarantotaldescuento: TWideStringField; qlineasalbaranbase: TWideStringField; qlineasalbaraniva: TWideStringField; qlineasalbarantotal: TWideStringField; qlineasalbaransscc: TWideStringField; qlineasalbaranidea: TIntegerField; qlineasalbaranpalets: TIntegerField; qpalets: TZReadOnlyQuery; qpaletspalets: TLargeintField; qinsertarlineasalbaran: TZReadOnlyQuery; qactualizaridnumalbaran: TZReadOnlyQuery; qactualizarlinpedidonumalbaran: TZReadOnlyQuery; qactualizaralbaran: TZReadOnlyQuery; qtotalesalbaran: TZReadOnlyQuery; qtotalesalbaranpesobruto: TFloatField; qtotalesalbaranpesoneto: TFloatField; qtotalesalbaranpesonetoteorico: TFloatField; qtotalesalbarannumpalets: TLargeintField; qlineasalbaranprecio: TFloatField; qlineaspedido: TZReadOnlyQuery; dsqlineaspedido: TDataSource; qlineaspedidoidempresa: TIntegerField; qlineaspedidopalets: TIntegerField; qlineaspedidoidea: TWideStringField; qlineaspedidodescripcion: TWideStringField; qlineaspedidocal: TWideStringField; qlineaspedidolote: TWideStringField; qlineaspedidobultos: TFloatField; qlineaspedidocantidad: TFloatField; qlineaspedidoprecio: TFloatField; qlineaspedidodescuento: TWideStringField; qlineaspedidototaldescuento: TWideStringField; qlineaspedidobase: TWideStringField; qlineaspedidotipoiva: TWideStringField; qlineaspedidoiva: TWideStringField; qlineaspedidototal: TWideStringField; qlineaspedidosscc: TWideStringField; qlineaspedidopesobruto: TFloatField; qlineasalbarantipoiva: TWideStringField; qlineasalbaranidalbaran: TWideStringField; qlineasalbaranidfactura: TWideStringField; qlineasalbaranpeso_bruto: TFloatField; qtotalespedido: TZReadOnlyQuery; qtotalespedidopesobruto: TFloatField; qtotalespedidopesoneto: TFloatField; qtotalespedidopesonetoteorico: TFloatField; qtotalespedidonumpalets: TFloatField; qlineaspedidodesc_envase: TWideStringField; qlineaspedidoref: TWideStringField; qlineaspedidoean: TWideStringField; qlineaspedidodesc_pais: TWideStringField; qlineaspedidounidadescaja: TIntegerField; insertarlotes: TZReadOnlyQuery; insertarpalets: TZReadOnlyQuery; qlineaspedidoidalbaran: TWideStringField; qlineaspedidoidfactura: TWideStringField; qlineaspedidoid: TIntegerField; borrarlineaalbaran: TZReadOnlyQuery; procedure FormShow(Sender: TObject); procedure Button1Click(Sender: TObject); procedure dsqseriesDataChange(Sender: TObject; Field: TField); private { Private declarations } public { Public declarations } var vidempresa,vidcliente,vpedido:integer; viddestino:string; end; var crearalbaran: Tcrearalbaran; implementation {$R *.dfm} uses fpedidos; procedure Tcrearalbaran.Button1Click(Sender: TObject); var vsscc,albaran:string; vpalets,num_palet,posicion,id:integer; begin try if qlineaspedidoidalbaran.AsString='' then begin albaran:=edit1.Text; qinsertaralbaran.Prepare; qinsertaralbaran.ParamByName('serie').AsString:=qseriesid.AsString; qinsertaralbaran.ParamByName('id').Asinteger:=strtoint(albaran); qinsertaralbaran.ParamByName('idempresa').Asinteger:=vidempresa; qinsertaralbaran.ParamByName('iddestino').Asstring:=viddestino; qinsertaralbaran.ParamByName('idcliente').Asinteger:=vidcliente; qinsertaralbaran.ParamByName('nif').AsString:=qclientesnif.AsString; qinsertaralbaran.ParamByName('direccion').AsString:=qclientesdireccion.AsString; qinsertaralbaran.ParamByName('poblacion').AsString:=qclientespoblacion.AsString; qinsertaralbaran.ParamByName('provincia').AsString:=qclientesprovincia.AsString; qinsertaralbaran.ParamByName('codpost').AsString:=qclientescodpost.AsString; qinsertaralbaran.ParamByName('fecha').Asdate:=pedidos.dtpedidosfecha_carga.AsDateTime;//vfecha.Date; qinsertaralbaran.ParamByName('nomcliente').AsString:=qclientesnombre.AsString; qinsertaralbaran.ParamByName('paiscliente').AsString:=qclientespais.AsString; qinsertaralbaran.ParamByName('nomdestino').AsString:=qdestinosdescripcion.asstring; qinsertaralbaran.ParamByName('direcciondestino').AsString:=qdestinosdireccion.asstring; qinsertaralbaran.ParamByName('poblaciondestino').AsString:=qdestinospoblacion.asstring; qinsertaralbaran.ParamByName('codpostdestino').AsString:=qdestinoscodpost.asstring; qinsertaralbaran.ParamByName('provinciadestino').AsString:=qdestinosprovincia.asstring; qinsertaralbaran.ParamByName('paisdestino').AsString:=qdestinospais.asstring; qinsertaralbaran.ParamByName('pedido').AsString:=pedidos.dtpedidospedidocliente.asstring; qinsertaralbaran.ExecSQL; end else begin albaran:=qlineaspedidoidalbaran.AsString; posicion:= pos('/',albaran); if posicion>0 then begin albaran:= copy(albaran,posicion +1 ,length(albaran)); end; end; finally if qseriesnum_albaran.AsInteger=strtoint(albaran) then begin qactualizarserie.Prepare; qactualizarserie.ParamByName('IDEMPRESA').AsInteger:=qserieside.Asinteger; qactualizarserie.ParamByName('IDSERIE').Asstring:=qseriesid.AsString; qactualizarserie.ExecSQL; end; end; try qpalets.Prepare; qpalets.ParamByName('IDEMPRESA').AsInteger:=vidempresa; qpalets.ParamByName('IDPEDIDO').AsInteger:=vpedido; qpalets.Open; num_palet:=1; vpalets:=qpaletspalets.asinteger; vsscc:=qlineasalbaransscc.AsString; if qlineasalbaran.RecordCount>0 then begin id:=0; while not qlineasalbaran.Eof do begin qinsertarlineasalbaran.Prepare; qinsertarlineasalbaran.ParamByName('vserie').AsString:=qseriesid.AsString; qinsertarlineasalbaran.ParamByName('vidempresa').Asinteger:=vidempresa; qinsertarlineasalbaran.ParamByName('vidalbaran').Asinteger:=strtoint(albaran); qinsertarlineasalbaran.ParamByName('vidarticulo').Asinteger:=qlineasalbaranidea.AsInteger; qinsertarlineasalbaran.ParamByName('vdescripcion').AsString:=qlineasalbarandescripcion.Asstring; qinsertarlineasalbaran.ParamByName('vcal').AsString:=qlineasalbarancal.Asstring; qinsertarlineasalbaran.ParamByName('vlote').AsString:=qlineasalbaranlote.Asstring; if vsscc<>qlineasalbaransscc.AsString then begin num_palet:=num_palet+1; vsscc:=qlineasalbaransscc.AsString; end; qinsertarlineasalbaran.ParamByName('vpalets').Asinteger:=num_palet; if id<>qlineasalbaranidea.AsInteger then begin qinsertarlineasalbaran.ParamByName('vbultos').Asinteger:=qlineasalbaranbultos.Asinteger; end else qinsertarlineasalbaran.ParamByName('vbultos').Asinteger:=0; qinsertarlineasalbaran.ParamByName('vcantidad').asfloat:=qlineasalbarancantidad.Asfloat; qinsertarlineasalbaran.ParamByName('vpesobruto').asfloat:=qlineasalbaranpeso_bruto.Asfloat; qinsertarlineasalbaran.ParamByName('vprecio').Asfloat:=qlineasalbaranprecio.Asfloat; qinsertarlineasalbaran.ParamByName('vdescuento').Asfloat:=0; qinsertarlineasalbaran.ParamByName('vtotaldescuento').Asfloat:=0; qinsertarlineasalbaran.ParamByName('vbase').Asfloat:=qlineasalbarancantidad.Asfloat*qlineasalbaranprecio.Asfloat; qinsertarlineasalbaran.ParamByName('vtipoiva').Asfloat:=21; qinsertarlineasalbaran.ParamByName('viva').Asfloat:=(qlineasalbarancantidad.Asfloat*qlineasalbaranprecio.Asfloat)*(1+(21/100)); qinsertarlineasalbaran.ParamByName('vtotal').Asfloat:=qlineasalbarancantidad.Asfloat*qlineasalbaranprecio.Asfloat; qinsertarlineasalbaran.ParamByName('venvase').Asstring:=''; qinsertarlineasalbaran.ParamByName('vreferencia').Asstring:=''; qinsertarlineasalbaran.ParamByName('vean').Asstring:=''; qinsertarlineasalbaran.ParamByName('vpais').Asstring:=''; qinsertarlineasalbaran.ParamByName('vunidadescaja').AsInteger:=0; qinsertarlineasalbaran.ExecSQL; id:=qlineasalbaranidea.AsInteger; qlineasalbaran.Next; end; qlineaspedido.First; while not qlineaspedido.Eof do begin borrarlineaalbaran.prepare; borrarlineaalbaran.ParamByName('serie').AsString:=qseriesid.AsString; borrarlineaalbaran.ParamByName('albaran').AsInteger:=strtoint(albaran); borrarlineaalbaran.ParamByName('id').Asstring:=qlineaspedidoid.AsString; borrarlineaalbaran.execsql; qlineaspedido.Next; end; end; if qlineasalbaran.RecordCount=0 then begin while not qlineaspedido.Eof do begin qinsertarlineasalbaran.Prepare; qinsertarlineasalbaran.ParamByName('vserie').AsString:=qseriesid.AsString; qinsertarlineasalbaran.ParamByName('vidempresa').Asinteger:=vidempresa; qinsertarlineasalbaran.ParamByName('vidalbaran').Asinteger:=strtoint(albaran); qinsertarlineasalbaran.ParamByName('vidarticulo').Asinteger:=qlineaspedidoid.AsInteger; qinsertarlineasalbaran.ParamByName('vdescripcion').AsString:=qlineaspedidodescripcion.Asstring; qinsertarlineasalbaran.ParamByName('vcal').AsString:=''; qinsertarlineasalbaran.ParamByName('vlote').AsString:=''; if vsscc<>qlineaspedidosscc.AsString then begin num_palet:=num_palet+1; vsscc:=qlineaspedidosscc.AsString; end; qinsertarlineasalbaran.ParamByName('vpalets').Asinteger:=qlineaspedidopalets.Asinteger; qinsertarlineasalbaran.ParamByName('vbultos').Asinteger:=qlineaspedidobultos.Asinteger; qinsertarlineasalbaran.ParamByName('vcantidad').asfloat:=qlineaspedidocantidad.Asfloat; qinsertarlineasalbaran.ParamByName('vpesobruto').asfloat:=qlineaspedidopesobruto.Asfloat+qlineaspedidocantidad.Asfloat; qinsertarlineasalbaran.ParamByName('vprecio').Asfloat:=qlineaspedidoprecio.Asfloat; qinsertarlineasalbaran.ParamByName('vdescuento').Asfloat:=0; qinsertarlineasalbaran.ParamByName('vtotaldescuento').Asfloat:=0; qinsertarlineasalbaran.ParamByName('vbase').Asfloat:=qlineaspedidocantidad.Asfloat*qlineaspedidoprecio.Asfloat; qinsertarlineasalbaran.ParamByName('vtipoiva').Asfloat:=0; qinsertarlineasalbaran.ParamByName('viva').Asfloat:=0; qinsertarlineasalbaran.ParamByName('vtotal').Asfloat:=qlineaspedidocantidad.Asfloat*qlineaspedidoprecio.Asfloat; qinsertarlineasalbaran.ParamByName('venvase').Asstring:=qlineaspedidodesc_envase.asstring; qinsertarlineasalbaran.ParamByName('vreferencia').Asstring:=qlineaspedidoref.asstring; qinsertarlineasalbaran.ParamByName('vean').Asstring:=qlineaspedidoean.Asstring; qinsertarlineasalbaran.ParamByName('vpais').Asstring:=qlineaspedidodesc_pais.asstring; qinsertarlineasalbaran.ParamByName('vunidadescaja').AsInteger:=qlineaspedidounidadescaja.asInteger; qinsertarlineasalbaran.ExecSQL; qlineaspedido.Next; end; end; finally qpalets.Close; qactualizaridnumalbaran.Prepare; qactualizaridnumalbaran.ParamByName('IDALBARAN').AsString:=qseriesid.AsString+'/'+albaran; qactualizaridnumalbaran.ParamByName('PEDIDO').AsInteger:=vpedido; qactualizaridnumalbaran.ExecSQL; qactualizarlinpedidonumalbaran.Prepare; qactualizarlinpedidonumalbaran.ParamByName('IDALBARAN').AsString:=qseriesid.AsString+'/'+albaran; qactualizarlinpedidonumalbaran.ParamByName('PEDIDO').AsInteger:=vpedido; qactualizarlinpedidonumalbaran.ExecSQL; if qlineasalbaran.RecordCount>0 then begin qtotalesalbaran.Close; qtotalesalbaran.Prepare; qtotalesalbaran.ParamByName('albaran').AsString:=qseriesid.AsString+'/'+albaran; qtotalesalbaran.ParamByName('empresa').AsInteger:=vidempresa; qtotalesalbaran.Open; qactualizaralbaran.Prepare; qactualizaralbaran.ParamByName('pesobruto').AsFloat:=qtotalesalbaranpesobruto.asfloat; qactualizaralbaran.ParamByName('kilos').AsFloat:=qtotalesalbaranpesoneto.asfloat; qactualizaralbaran.ParamByName('kilosventa').AsFloat:=qtotalesalbaranpesonetoteorico.asfloat; qactualizaralbaran.ParamByName('numpalets').Asinteger:=qtotalesalbarannumpalets.asinteger; qactualizaralbaran.ParamByName('serie').Asstring:=qseriesid.AsString; qactualizaralbaran.ParamByName('albaran').Asinteger:=strtoint(albaran); qactualizaralbaran.ParamByName('empresa').Asinteger:=vidempresa; qactualizaralbaran.ExecSQL; end; if qlineasalbaran.RecordCount=0 then begin qtotalespedido.Close; qtotalespedido.Prepare; qtotalespedido.ParamByName('serie').AsString:=qseriesid.AsString; qtotalespedido.ParamByName('albaran').AsString:=edit1.Text; qtotalespedido.ParamByName('empresa').AsInteger:=vidempresa; qtotalespedido.Open; qactualizaralbaran.Prepare; qactualizaralbaran.ParamByName('pesobruto').AsFloat:=qtotalespedidopesobruto.asfloat; qactualizaralbaran.ParamByName('kilos').AsFloat:=qtotalespedidopesoneto.asfloat; qactualizaralbaran.ParamByName('kilosventa').AsFloat:=qtotalespedidopesonetoteorico.asfloat; qactualizaralbaran.ParamByName('numpalets').Asinteger:=qtotalespedidonumpalets.asinteger; qactualizaralbaran.ParamByName('serie').Asstring:=qseriesid.AsString; qactualizaralbaran.ParamByName('albaran').Asinteger:=strtoint(albaran); qactualizaralbaran.ParamByName('empresa').Asinteger:=vidempresa; qactualizaralbaran.ExecSQL; end; end; if qlineasalbaran.RecordCount=0 then begin insertarlotes.Prepare; insertarlotes.ParamByName('serie').AsString:=qseriesid.AsString; insertarlotes.ParamByName('albaran').AsString:=albaran; insertarlotes.ParamByName('empresa').AsInteger:=vidempresa; insertarlotes.ExecSQL; insertarpalets.Prepare; insertarpalets.ParamByName('serie').AsString:=qseriesid.AsString; insertarpalets.ParamByName('albaran').AsString:=albaran; insertarpalets.ParamByName('empresa').AsInteger:=vidempresa; insertarpalets.ExecSQL; end; qlineasalbaran.Refresh; showmessage('EL ALBARAN '+QSERIESID.AsString+'/'+albaran+' HA SIDO CREADO CORRECTAMENTE'); end; procedure Tcrearalbaran.dsqseriesDataChange(Sender: TObject; Field: TField); begin edit1.Text:=qseriesnum_albaran.AsString; qlineasalbaran.Close; qlineasalbaran.Prepare; qlineasalbaran.ParamByName('PEDIDO').AsInteger:=vpedido; qlineasalbaran.Open; qlineaspedido.Close; qlineaspedido.Prepare; qlineaspedido.ParamByName('PEDIDO').AsInteger:=vpedido; qlineaspedido.Open; if qlineasalbaran.RecordCount=0 then begin dsqlineasalbaran.DataSet:=qlineaspedido; end; end; procedure Tcrearalbaran.FormShow(Sender: TObject); begin vfecha.Date:=date(); qseries.Prepare; qseries.ParamByName('IDEMPRESA').AsInteger:=vidempresa; qseries.Open; comboserie.KeyValue:=qseriesid.AsString; qclientes.Prepare; qclientes.ParamByName('IDEMPRESA').AsInteger:=vidempresa; qclientes.ParamByName('IDCLIENTE').AsInteger:=vidcliente; qclientes.Open; qdestinos.Prepare; qdestinos.ParamByName('IDEMPRESA').AsInteger:=vidempresa; qdestinos.ParamByName('IDCLIENTE').AsInteger:=vidcliente; qdestinos.ParamByName('IDDESTINO').Asstring:=viddestino; qdestinos.Open; qtipoiva.Prepare; qtipoiva.ParamByName('IDCLIENTE').AsInteger:=vidcliente; qtipoiva.Open; end; end. ======================================== FICHERO: fcuadernos.pas ======================================== unit fcuadernos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.DBCtrls, Vcl.ComCtrls, frxClass, frxDBSet, URLMon, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP,shellapi, Vcl.Mask; type Tcuadernos = class(TForm) dbempresa: TfrxDBDataset; dbtratamiento: TfrxDBDataset; dbtratamientosdetalle: TfrxDBDataset; gcrpagado: TDBCheckBox; informes: TfrxReport; qarticulo: TZQuery; qarticuloidempresa: TIntegerField; qarticuloidaf: TIntegerField; qarticulodescripcion: TWideStringField; qarticulopreciocoste: TFloatField; qarticuloidgrupo: TIntegerField; qarticuloidfamilia: TIntegerField; qarticulocodigo: TWideStringField; qarticuloregistro: TWideStringField; qaux: TZQuery; qaux2: TZReadOnlyQuery; qboquillas: TZReadOnlyQuery; qboquillasboquilla: TWideStringField; qcentrocoste: TZReadOnlyQuery; qcentrocosteempresa: TIntegerField; qcentrocostecodpar: TWideStringField; qcentrocostenombre: TWideStringField; qcentrocoste2: TZReadOnlyQuery; qcentrocoste2empresa: TIntegerField; qcentrocoste2codpar: TWideStringField; qcentrocoste2nombre: TWideStringField; qdepositos: TZReadOnlyQuery; qdepositosdeposito: TWideStringField; qmateriaprima: TZReadOnlyQuery; qmateriaprimadescripcion: TWideStringField; qmateriaprima2: TZReadOnlyQuery; qmateriaprima2descripcion: TWideStringField; qoperarios: TZReadOnlyQuery; qoperariosoperario: TWideStringField; qpresiones: TZReadOnlyQuery; qpresionespresion: TWideStringField; qresponsables: TZReadOnlyQuery; qresponsablesnif: TWideStringField; qresponsablesnombre: TWideStringField; qresponsablesfirma: TBlobField; qresponsables2: TZReadOnlyQuery; qresponsables2nif: TWideStringField; qresponsables2nombre: TWideStringField; qresponsables2firma: TBlobField; qstock: TZReadOnlyQuery; qstockid: TIntegerField; qstockidempresa: TIntegerField; qstocklote: TWideStringField; qstockfecha: TDateField; qtractores: TZReadOnlyQuery; qtractorestractor: TWideStringField; qtratamientos: TZQuery; qtratamientosdetalle: TZQuery; qvelocidad: TZReadOnlyQuery; qvelocidadvelocidad: TWideStringField; qventilador: TZReadOnlyQuery; qventiladorventilador: TWideStringField; qtratamientoside: TIntegerField; qtratamientosid: TIntegerField; qtratamientosfecha: TDateField; qtratamientosidcc: TWideStringField; qtratamientosdesc_cc: TWideStringField; qtratamientosresponsable: TWideStringField; qtratamientosidrecomendacion: TIntegerField; qtratamientoscontabilizado: TIntegerField; qtratamientosnif_responsable: TWideStringField; qtratamientosobservaciones: TWideStringField; qtratamientosoperario: TWideStringField; qtratamientosidjustificacion: TIntegerField; qtratamientoscondiciones_metereologicas: TWideStringField; qtratamientoshora_fin: TTimeField; qtratamientostractor: TWideStringField; qtratamientosdeposito: TWideStringField; qtratamientosvelocidad: TWideStringField; qtratamientospresion: TWideStringField; qtratamientosboquilla: TWideStringField; qtratamientosventilador: TWideStringField; qtratamientosmostrar: TIntegerField; qtratamientosvariedad: TWideStringField; qtratamientosdetalleide: TIntegerField; qtratamientosdetalleidt: TIntegerField; qtratamientosdetalleidaf: TIntegerField; qtratamientosdetalleidma: TIntegerField; qtratamientosdetalledescripcion_af: TWideStringField; qtratamientosdetalledescripcion_ma: TWideStringField; qtratamientosdetallecantidad_base: TFloatField; qtratamientosdetalledosis: TFloatField; qtratamientosdetalleunidad_medida: TWideStringField; qtratamientosdetalleregistro: TWideStringField; qtratamientosdetalleplazo: TIntegerField; qtratamientosdetalleficha: TBlobField; qtratamientosdetallecantidad_mezcla: TFloatField; qtratamientosdetallecantidad_materia: TFloatField; qtratamientosdetalleen_cuaderno: TIntegerField; qtratamientosdetalleidconsumo: TIntegerField; qtratamientosdetalleorden: TIntegerField; dsqconsumos: TDataSource; dsqtratamientos: TDataSource; dsqtratamientosdetalle: TDataSource; dsqoperarios: TDataSource; dsqcentrocoste2: TDataSource; dsqcentrocoste: TDataSource; dsqresponsables: TDataSource; dsqtractores: TDataSource; dsqvelocidad: TDataSource; dsqdepositos: TDataSource; dsqventilador: TDataSource; dsmateriasprimas: TDataSource; dsqresponsable2: TDataSource; dsqboquillas: TDataSource; dsqpresiones: TDataSource; Panel6: TPanel; Panel7: TPanel; Label36: TLabel; btAmodificar: TButton; btAborrar: TButton; btAnuevo: TButton; btAguardar: TButton; btAcancelar: TButton; Button4: TButton; Panel9: TPanel; DBGrid3: TDBGrid; Panel10: TPanel; Label4: TLabel; Label5: TLabel; Label3: TLabel; Label1: TLabel; Label6: TLabel; Label7: TLabel; combobuscarresponsables: TDBLookupComboBox; combobuscarparcelas: TDBLookupComboBox; btfiltrar: TButton; Button9: TButton; fdesde: TDateTimePicker; fhasta: TDateTimePicker; combovariedades: TDBLookupComboBox; Ffecha: TDateTimePicker; combocentrocoste: TDBLookupComboBox; comboresponsables: TDBLookupComboBox; Panel11: TPanel; Panel12: TPanel; Button7: TButton; Button6: TButton; DBGrid4: TDBGrid; Panel13: TPanel; Button2: TButton; Button3: TButton; combotractores: TDBLookupComboBox; combovelocidad: TDBLookupComboBox; combodepositos: TDBLookupComboBox; comboboquillas: TDBLookupComboBox; comboventilador: TDBLookupComboBox; combopresiones: TDBLookupComboBox; combooperarios: TDBLookupComboBox; DBGrid5: TDBGrid; dsqresumenproductos: TDataSource; qresumenproductos: TZReadOnlyQuery; qresumenproductosidcc: TWideStringField; qresumenproductosdesc_cc: TWideStringField; qresumenproductosdescripcion_af: TWideStringField; qresumenproductosnum_tratamientos: TFloatField; qresumenproductosnum_aplicaciones: TFloatField; qresumenproductosplazo_seguridad: TFloatField; qresumenproductosdosis_recomendada: TWideStringField; qresumenproductoscampanya: TWideStringField; qnombrecampanya: TZReadOnlyQuery; qnombrecampanyadescripcion: TWideStringField; qtratamientosdetalleconficha: TStringField; qtratamientosdetalleidentrada: TIntegerField; qtratamientosdetallefecha: TDateField; procedure Button6Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); procedure btfiltrarClick(Sender: TObject); procedure Button9Click(Sender: TObject); procedure dsqtratamientosDataChange(Sender: TObject; Field: TField); procedure dsqtratamientosdetalleDataChange(Sender: TObject; Field: TField); procedure DBGrid5DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure qtratamientosAfterPost(DataSet: TDataSet); procedure qtratamientosBeforeDelete(DataSet: TDataSet); procedure qtratamientosdetalleAfterDelete(DataSet: TDataSet); procedure qtratamientosdetalleAfterPost(DataSet: TDataSet); procedure qtratamientosdetalleBeforeDelete(DataSet: TDataSet); procedure qtratamientosdetalleBeforePost(DataSet: TDataSet); procedure qtratamientosdetalleCalcFields(DataSet: TDataSet); procedure DBGrid3CellClick(Column: TColumn); procedure DBGrid3ColExit(Sender: TObject); procedure DBGrid3DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBGrid3TitleClick(Column: TColumn); procedure DBGrid4CellClick(Column: TColumn); procedure DBGrid4DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBGrid4KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DBGrid4TitleClick(Column: TColumn); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button7Click(Sender: TObject); procedure btAnuevoClick(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure btAmodificarClick(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var cuadernos: Tcuadernos; implementation {$R *.dfm} uses principal, fbuscararticulos, datos; procedure Tcuadernos.btAborrarClick(Sender: TObject); begin qtratamientos.Delete; end; procedure Tcuadernos.btAcancelarClick(Sender: TObject); begin qtratamientos.Cancel; end; procedure Tcuadernos.btAguardarClick(Sender: TObject); begin qtratamientosidcc.value:=qcentrocostecodpar.AsString; qtratamientoside.Value:=qcentrocosteempresa.Asinteger; qtratamientosresponsable.Value:=qresponsablesnombre.AsString; qtratamientosnif_responsable.Value:=qresponsablesnif.asstring; qtratamientosfecha.Value:=ffecha.Date; qtratamientos.Post; qtratamientos.Refresh; end; procedure Tcuadernos.btAmodificarClick(Sender: TObject); begin qtratamientos.Edit; end; procedure Tcuadernos.btAnuevoClick(Sender: TObject); begin ffecha.Date:=date; qtratamientos.Append; qaux.Close; qaux.ParamByName('EMPRESA').AsInteger:=dm.tempresaid.asinteger; qaux.Prepare; qaux.Open; qtratamientoside.value:=dm.tempresaid.AsInteger; qtratamientosid.Value:=qaux.Fields[0].AsInteger; qtratamientosfecha.Value:=ffecha.Date; dbgrid3.setfocus; dbgrid3.SelectedIndex:=1; end; procedure Tcuadernos.btfiltrarClick(Sender: TObject); var vparcela,vresponsable,vvariedad:string; begin if combobuscarparcelas.keyvalue=null then vparcela:='%' else vparcela:=combobuscarparcelas.keyvalue; if combobuscarresponsables.keyvalue=null then vresponsable:='%' else vresponsable:=combobuscarresponsables.keyvalue; if combovariedades.keyvalue=null then vvariedad:='%' else vvariedad:=combovariedades.keyvalue; qtratamientos.Close; qtratamientos.Prepare; qtratamientos.ParamByName('parcela').AsString:=vparcela; qtratamientos.ParamByName('responsable').AsString:=vresponsable; qtratamientos.ParamByName('variedad').AsString:=vvariedad; qtratamientos.ParamByName('DESDE').AsDate:=fdesde.Date; qtratamientos.ParamByName('HASTA').AsDate:=fhasta.Date; qtratamientos.ParamByName('MOSTRAR').asstring:='%'; qtratamientos.Open; end; procedure Tcuadernos.Button2Click(Sender: TObject); begin qtratamientosdetalle.Delete; end; procedure Tcuadernos.Button3Click(Sender: TObject); begin if qtratamientosdetalleficha.AsString<>'' then begin qtratamientosdetalleficha.SaveToFile('c:\agrigest\tmp\'+qtratamientosdetalleregistro.AsString+'.pdf'); ShellExecute(Handle,nil,PChar('c:\agrigest\tmp\'+qtratamientosdetalleregistro.AsString+'.pdf'),'','',SW_SHOWNORMAL); end; end; procedure Tcuadernos.Button4Click(Sender: TObject); var imprimirtodo,vparcela,vresponsable:string; begin if combobuscarparcelas.keyvalue=null then vparcela:='%' else vparcela:=combobuscarparcelas.keyvalue; if combobuscarresponsables.keyvalue=null then vresponsable:='%' else vresponsable:=combobuscarresponsables.keyvalue; imprimirtodo:='1'; qtratamientos.Close; qtratamientos.Prepare; qtratamientos.ParamByName('parcela').AsString:=vparcela; qtratamientos.ParamByName('responsable').AsString:=vresponsable; qtratamientos.ParamByName('DESDE').AsDate:=fdesde.Date; qtratamientos.ParamByName('HASTA').AsDate:=fhasta.Date; qtratamientos.ParamByName('MOSTRAR').asstring:=imprimirtodo; qtratamientos.Open; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\inftratamientos.fr3'); informes.ShowReport(); qtratamientos.Filtered:=false; qtratamientosdetalle.Filtered:=false; end; procedure Tcuadernos.Button6Click(Sender: TObject); begin qtratamientos.Filter:='id='+qtratamientosid.Asstring; qtratamientos.Filtered:=true; qtratamientosdetalle.Filter:='en_cuaderno=1'; qtratamientosdetalle.Filtered:=true; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\inftratamientos.fr3'); informes.ShowReport(); qtratamientos.Filtered:=false; qtratamientosdetalle.Filtered:=false; end; procedure Tcuadernos.Button7Click(Sender: TObject); var direccion:pwidechar; registro,cadena:string; begin while not qtratamientosdetalle.eof do begin registro:= qtratamientosdetalleregistro.AsString; if registro<>'' then begin qaux.SQL.Clear; qaux.SQL.Add('select registro,autorizado from productos_fitosanitarios where registro=:REGISTRO'); qaux.Prepare; qaux.ParamByName('REGISTRO').AsString:=registro; qaux.Open; if qaux.RecordCount>0 then begin if qaux.Fields[1].AsInteger=1 then begin cadena:='https://www.mapa.gob.es/agricultura/pags/fitos/registro/productos/pdf/'+registro+'.pdf'; direccion:=pwidechar(widestring(cadena)); URLDownloadToFile(nil, direccion, 'C:\agrigest\tmp\ficha.pdf', 0, nil); qtratamientosdetalle.Edit; qtratamientosdetalleficha.LoadFromFile('c:\agrigest\tmp\ficha.pdf'); end else showmessage('PRODUCTO NO AUTORIZADO EN PRODUCTOS FITOSANITARIOS AUTORIZADOS'); end else showmessage('PRODUCTO NO ENCONTRADO EN PRODUCTOS FITOSANITARIOS AUTORIZADOS'); end; qtratamientosdetalle.Next; end; end; procedure Tcuadernos.Button9Click(Sender: TObject); begin combobuscarparcelas.KeyValue:=null; combobuscarresponsables.KeyValue:=null; combovariedades.KeyValue:=null; btfiltrar.click; end; procedure Tcuadernos.DBGrid3CellClick(Column: TColumn); begin if column.Field.FieldName ='mostrar' then begin if qtratamientosmostrar.asinteger=1 then begin qtratamientos.Edit; qtratamientosmostrar.Value:=0; qtratamientos.Post; dbgrid3.selectedIndex:=1; end else begin qtratamientos.Edit; qtratamientosmostrar.Value:=1; qtratamientos.Post; qtratamientos.Refresh; dbgrid3.SelectedIndex:=1; end; end; end; procedure Tcuadernos.DBGrid3ColExit(Sender: TObject); begin if qtratamientos.State in [dsinsert,dsedit] then begin qtratamientosfecha.Value:=ffecha.Date; end else begin // qtratamientos.Edit; // qtratamientosfecha.Value:=ffecha.Date; end; end; procedure Tcuadernos.DBGrid3DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); const IsChecked : array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED); var DrawState,imgindex,bmpwidth: Integer; DrawRect: TRect; begin if (gdFocused in State) then begin if (Column.Field.FieldName = 'contabilizado') then begin gcrpagado.Left := Rect.Left + DBgrid3.Left + 2; gcrpagado.Top := Rect.Top + DBgrid3.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'contabilizado') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; DBgrid3.Canvas.FillRect(Rect); DrawFrameControl(DBgrid3.Canvas.Handle, DrawRect,DFC_BUTTON, DrawState); end; end; if (gdFocused in State) then begin if (Column.Field.FieldName = 'mostrar') then begin gcrpagado.Left := Rect.Left + DBgrid3.Left + 2; gcrpagado.Top := Rect.Top + DBgrid3.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'mostrar') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; DBgrid3.Canvas.FillRect(Rect); DrawFrameControl(DBgrid3.Canvas.Handle, DrawRect,DFC_BUTTON, DrawState); end; end; gcrpagado.visible:=false; if (gdFocused in State) then begin if (Column.Field.FieldName = combocentrocoste.DataField) then with combocentrocoste do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else combocentrocoste.Visible:=false; if (Column.Field.FieldName = comboresponsables.DataField) then with comboresponsables do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else comboresponsables.Visible:=false; if (Column.Field.FieldName = combotractores.DataField) then with combotractores do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else combotractores.Visible:=false; if (Column.Field.FieldName = combodepositos.DataField) then with combodepositos do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else combodepositos.Visible:=false; if (Column.Field.FieldName = combovelocidad.DataField) then with combovelocidad do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else combovelocidad.Visible:=false; if (Column.Field.FieldName = combopresiones.DataField) then with combopresiones do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else combopresiones.Visible:=false; if (Column.Field.FieldName = comboboquillas.DataField) then with comboboquillas do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else comboboquillas.Visible:=false; if (Column.Field.FieldName = comboventilador.DataField) then with comboventilador do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else comboventilador.Visible:=false; if (Column.Field.FieldName = combooperarios.DataField) then with combooperarios do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else combooperarios.Visible:=false; if (Column.Field.FieldName = 'fecha') then with ffecha do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; end else begin ffecha.Visible:=false; end; end; end; procedure Tcuadernos.DBGrid3TitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=qtratamientos.SortType; qtratamientos.SortedFields:=Column.FieldName; If st = stAscending then qtratamientos.SortType:=stDescending else qtratamientos.SortType:=stAscending; dsqtratamientos.DataSet.First; end; procedure Tcuadernos.DBGrid4CellClick(Column: TColumn); begin if column.Field.FieldName ='en_cuaderno' then begin if qtratamientosdetalleen_cuaderno.asinteger=1 then begin qtratamientosdetalle.Edit; qtratamientosdetalleen_cuaderno.Value:=0; qtratamientosdetalle.Post; dbgrid4.selectedIndex:=1; end else begin qtratamientosdetalle.Edit; qtratamientosdetalleen_cuaderno.Value:=1; qtratamientosdetalle.Post; qtratamientosdetalle.Refresh; dbgrid4.SelectedIndex:=1; end; end; end; procedure Tcuadernos.DBGrid4DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); const IsChecked : array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED); var DrawState,imgindex,bmpwidth: Integer; DrawRect: TRect; fixRect:TRect; bitmap:tbitmap; begin fixRect := Rect; if (gdFocused in State) then begin if (Column.Field.FieldName = 'en_cuaderno') then begin gcrpagado.Left := Rect.Left + DBgrid4.Left + 2; gcrpagado.Top := Rect.Top + DBgrid4.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'en_cuaderno') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; // DrawState := ISChecked[Column.Field.Asboolean]; DBgrid4.Canvas.FillRect(Rect); DrawFrameControl(DBgrid4.Canvas.Handle, DrawRect,DFC_BUTTON, DrawState); end; end; gcrpagado.visible:=false; fixRect := Rect; if column.Title.Caption ='Ficha' then begin if qtratamientosdetalle.FieldByname('conficha').Asstring=' ' then imgIndex := 88 else imgIndex := -1; bitmap := TBitmap.Create; try base.listaiconos.GetBitmap(imgIndex,bitmap); bmpWidth := (Rect.Bottom - Rect.Top); fixRect.right := Rect.Left + bmpWidth; DBGrid4.Canvas.StretchDraw(fixRect,bitmap); finally bitmap.Free; end; fixRect := Rect; fixRect.Left := fixRect.Left + bmpWidth; // DBgrid4.Canvas.FillRect(Rect); DBGrid4.DefaultDrawColumnCell(fixRect,-1,Column,State); end; end; procedure Tcuadernos.DBGrid4KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (key=115) then begin buscararticulos := Tbuscararticulos.Create(nil); try fbuscararticulos.filtro:=qtratamientosdetalledescripcion_af.AsString; buscararticulos.Edit1.Text:=qtratamientosdetalledescripcion_af.AsString; buscararticulos.showmodal(); finally if qtratamientosdetalle.State in [dsbrowse] then qtratamientosdetalle.Edit; qtratamientosdetalleidaf.Value:=buscararticulos.qarticulosid.Asinteger; qtratamientosdetalleregistro.Value:=buscararticulos.qarticulosregistro.Asstring; qtratamientosdetalledescripcion_af.value:=buscararticulos.qarticulosdescripcion.AsString; qtratamientosdetalledescripcion_ma.Value:=buscararticulos.qarticulosmateria_activa.Asstring; qtratamientosdetalledosis.value:=0; qtratamientosdetalleplazo.value:=buscararticulos.qarticulosplazo_seguridad.Asinteger; buscararticulos.Free; end; end; end; procedure Tcuadernos.DBGrid4TitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=qtratamientosdetalle.SortType; qtratamientos.SortedFields:=Column.FieldName; If st = stAscending then qtratamientosdetalle.SortType:=stDescending else qtratamientosdetalle.SortType:=stAscending; dsqtratamientosdetalle.DataSet.First; end; procedure Tcuadernos.DBGrid5DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if (qresumenproductosnum_tratamientos.Asinteger>qresumenproductosnum_aplicaciones.asinteger)then begin DBGrid5.Canvas.brush.Color := rojo; end ; DBGrid5.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure Tcuadernos.dsqtratamientosDataChange(Sender: TObject; Field: TField); begin qnombrecampanya.Prepare; qnombrecampanya.ParamByName('FECHA').AsDateTime:=qtratamientosfecha.AsDateTime; qnombrecampanya.refresh; qresumenproductos.Prepare; qresumenproductos.ParamByName('PARCELA').AsString:=qtratamientosidcc.AsString; qresumenproductos.ParamByName('CAMPANYA').AsString:=qnombrecampanyadescripcion.asstring; qresumenproductos.refresh; qtratamientosdetalle.Prepare; qtratamientosdetalle.ParamByName('EMPRESA').AsInteger:=qtratamientoside.AsInteger; qtratamientosdetalle.ParamByName('TRATAMIENTO').AsInteger:=qtratamientosid.AsInteger; qtratamientosdetalle.Refresh; end; procedure Tcuadernos.dsqtratamientosdetalleDataChange(Sender: TObject; Field: TField); begin qresumenproductos.Locate('descripcion_af',qtratamientosdetalledescripcion_af.AsString,[loCaseInsensitive]); end; procedure Tcuadernos.FormKeyPress(Sender: TObject; var Key: Char); begin key:=upcase(key); if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; // si presionamos ESC if (key=#$1B) and (activecontrol is tdblookupcombobox )then begin activecontrol.Visible:=false; end; end; procedure Tcuadernos.FormShow(Sender: TObject); var anyo,mes,dia:word; begin decodedate(date,anyo,mes,dia); fdesde.Date:=(strtodate('01/01/'+inttostr(anyo))); fhasta.Date:=(strtodate('31/12/'+inttostr(anyo))); ffecha.Date:=date; qcentrocoste.close; qresponsables.Close; qtratamientos.Close; qtratamientosdetalle.close; qcentrocoste2.close; qresponsables2.Close; qmateriaprima2.Close; qtractores.close; qvelocidad.close; qdepositos.close; qboquillas.close; qpresiones.close; qventilador.close; qcentrocoste.open; qresponsables.open; qcentrocoste2.open; qresponsables2.open; qmateriaprima2.open; qnombrecampanya.Open; qresumenproductos.Open; qtratamientosdetalle.open; qtratamientos.ParamByName('parcela').AsString:='%'; qtratamientos.ParamByName('responsable').AsString:='%'; qtratamientos.ParamByName('DESDE').AsDate:=fdesde.Date; qtratamientos.ParamByName('HASTA').AsDate:=fhasta.Date; qtratamientos.ParamByName('MOSTRAR').asstring:='%'; qtratamientos.Prepare; qtratamientos.open; qtractores.Open; qvelocidad.Open; qdepositos.Open; qboquillas.Open; qpresiones.Open; qventilador.Open; qoperarios.Open; end; procedure Tcuadernos.qtratamientosAfterPost(DataSet: TDataSet); begin qtractores.refresh; qvelocidad.refresh; qdepositos.refresh; qboquillas.refresh; qpresiones.refresh; qventilador.refresh; qoperarios.Refresh; end; procedure Tcuadernos.qtratamientosBeforeDelete(DataSet: TDataSet); begin case dm.PedirConfirmacion('¿Confirma que desea borrar este tratamiento?',true,true,false) of mrno:Abort; end; end; procedure Tcuadernos.qtratamientosdetalleAfterDelete(DataSet: TDataSet); begin qresumenproductos.Refresh; end; procedure Tcuadernos.qtratamientosdetalleAfterPost(DataSet: TDataSet); begin qtratamientosdetalle.Refresh; qresumenproductos.Refresh; end; procedure Tcuadernos.qtratamientosdetalleBeforeDelete(DataSet: TDataSet); begin case dm.PedirConfirmacion('¿Confirma que desea borrar este tratamiento?',true,true,false) of mrno:Abort; end; end; procedure Tcuadernos.qtratamientosdetalleBeforePost(DataSet: TDataSet); var x:integer; begin qtratamientosdetalleide.Value:=qtratamientoside.AsInteger; qtratamientosdetalleidt.Value:=qtratamientosid.AsInteger; if qtratamientosdetalle.state=dsinsert then x:=dm.PedirConfirmacion('¿Confirma que desea dar de alta este producto?',true,true,true) else x:=dm.PedirConfirmacion('¿Confirma que desea modificar este producto?',true,true,true); case x of mrno: begin qtratamientosdetalle.cancel; abort; end; mrcancel:BEGIN abort; END; end; end; procedure Tcuadernos.qtratamientosdetalleCalcFields(DataSet: TDataSet); begin if qtratamientosdetalleficha.AsString<>'' then qtratamientosdetalleconficha.Value:=' ' else qtratamientosdetalleconficha.Value:=''; end; end. ======================================== FICHERO: fdlgfecha.pas ======================================== unit fdlgfecha; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Mask; type Tdlgfecha = class(TForm) Button1: TButton; lfecha: TMaskEdit; procedure FormShow(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var dlgfecha: Tdlgfecha; implementation {$R *.dfm} procedure Tdlgfecha.Button1Click(Sender: TObject); begin close(); end; procedure Tdlgfecha.FormShow(Sender: TObject); begin lfecha.Text:=datetostr(date()); lfecha.SetFocus; end; end. ======================================== FICHERO: fdlglineaspedido.pas ======================================== unit fdlglineaspedido; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids,data.db, Vcl.ExtCtrls, Vcl.Mask, Vcl.DBCtrls, ZAbstractRODataset, ZDataset; type Tdlglineaspedido = class(TForm) Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; Panel4: TPanel; Panel5: TPanel; Panel25: TPanel; DBGrid6: TDBGrid; Panel6: TPanel; Label35: TLabel; btAcancelar: TButton; btAguardar: TButton; btAmodificar: TButton; btAborrar: TButton; btAnuevo: TButton; Panel9: TPanel; Label3: TLabel; btClcancelar: TButton; btClguardar: TButton; btClmodificar: TButton; btClborrar: TButton; btClnuevo: TButton; Panel26: TPanel; DBGrid3: TDBGrid; Panel23: TPanel; DBGrid2: TDBGrid; Panel7: TPanel; Label1: TLabel; Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; Button5: TButton; Panel16: TPanel; DBGrid9: TDBGrid; Panel21: TPanel; Label20: TLabel; btCAcancelar: TButton; btCAmodificar: TButton; btCAborrar: TButton; btCAnuevo: TButton; btCAguardar: TButton; Panel8: TPanel; DBGrid1: TDBGrid; Panel10: TPanel; Label2: TLabel; Panel11: TPanel; DBGrid4: TDBGrid; Panel12: TPanel; Label4: TLabel; DBText1: TDBText; DBText2: TDBText; DBText3: TDBText; DBText5: TDBText; DBText6: TDBText; DBText9: TDBText; DBText10: TDBText; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; DBText11: TDBText; DBText12: TDBText; DBText13: TDBText; DBText14: TDBText; Label9: TLabel; Label10: TLabel; Label11: TLabel; Label12: TLabel; DBText4: TDBText; DBEdit1: TDBEdit; DBEdit2: TDBEdit; Panel13: TPanel; Button6: TButton; Button7: TButton; Label13: TLabel; DBMemo1: TDBMemo; qaux: TZReadOnlyQuery; Label14: TLabel; DBEdit3: TDBEdit; Label15: TLabel; DBEdit5: TDBEdit; Label16: TLabel; lbcliente: TLabel; lbdestino: TLabel; Panel14: TPanel; DBGrid5: TDBGrid; Panel15: TPanel; Label17: TLabel; Button8: TButton; Button9: TButton; Button10: TButton; Button11: TButton; Button12: TButton; Panel17: TPanel; DBGrid7: TDBGrid; Panel18: TPanel; Label18: TLabel; Button13: TButton; Button14: TButton; Button15: TButton; Button16: TButton; Button17: TButton; Label19: TLabel; DBText7: TDBText; DBText8: TDBText; Label21: TLabel; DBText15: TDBText; DBText16: TDBText; Panel19: TPanel; DBText17: TDBText; Label22: TLabel; DBEdit4: TDBEdit; Label23: TLabel; DBEdit6: TDBEdit; DBEdit7: TDBEdit; Label24: TLabel; DBText18: TDBText; procedure DBGrid6DblClick(Sender: TObject); procedure DBGrid3DblClick(Sender: TObject); procedure DBGrid2DblClick(Sender: TObject); procedure DBGrid9DblClick(Sender: TObject); procedure DBGrid1DblClick(Sender: TObject); procedure DBGrid4DblClick(Sender: TObject); procedure Button6Click(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure Button7Click(Sender: TObject); procedure btAnuevoClick(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure btAmodificarClick(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); procedure btClnuevoClick(Sender: TObject); procedure btClborrarClick(Sender: TObject); procedure btClmodificarClick(Sender: TObject); procedure btClcancelarClick(Sender: TObject); procedure btClguardarClick(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure btCAnuevoClick(Sender: TObject); procedure btCAborrarClick(Sender: TObject); procedure btCAmodificarClick(Sender: TObject); procedure btCAcancelarClick(Sender: TObject); procedure btCAguardarClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure DBGrid5DblClick(Sender: TObject); procedure DBGrid7DblClick(Sender: TObject); procedure Button11Click(Sender: TObject); procedure Button16Click(Sender: TObject); procedure Button10Click(Sender: TObject); procedure Button9Click(Sender: TObject); procedure Button12Click(Sender: TObject); procedure Button8Click(Sender: TObject); procedure Button13Click(Sender: TObject); procedure Button17Click(Sender: TObject); procedure Button14Click(Sender: TObject); procedure Button15Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var dlglineaspedido: Tdlglineaspedido; implementation {$R *.dfm} uses fpedidos, datosclientes; procedure Tdlglineaspedido.btAborrarClick(Sender: TObject); begin pedidos.dtarticulos.delete; end; procedure Tdlglineaspedido.btAcancelarClick(Sender: TObject); begin pedidos.dtarticulos.Cancel; end; procedure Tdlglineaspedido.btAguardarClick(Sender: TObject); var id,ide,idcliente:string; begin pedidos.dtarticulos.Post; id:=pedidos.dtarticulosid.AsString; ide:=pedidos.dtarticulosidempresa.AsString; idcliente:=pedidos.dtarticulosidcliente.AsString; pedidos.dtarticulosiddestino.value:=pedidos.dtpedidosiddestino.Asstring; pedidos.dtarticulos.Post; pedidos.dtarticulos.MasterSource:=pedidos.dsqpedidos; pedidos.dtarticulos.refresh; pedidos.dtarticulos.Locate('idempresa,id,idcliente',vararrayof([ide,id,idcliente]),[locaseinsensitive]); end; procedure Tdlglineaspedido.btAmodificarClick(Sender: TObject); begin pedidos.dtarticulos.edit; end; procedure Tdlglineaspedido.btAnuevoClick(Sender: TObject); begin qaux.SQL.Clear; qaux.SQL.Add('select count(*)+1 from clientes_articulos'); qaux.Open; pedidos.dtarticulos.append; pedidos.dtarticulosid.value:=qaux.Fields[0].AsString; pedidos.dtarticulosidempresa.value:=pedidos.dtpedidosIde.AsInteger; pedidos.dtarticulosidcliente.value:=pedidos.dtpedidosIdcliente.AsInteger; pedidos.dtarticulosiddestino.value:=pedidos.dtpedidosiddestino.Asstring; end; procedure Tdlglineaspedido.btCAborrarClick(Sender: TObject); begin pedidos.qclientesacabados.delete; end; procedure Tdlglineaspedido.btCAcancelarClick(Sender: TObject); begin pedidos.qclientesacabados.cancel; end; procedure Tdlglineaspedido.btCAguardarClick(Sender: TObject); var id,ide,idcliente:string; begin id:=pedidos.qclientesacabadosid.AsString; ide:=pedidos.qclientesacabadosidempresa.AsString; idcliente:=pedidos.qclientesacabadosidcliente.AsString; pedidos.qclientesacabadosiddestino.value:=pedidos.dtpedidosiddestino.Asstring; pedidos.qclientesacabados.Post; pedidos.qclientesacabados.MasterSource:=pedidos.dsqpedidos; pedidos.qclientesacabados.Refresh; pedidos.qclientesacabados.Locate('idempresa,id,idcliente',vararrayof([ide,id,idcliente]),[locaseinsensitive]); end; procedure Tdlglineaspedido.btCAmodificarClick(Sender: TObject); begin pedidos.qclientesacabados.edit; end; procedure Tdlglineaspedido.btCAnuevoClick(Sender: TObject); begin qaux.SQL.Clear; qaux.SQL.Add('select count(*)+1 from clientes_acabados'); qaux.Open; pedidos.qclientesacabados.append; pedidos.qclientesacabadosid.value:=qaux.Fields[0].AsString; pedidos.qclientesacabadosidempresa.value:=pedidos.dtpedidosIde.AsInteger; pedidos.qclientesacabadosidcliente.value:=pedidos.dtpedidosIdcliente.AsInteger; pedidos.qclientesacabadosiddestino.value:=pedidos.dtpedidosiddestino.Asstring; end; procedure Tdlglineaspedido.btClborrarClick(Sender: TObject); begin pedidos.qclientescalidad.delete; end; procedure Tdlglineaspedido.btClcancelarClick(Sender: TObject); begin pedidos.qclientescalidad.cancel; end; procedure Tdlglineaspedido.btClguardarClick(Sender: TObject); var id,ide,idcliente:string; begin id:=pedidos.qclientescalidadid.AsString; ide:=pedidos.qclientescalidadidempresa.AsString; idcliente:=pedidos.qclientescalidadidcliente.AsString; pedidos.qclientescalidadiddestino.value:=pedidos.dtpedidosiddestino.Asstring; pedidos.qclientescalidad.Post; pedidos.qclientescalidad.MasterSource:=pedidos.dsqpedidos; pedidos.qclientescalidad.refresh; pedidos.qclientescalidad.Locate('idempresa,id,idcliente',vararrayof([ide,id,idcliente]),[locaseinsensitive]); end; procedure Tdlglineaspedido.btClmodificarClick(Sender: TObject); begin pedidos.qclientescalidad.edit; end; procedure Tdlglineaspedido.btClnuevoClick(Sender: TObject); begin qaux.SQL.Clear; qaux.SQL.Add('select count(*)+1 from clientes_calidad'); qaux.Open; pedidos.qclientescalidad.append; pedidos.qclientescalidadid.value:=qaux.Fields[0].AsString; pedidos.qclientescalidadidempresa.value:=pedidos.dtpedidosIde.AsInteger; pedidos.qclientescalidadidcliente.value:=pedidos.dtpedidosIdcliente.AsInteger; pedidos.qclientescalidadiddestino.value:=pedidos.dtpedidosiddestino.Asstring; dbgrid3.SetFocus; end; procedure Tdlglineaspedido.Button10Click(Sender: TObject); begin pedidos.qpaises.Delete; end; procedure Tdlglineaspedido.Button11Click(Sender: TObject); begin pedidos.qpaises.append; pedidos.qpaisesidempresa.value:=pedidos.dtpedidosIde.AsInteger; pedidos.qpaisesidcliente.value:=pedidos.dtpedidosIdcliente.AsInteger; end; procedure Tdlglineaspedido.Button12Click(Sender: TObject); begin pedidos.qvariedadesidempresa.value:=pedidos.dtpedidosIde.AsInteger; pedidos.qvariedadesidcliente.value:=pedidos.dtpedidosIdcliente.AsInteger; pedidos.qpaises.post; end; procedure Tdlglineaspedido.Button13Click(Sender: TObject); begin pedidos.qvariedades.cancel; end; procedure Tdlglineaspedido.Button14Click(Sender: TObject); begin pedidos.qvariedades.edit; end; procedure Tdlglineaspedido.Button15Click(Sender: TObject); begin pedidos.qvariedades.delete; end; procedure Tdlglineaspedido.Button16Click(Sender: TObject); begin pedidos.qvariedades.append; pedidos.qvariedadesidempresa.value:=pedidos.dtpedidosIde.AsInteger; pedidos.qvariedadesidcliente.value:=pedidos.dtpedidosIdcliente.AsInteger; end; procedure Tdlglineaspedido.Button17Click(Sender: TObject); begin pedidos.qvariedadesidempresa.value:=pedidos.dtpedidosIde.AsInteger; pedidos.qvariedadesidcliente.value:=pedidos.dtpedidosIdcliente.AsInteger; pedidos.qvariedades.Post end; procedure Tdlglineaspedido.Button1Click(Sender: TObject); begin pedidos.dtarticulosformato.cancel; end; procedure Tdlglineaspedido.Button2Click(Sender: TObject); begin pedidos.dtarticulosformato.edit; end; procedure Tdlglineaspedido.Button3Click(Sender: TObject); begin pedidos.dtarticulosformato.delete; end; procedure Tdlglineaspedido.Button4Click(Sender: TObject); begin qaux.SQL.Clear; qaux.SQL.Add('select count(*)+1 from clientes_formatoarticulos'); qaux.Open; pedidos.dtarticulosformato.append; pedidos.dtarticulosformatoid.value:=qaux.Fields[0].AsString; pedidos.dtarticulosformatoidempresa.value:=pedidos.dtpedidosIde.AsInteger; pedidos.dtarticulosformatoidcliente.value:=pedidos.dtpedidosIdcliente.AsInteger; pedidos.dtarticulosformatoiddestino.value:=pedidos.dtpedidosiddestino.Asstring; dbgrid2.SetFocus; end; procedure Tdlglineaspedido.Button5Click(Sender: TObject); var id,ide,idcliente:string; begin id:=pedidos.dtarticulosformatoid.AsString; ide:=pedidos.dtarticulosformatoidempresa.AsString; idcliente:=pedidos.dtarticulosformatoidcliente.AsString; pedidos.dtarticulosformatoiddestino.value:=pedidos.dtpedidosiddestino.Asstring; pedidos.dtarticulosformato.Post; pedidos.dtarticulosformato.MasterSource:=pedidos.dsqpedidos; pedidos.dtarticulosformato.Refresh; pedidos.dtarticulosformato.Locate('idempresa,id,idcliente',vararrayof([ide,id,idcliente]),[locaseinsensitive]); end; procedure Tdlglineaspedido.Button6Click(Sender: TObject); begin pedidos.dtlinpedidoside.value:=pedidos.dtpedidoside.Asinteger; pedidos.dtlinpedidosidpedido.value:=pedidos.dtpedidosid.Asinteger; pedidos.dtlinpedidosidcliente.value:=pedidos.dtpedidosidcliente.Asinteger; pedidos.dtlinpedidos.post; close; end; procedure Tdlglineaspedido.Button7Click(Sender: TObject); begin pedidos.dtlinpedidos.cancel; close; end; procedure Tdlglineaspedido.Button8Click(Sender: TObject); begin pedidos.qpaises.cancel; end; procedure Tdlglineaspedido.Button9Click(Sender: TObject); begin pedidos.qpaises.Edit; end; procedure Tdlglineaspedido.DBGrid1DblClick(Sender: TObject); begin pedidos.dtlinpedidosidcajapropia.value:=pedidos.qcajascodigo.AsString; pedidos.dtlinpedidosdesc_envpropio.value:=pedidos.qcajasdescripcion.AsString; end; procedure Tdlglineaspedido.DBGrid2DblClick(Sender: TObject); begin pedidos.dtlinpedidosidenvase.Value:=pedidos.dtarticulosformatoidformato.Asstring; pedidos.dtlinpedidosdesc_envase.Value:=pedidos.dtarticulosformatodes_envase.Asstring; pedidos.dtlinpedidosean.Value:=pedidos.dtarticulosformatoean.Asstring; pedidos.dtlinpedidosmarca.Value:=pedidos.dtarticulosformatomarca.Asstring; pedidos.dtlinpedidosdun14.Value:=pedidos.dtarticulosformatodun14.Asstring; pedidos.dtlinpedidosref.Value:=pedidos.dtarticulosformatoid.Asstring; end; procedure Tdlglineaspedido.DBGrid3DblClick(Sender: TObject); begin pedidos.dtlinpedidosidcalidad.Value:=pedidos.qclientescalidadid.asstring; pedidos.dtlinpedidosdesc_calidad.Value:=pedidos.qclientescalidaddescripcion.Asstring; end; procedure Tdlglineaspedido.DBGrid4DblClick(Sender: TObject); begin pedidos.dtlinpedidosidformatopropio.value:=pedidos.qacabadosid.Asinteger; pedidos.dtlinpedidosdesc_formatopropio.value:=pedidos.qacabadosdescripcion.AsString; end; procedure Tdlglineaspedido.DBGrid5DblClick(Sender: TObject); begin pedidos.dtlinpedidosidpais.Value:=pedidos.qpaisesid.Asstring; pedidos.dtlinpedidosdesc_pais.Value:=pedidos.qpaisesdescripcion.Asstring; end; procedure Tdlglineaspedido.DBGrid6DblClick(Sender: TObject); begin pedidos.dtlinpedidosidproductocli.Value:=pedidos.dtarticulosid.asstring; pedidos.dtlinpedidosdesc_producto.Value:=pedidos.dtarticulosdesc_cliente.Asstring; end; procedure Tdlglineaspedido.DBGrid7DblClick(Sender: TObject); begin pedidos.dtlinpedidosidvariedad.Value:=pedidos.qvariedadesid.Asstring; pedidos.dtlinpedidosdesc_variedad.Value:=pedidos.qvariedadesdescripcion.Asstring; end; procedure Tdlglineaspedido.DBGrid9DblClick(Sender: TObject); begin pedidos.dtlinpedidosidacabado.Value:=pedidos.qclientesacabadosid.Asstring; pedidos.dtlinpedidosdesc_acabado.Value:=pedidos.qclientesacabadosdescripcion.Asstring; end; procedure Tdlglineaspedido.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tdlglineaspedido.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is tdbgrid) then begin key:=','; end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tdlglineaspedido.FormShow(Sender: TObject); begin lbcliente.Caption:='CLIENTE: '+pedidos.qclientesnombre.AsString; lbdestino.Caption:='DESTINO: '+pedidos.qdestinosdescripcion.AsString; end; end. ======================================== FICHERO: fdlgllamamientos.pas ======================================== unit fdlgllamamientos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Data.DB, ZAbstractRODataset, ZDataset, Vcl.DBCtrls, Vcl.Mask; type Tdlgllamamientos = class(TForm) listaconvocatorias: TDBLookupListBox; qconvocatorias: TZReadOnlyQuery; dsqconvocatorias: TDataSource; Button1: TButton; Label1: TLabel; qconvocatoriasconvocatoria: TWideStringField; lfecha: TMaskEdit; lhora: TMaskEdit; Label2: TLabel; Label3: TLabel; lfecha2: TMaskEdit; Label4: TLabel; procedure FormShow(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var dlgllamamientos: Tdlgllamamientos; implementation {$R *.dfm} procedure Tdlgllamamientos.Button1Click(Sender: TObject); begin close(); end; procedure Tdlgllamamientos.FormShow(Sender: TObject); begin qconvocatorias.Open; lfecha.Text:=datetostr(date()); lfecha.SetFocus; end; end. ======================================== FICHERO: fdlgticados.pas ======================================== unit fdlgticados; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZDataset, Vcl.Grids, Vcl.DBGrids, ZAbstractDataset, Vcl.StdCtrls, Vcl.ExtCtrls; type Tdlgticados = class(TForm) DBGrid1: TDBGrid; dsqticados: TDataSource; Panel6: TPanel; Button1: TButton; qticados: TZQuery; qticadosid: TLargeintField; qticadoside: TSmallintField; qticadosfecha: TDateField; qticadosidt: TIntegerField; qticadosTRABAJADOR: TWideStringField; qticadosENTRADA_REAL: TTimeField; qticadosSALIDA_REAL: TTimeField; qticadostiempo: TFloatField; updateticadoscompleto: TZQuery; procedure Button1Click(Sender: TObject); procedure qticadosAfterPost(DataSet: TDataSet); procedure qticadosBeforePost(DataSet: TDataSet); private { Private declarations } public { Public declarations } var idticado: integer; end; var dlgticados: Tdlgticados; implementation {$R *.dfm} uses fticados; procedure Tdlgticados.Button1Click(Sender: TObject); begin qticados.Delete; end; procedure Tdlgticados.qticadosAfterPost(DataSet: TDataSet); begin qticados.Refresh; end; procedure Tdlgticados.qticadosBeforePost(DataSet: TDataSet); begin qticadosidt.Value:=ticados.qticadosidt.AsInteger; qticadostrabajador.Value:=ticados.qticadosTRABAJADOR.AsString; end; end. ======================================== FICHERO: fechacierre.pas ======================================== unit fechacierre; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,datosproduccion, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls, Data.DB, ZAbstractRODataset, ZDataset; type Tpreguntarfecha = class(TForm) Label1: TLabel; Button1: TButton; Label2: TLabel; calendario: TDateTimePicker; qaux: TZReadOnlyQuery; procedure FormShow(Sender: TObject); procedure Button1Click(Sender: TObject); procedure calendarioClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var preguntarfecha: Tpreguntarfecha; implementation {$R *.dfm} procedure Tpreguntarfecha.Button1Click(Sender: TObject); var anyo,mes,dia:word; vanyo,vmes,vdia,vmessig,vfecha:string; begin decodedate(calendario.date,anyo,mes,dia); vanyo:=floattostr(anyo); vmes:=floattostr(mes); vmessig:=floattostr(mes+1); if length(vmes)=1 then vmes:='0'+vmes; if length(vmessig)=1 then vmessig:='0'+vmessig; if length(vdia)=1 then vdia:='0'+vdia; vmes:=floattostr(mes); vmessig:=floattostr(mes+1); vdia:=floattostr(dia); vfecha:=floattostr(anyo)+'-'+vmes+'-'+vdia; dmproduccion.qactualizar.sql.clear; dmproduccion.qactualizar.sql.add('select * from restos_dia where lote='+dmproduccion.qrestos_dialote.asstring+' and fecha='+''''+vfecha+''''); dmproduccion.qactualizar.open; if dmproduccion.qactualizar.RecordCount=0 then begin dmproduccion.qactualizar.sql.clear; dmproduccion.qactualizar.sql.add('insert into restos_dia (ide,idalmacen,lote,parcela,mprima,fecha,cant_inicial,cant_final) '); dmproduccion.qactualizar.sql.add(' select ide,idalmacen,lote,parcela,mprima,'+''''+vfecha+''''+',cant_final,0 from restos_dia where id='+dmproduccion.qrestos_diaid.AsString); dmproduccion.qactualizar.ExecSQL; end else begin qaux.SQL.Clear; qaux.SQL.Add('select sum(num_envases) from ea_pesadas where fechatrabajo='+''''+vfecha+''''+' and iddestino='+dmproduccion.qrestos_diaidalmacen.asstring+' and idempresa='+dmproduccion.qrestos_diaide.AsString+' and lote='+dmproduccion.qrestos_dialote.AsString); qaux.Open; if qaux.fields[0].AsInteger>0 then begin dmproduccion.qactualizar.sql.clear; dmproduccion.qactualizar.sql.add('update restos_dia set cant_inicial='+inttostr(qaux.Fields[0].Asinteger+dmproduccion.qrestos_diacant_final.Asinteger) +' where ide='+dmproduccion.qrestos_diaide.AsString+' and lote='+dmproduccion.qrestos_dialote.AsString+' and fecha='+''''+vfecha+''''); dmproduccion.qactualizar.ExecSQL; end else begin dmproduccion.qactualizar.sql.clear; dmproduccion.qactualizar.sql.add('update restos_dia set cant_inicial='+dmproduccion.qrestos_diacant_final.AsString +' where ide='+dmproduccion.qrestos_diaide.AsString+' and lote='+dmproduccion.qrestos_dialote.AsString+' and fecha='+''''+vfecha+''''); dmproduccion.qactualizar.ExecSQL; end; end; close; dmproduccion.qrestos_dia.Refresh; dmproduccion.qpartesdiarios.Edit; dmproduccion.qpartesdiariosfecha_traspaso.Value:=calendario.Date; dmproduccion.qpartesdiarios.Post; end; procedure Tpreguntarfecha.calendarioClick(Sender: TObject); begin label2.Caption:=datetostr(calendario.Date); end; procedure Tpreguntarfecha.FormShow(Sender: TObject); begin label1.Caption:='Próximo día de trabajo para el lote: '+dmproduccion.qrestos_dialote.asstring; calendario.Date:=date; label2.Caption:=datetostr(calendario.Date); end; end. ======================================== FICHERO: femphistorico.pas ======================================== unit femphistorico; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.ExtCtrls, Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset; type Temp_historico = class(TForm) Panel1: TPanel; btnuevo: TButton; btmodificar: TButton; btborrar: TButton; btguardar: TButton; btcancelar: TButton; dsqemp_historico: TDataSource; DBGrid1: TDBGrid; procedure btnuevoClick(Sender: TObject); procedure btmodificarClick(Sender: TObject); procedure btborrarClick(Sender: TObject); procedure btguardarClick(Sender: TObject); procedure btcancelarClick(Sender: TObject); procedure dsqemp_historicoStateChange(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } end; var emp_historico: Temp_historico; implementation {$R *.dfm} uses empleados, datos; procedure Temp_historico.btborrarClick(Sender: TObject); begin fempleados.qemp_historico.delete; end; procedure Temp_historico.btnuevoClick(Sender: TObject); begin fempleados.qemp_historico.Append; end; procedure Temp_historico.btguardarClick(Sender: TObject); begin fempleados.qemp_historico.post end; procedure Temp_historico.btcancelarClick(Sender: TObject); begin fempleados.qemp_historico.cancel; end; procedure Temp_historico.btmodificarClick(Sender: TObject); begin fempleados.qemp_historico.edit; end; procedure Temp_historico.dsqemp_historicoStateChange(Sender: TObject); begin if fempleados.qemp_historico.State in [dsedit,dsinsert] then begin btnuevo.Enabled:=false; btmodificar.Enabled:=false; btborrar.Enabled:=false; btcancelar.Enabled:=true; btguardar.Enabled:=true; dbgrid1.Enabled:=true; end else begin btnuevo.Enabled:=true; btmodificar.Enabled:=true; btborrar.Enabled:=true; btcancelar.Enabled:=false; btguardar.Enabled:=false; dbgrid1.Enabled:=true; end; end; procedure Temp_historico.FormKeyPress(Sender: TObject; var Key: Char); begin key:=upcase(key); if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; end. ======================================== FICHERO: fentradas.pas ======================================== unit fentradas; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.DBCtrls, Vcl.Mask, Vcl.ComCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, datos, ZAbstractDataset, ZDataset, Data.DB, ZAbstractRODataset, ZAbstractTable; type Tentradas = class(TForm) Panel1: TPanel; Panel2: TPanel; Panel5: TPanel; Label1: TLabel; tbuscar: TEdit; DBGrid1: TDBGrid; Panel3: TPanel; Panel4: TPanel; DatosProveedores: TPageControl; TDatosClientes: TTabSheet; Panel14: TPanel; Label2: TLabel; Label4: TLabel; DBEdit3: TDBEdit; Panel6: TPanel; Label37: TLabel; BtEcancelar: TButton; btEmodificar: TButton; BtEborrar: TButton; BtENuevo: TButton; BtEguardar: TButton; qentradas: TZReadOnlyQuery; entradas: TZQuery; entradas_detalle: TZQuery; entradas_detalleid: TIntegerField; entradas_detalleidempresa: TIntegerField; entradas_detalleidentrada: TIntegerField; entradas_detallecodigo: TWideStringField; entradas_detalleid_propio: TWideStringField; entradas_detalledescripcion: TWideStringField; entradas_detallecantidad: TFloatField; entradas_detallestock: TFloatField; entradas_detalleprecio: TFloatField; DBLookupComboBox1: TDBLookupComboBox; dsentradas: TDataSource; dsqentradas: TDataSource; qaux: TZReadOnlyQuery; DBEdit2: TDBEdit; DBText3: TDBText; DBText2: TDBText; DBText1: TDBText; qproveedores: TZReadOnlyQuery; qproveedoresIdempresa: TIntegerField; qproveedoresnombre: TWideStringField; qproveedoresid: TIntegerField; dsqproveedores: TDataSource; dsentradasdetalle: TDataSource; Label3: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; DBGrid2: TDBGrid; entradas_detallelote: TWideStringField; entradas_detalletipo_iva: TIntegerField; entradas_detallebase: TFloatField; entradas_detalletotal: TFloatField; entradasid: TIntegerField; entradasidempresa: TIntegerField; entradasfecha: TDateField; entradasidproveedor: TIntegerField; entradasdocumento: TWideStringField; entradasbase: TFloatField; entradastotaliva: TFloatField; entradastotalentrada: TFloatField; qentradasid: TIntegerField; qentradasidempresa: TIntegerField; qentradasfecha: TDateField; qentradasidproveedor: TIntegerField; qentradasdocumento: TWideStringField; qentradasbase: TFloatField; qentradastotaliva: TFloatField; qentradastotalentrada: TFloatField; qentradasnomproveedor: TStringField; DBLookupComboBox2: TDBLookupComboBox; qarticulospropios: TZReadOnlyQuery; qarticulospropioscodigo: TWideStringField; qarticulospropiosdescripcion: TWideStringField; dsarticulospropios: TDataSource; qarticulospropiosidempresa: TIntegerField; DBEdit1: TDBEdit; Panel7: TPanel; Button1: TButton; entradas_detalleidproveedor: TIntegerField; Button2: TButton; procedure qentradasCalcFields(DataSet: TDataSet); procedure FormShow(Sender: TObject); procedure BtENuevoClick(Sender: TObject); procedure BtEborrarClick(Sender: TObject); procedure btEmodificarClick(Sender: TObject); procedure BtEguardarClick(Sender: TObject); procedure BtEcancelarClick(Sender: TObject); procedure dsentradasStateChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure DBGrid2KeyPress(Sender: TObject; var Key: Char); procedure DBGrid2DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBGrid2ColExit(Sender: TObject); procedure entradas_detalleBeforePost(DataSet: TDataSet); procedure Button1Click(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure tbuscarChange(Sender: TObject); procedure qentradasBeforeOpen(DataSet: TDataSet); procedure DBGrid2KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DBGrid1TitleClick(Column: TColumn); procedure Button2Click(Sender: TObject); procedure entradas_detalleAfterPost(DataSet: TDataSet); private { Private declarations } public { Public declarations } var filtro:string; idpropio:string; vertodos:integer; procedure AppMessage(var Msg: Tmsg; var Handled:Boolean); end; var entradas: Tentradas; implementation {$R *.dfm} uses fbuscararticulos, fbuscararticulosprov, ftraza_materiales; procedure Tentradas.AppMessage(var Msg: Tmsg; var Handled: Boolean); var actual : TWincontrol; begin if Msg.message = WM_KEYDOWN then begin // esto es para controlar que con la flecha abajo se desplegen las // listas if Msg.wParam = VK_DOWN then begin Actual := Screen.ActiveControl; if Actual is TDBLookupComboBox then if not TDBLookupComboBox(Screen.ActiveForm.ActiveControl).listVisible then TDBLookupComboBox(Screen.ActiveForm.ActiveControl).DropDown; // si utilizas las RX { if Actual is TRxDBLookupCombo then if not TRxDBLookupCombo(Screen.ActiveForm.ActiveControl).listVisible then TRxDBLookupCombo(Screen.ActiveForm.ActiveControl).DropDown; } if Actual is TComboBox then SendMessage(TComboBox(Screen.ActiveForm.ActiveControl).Handle,CB_SHOWDROPDOWN,-1,0); if (Actual is TCustomEdit) then Msg.wParam := VK_TAB; // se pueden añadir mas controles.... end; // y aqui es el control del intro. if Msg.wParam = VK_RETURN THEN begin Actual := Screen.ActiveControl; // para los edit. if (Actual is TCustomEdit) and not (Actual is TCustomMemo) then Msg.wParam := VK_TAB; // para los memo. Con ctrl + enter se salta de linea dentro del // memo, si solo es intro salta al siguiente control if (Actual is TCustomMemo) and (HiWord(GetKeyState(VK_CONTROL)) = 0)then Msg.wParam := VK_TAB; // para los lookup if Actual is TDBLookupComboBox then if not TDBLookupComboBox(Actual).listVisible then Msg.wParam := VK_TAB; // Si utilizas las RX { if Actual is TRxDBLookupCombo then if not TRxDBLookupCombo(Actual).listVisible then Msg.wParam := VK_TAB; } // Los combobox if Actual is TCustomComboBox then if not TCustomComboBox(Actual).DroppedDown then Msg.wParam := VK_TAB; // el radiobutton if Actual is TRadioButton then Msg.wParam := VK_TAB; // en el grid if Actual is TDBGrid then if (TDBGrid(Actual).ReadOnly) or (HiWord(GetKeyState(VK_CONTROL)) = 1)then Msg.wParam := VK_TAB; // o esto otro Con Ctrl + intro siguiente celda con // ctrl + shift + intro celda anterior // es complicado pero es por no liar con el intro solo // que siempre pasa de un control a otro. if Actual is TDBGrid then begin if (TDBGrid(Actual).ReadOnly) or (HiWord(GetKeyState(VK_CONTROL)) = 0) then Msg.wParam := VK_TAB else if not(HiWord(GetKeyState(VK_SHIFT)) = 0) then begin if TDBGrid(Actual).selectedindex > 0 then { increment the field } TDBGrid(Actual).selectedindex := TDBGrid(Actual).selectedindex -1 else TDBGrid(Actual).selectedindex := TDBGrid(Actual).fieldcount -1; end else begin if TDBGrid(Actual).selectedindex < (TDBGrid(Actual).fieldcount -1) then { increment the field } TDBGrid(Actual).selectedindex := TDBGrid(Actual).selectedindex +1 else TDBGrid(Actual).selectedindex := 0; end; end; // ListBox if Actual is TCustomListBox then Msg.wParam := VK_TAB; // TabControl if Actual is TCustomTabControl then Msg.wParam := VK_TAB; // Aqui se pondrían todos los controles que usamos en la // aplicación y necesitamos cambiar el tab por intro. // de esta forma te despreocupas de cuantos añades y es más // limpio el código end; end; end; procedure Tentradas.BtEborrarClick(Sender: TObject); begin entradas.Delete; qentradas.Refresh; end; procedure Tentradas.BtEcancelarClick(Sender: TObject); begin entradas.Cancel; entradas.MasterSource:=dsqentradas; end; procedure Tentradas.BtEguardarClick(Sender: TObject); begin entradas.Post; qentradas.Refresh; qentradas.Locate('id',entradasid.AsInteger,[locaseinsensitive,lopartialkey]); entradas.MasterSource:=dsqentradas; entradas.Refresh; end; procedure Tentradas.btEmodificarClick(Sender: TObject); begin entradas.edit; dbedit3.SetFocus; end; procedure Tentradas.BtENuevoClick(Sender: TObject); begin entradas.MasterSource:=nil; entradas.append; entradasidempresa.Value:=dm.tempresaid.AsInteger; dbedit3.SetFocus; end; procedure Tentradas.Button1Click(Sender: TObject); begin entradas_detalle.Delete; entradas_detalle.Refresh; entradas.Refresh; end; procedure Tentradas.Button2Click(Sender: TObject); //var tlote,tcodigo,proveedor,documento:string; begin // tlote:=''''+entradas_detallelote.asstring+''''; // tcodigo:=''''+entradas_detalleid_propio.AsString+''''; // proveedor:=''''+qentradasnomproveedor.AsString+''''; // documento:=''''+qentradasdocumento.AsString+''''; traza_materiales := Ttraza_materiales.Create(nil); try traza_materiales.qpesadas.close; traza_materiales.qpesadas.Prepare; traza_materiales.qpesadas.ParamByName('IDENTRADA').AsInteger:=entradas_detalleid.AsInteger; traza_materiales.qpesadas.ParamByName('LOTE').Asstring:=entradas_detalleid.AsString; traza_materiales.qpesadas.open; { traza_materiales.qpesadas2.close; traza_materiales.qpesadas2.SQL.Clear; traza_materiales.qpesadas2.SQL.Add('select '+proveedor+' as proveedor,'+documento+' as documento,'+tcodigo+' as codigo,'+tlote+' as lote,ea.id,idea,fecha,p.iddestino,origen,idorigen,parcela,lotes_detalle,ea.idalbaran,ea.idfactura as factura,c.nombre,p.pedidocliente,cd.descripcion as destino from ea_pesadas ea,pedidos p,clientes c,clientes_destinos cd'); traza_materiales.qpesadas2.SQL.Add(' where c.idempresa=cd.idempresa and c.id=cd.idcliente and cd.codigo=p.iddestino and ea.idempresa=p.ide and ea.pedidocliente=p.id and p.idcliente=c.id and c.idempresa=ea.idempresa and ea.id in (select DISTINCT(idea) from ea_materiales where lote='+tlote+' and idaf=(select id from articulosf where codigo='+tcodigo+')) order by ea.id'); traza_materiales.qpesadas2.open;} traza_materiales.showmodal(); finally traza_materiales.Free; end; end; procedure Tentradas.DBGrid1TitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=qentradas.SortType; qentradas.SortedFields:=Column.FieldName; If st = stAscending then qentradas.SortType:=stDescending else qentradas.SortType:=stAscending; dsqentradas.DataSet.First; end; procedure Tentradas.DBGrid2ColExit(Sender: TObject); begin if DBGrid2.SelectedField.FieldName = DBLookupComboBox2.DataField then DBLookupComboBox2.Visible := False; if (dbgrid2.SelectedField.FieldName='codigo') and (entradas_detalle.State in [dsedit,dsinsert]) and (entradas_detallecodigo.AsString<>'') then begin qaux.SQL.Clear; qaux.SQL.Add('select id,id_propio,descripcion,ult_precio from proveedores_articulos where idempresa='+entradasidempresa.AsString+' and id='+''''+entradas_detallecodigo.asstring+''''+' and idproveedor='+entradasidproveedor.asstring); qaux.Open; if qaux.RecordCount>0 then begin entradas_detalledescripcion.Value:=qaux.Fields[2].AsString; entradas_detalleid_propio.Value:=qaux.Fields[1].AsString; entradas_detalleprecio.Value:=qaux.Fields[3].Asfloat; end; end; end; procedure Tentradas.DBGrid2DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if (gdFocused in State) then begin if (Column.Field.FieldName = DBLookupComboBox2.DataField) then with DBLookupComboBox2 do begin Left := Rect.Left + DBGrid2.Left + 2; Top := Rect.Top + DBGrid2.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; end; end end; procedure Tentradas.DBGrid2KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (key=115) then begin buscararticulosprov := Tbuscararticulosprov.Create(nil); try fbuscararticulosprov.filtro:=entradas_detallecodigo.AsString; buscararticulosprov.Edit1.Text:=entradas_detallecodigo.AsString; buscararticulosprov.showmodal(); finally if entradas_detalle.State in [dsbrowse] then entradas_detalle.Edit; entradas_detallecodigo.Value:=buscararticulosprov.qarticuloscodigo.AsString; entradas_detalledescripcion.value:=buscararticulosprov.qarticulosdescripcion.AsString; buscararticulosprov.Free; end; end; end; procedure Tentradas.DBGrid2KeyPress(Sender: TObject; var Key: Char); begin if (key = Chr(9)) then Exit; if (DBGrid2.SelectedField.FieldName = DBLookupComboBox2.DataField) then begin DBLookupComboBox2.SetFocus; SendMessage(DBLookupComboBox2.Handle, WM_Char, word(Key), 0); end end; procedure Tentradas.dsentradasStateChange(Sender: TObject); begin if entradas.State in [dsedit,dsinsert] then begin Panel14.Enabled:=true; btenuevo.enabled:=false; bteborrar.enabled:=false; btemodificar.enabled:=false; bteguardar.enabled:=true; btecancelar.enabled:=true; panel7.Visible:=false; dbgrid2.Visible:=false; end; if entradas.State in [dsbrowse] then begin Panel14.Enabled:=false; btenuevo.enabled:=true; bteborrar.enabled:=true; btemodificar.enabled:=true; bteguardar.enabled:=false; btecancelar.enabled:=false; panel7.Visible:=true; dbgrid2.Visible:=true; end; end; procedure Tentradas.entradas_detalleAfterPost(DataSet: TDataSet); var preciocompra,tipoiva,idempresa,codigoart:string; begin preciocompra:=entradas_detalleprecio.AsString; preciocompra:=stringreplace(preciocompra,',','.',[rfreplaceall]); tipoiva:=entradas_detalletipo_iva.AsString; tipoiva:=stringreplace(tipoiva,',','.',[rfreplaceall]); idempresa:=entradas_detalleidempresa.AsString; codigoart:=entradas_detalleid_propio.AsString; entradas.Refresh; entradas_detalle.Refresh; qaux.SQL.Clear; qaux.SQL.Add('update articulosf set ult_preciocompra='+preciocompra+',tipoiva=(select id from tipos_iva where tipo='+tipoiva+')'); qaux.SQL.Add(',stock=(select sum(stock) from entradas_detalle where stock>0 and id_propio='+''''+codigoart+''''+' and idempresa='+idempresa+')'); qaux.SQL.Add(',preciocoste='+preciocompra); qaux.SQL.Add(' where idempresa='+idempresa+' and codigo='+''''+codigoart+''''); qaux.execsql; end; procedure Tentradas.entradas_detalleBeforePost(DataSet: TDataSet); begin entradas_detalleidempresa.Value:=dm.tempresaid.AsInteger; if entradas_detallecodigo.asstring='' then entradas_detalle.Cancel; end; procedure Tentradas.FormCreate(Sender: TObject); begin with DBLookupComboBox2 do begin DataSource := dsentradasdetalle; // -> AdoTable1 -> DBGrid1 ListSource := dsarticulospropios; DataField := 'id_propio'; // from AdoTable1 - displayed in the DBGrid KeyField := 'codigo'; ListField := 'descripcion;codigo'; Visible := False; end; end; procedure Tentradas.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tentradas.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is tdbgrid) then begin key:=','; end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tentradas.FormShow(Sender: TObject); begin dm.tempresa.Open; qentradas.Close; qentradas.Open; entradas.Close; entradas.Open; entradas_detalle.Close; entradas_detalle.Open; qproveedores.Open; qarticulospropios.open; end; procedure Tentradas.qentradasBeforeOpen(DataSet: TDataSet); var filtrolocal:string; begin if filtro<>'' then begin begin filtrolocal:=' where nombre like('+''''+filtro+''''+') or nombre_corto like('+''''+filtro+''''+') or id like('+''''+filtro+''''+')'; end; if vertodos=0 then begin begin filtrolocal:=' where idproveedor in (select id from proveedores where nombre like('+''''+filtro+''''+')) or documento like('+''''+filtro+''''+') or id like('+''''+filtro+''''+')'; end; end; end; if filtro='' then begin filtrolocal:=''; end; qentradas.SQL.Clear; qentradas.SQL.Add('select * from entradas ' + filtrolocal +' order by fecha desc,idproveedor') end; procedure Tentradas.qentradasCalcFields(DataSet: TDataSet); begin qaux.SQL.Clear; qaux.SQL.Add('select nombre_corto from proveedores where id='+qentradasidproveedor.asstring+' and idempresa='+qentradasidempresa.asstring); qaux.Open; qentradasnomproveedor.Value:=qaux.Fields[0].AsString; end; procedure Tentradas.tbuscarChange(Sender: TObject); begin filtro:='%'+tbuscar.Text+'%'; qentradas.Close; qentradas.open; end; end. ======================================== FICHERO: fenvasadoscampo.pas ======================================== unit fenvasadoscampo; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ComCtrls, Vcl.ExtCtrls; type TForm1 = class(TForm) Panel1: TPanel; vdesde: TDateTimePicker; vhasta: TDateTimePicker; Label1: TLabel; Label2: TLabel; DBGrid1: TDBGrid; Button1: TButton; private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} end. ======================================== FICHERO: fenvases_almacen.pas ======================================== unit fenvases_almacen; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,principal,datosclientes,datos, Vcl.StdCtrls, Vcl.DBCtrls, Vcl.Mask, Vcl.ComCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls,DATA.DB, ZAbstractRODataset, ZDataset; type Tenvases_almacen = class(TForm) Panel1: TPanel; Panel2: TPanel; Panel5: TPanel; Label1: TLabel; todosarticulos: TCheckBox; tbuscar: TEdit; DBGrid1: TDBGrid; particulos: TPanel; pdatosarticulos: TPanel; Panel14: TPanel; Label10: TLabel; Label11: TLabel; Label2: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label8: TLabel; Label3: TLabel; DBCheckBox2: TDBCheckBox; DBEdit1: TDBEdit; DBEdit10: TDBEdit; DBEdit12: TDBEdit; DBEdit3: TDBEdit; DBEdit4: TDBEdit; DBEdit9: TDBEdit; DBMemo1: TDBMemo; Panel4: TPanel; Label36: TLabel; btEAcancelar: TButton; btEAmodificar: TButton; btEAborrar: TButton; btEAnuevo: TButton; btEAguardar: TButton; Detallesarticulos: TPageControl; TComponentes: TTabSheet; Panel10: TPanel; Label32: TLabel; DBGrid7: TDBGrid; DBEdit121: TDBEdit; Label213: TLabel; DBEdit120: TDBEdit; Label211: TLabel; DBEdit118: TDBEdit; DBCheckBox28: TDBCheckBox; DBCheckBox26: TDBCheckBox; DBCheckBox27: TDBCheckBox; DBCheckBox32: TDBCheckBox; qaux: TZReadOnlyQuery; DBGrid2: TDBGrid; Panel3: TPanel; btALnuevo: TButton; btALborrar: TButton; Panel6: TPanel; Label7: TLabel; tbuscarcomponentes: TEdit; Label13: TLabel; DBEdit5: TDBEdit; Label14: TLabel; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); procedure tbuscarChange(Sender: TObject); procedure todosarticulosClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btEAnuevoClick(Sender: TObject); procedure btEAborrarClick(Sender: TObject); procedure btEAmodificarClick(Sender: TObject); procedure btEAguardarClick(Sender: TObject); procedure btEAcancelarClick(Sender: TObject); procedure btALnuevoClick(Sender: TObject); procedure btALborrarClick(Sender: TObject); procedure tbuscarcomponentesChange(Sender: TObject); procedure todoscomponentesClick(Sender: TObject); procedure DBGrid1TitleClick(Column: TColumn); procedure DBEdit4Exit(Sender: TObject); private { Private declarations } public { Public declarations } end; var envases_almacen: Tenvases_almacen; implementation {$R *.dfm} procedure Tenvases_almacen.btEAcancelarClick(Sender: TObject); begin dm.dtarticulosalmacen.cancel; dm.dtarticulosalmacen.MasterSource:=dm.dsqarticulosalmacen; end; procedure Tenvases_almacen.btEAmodificarClick(Sender: TObject); begin dm.dtarticulosalmacen.MasterSource:=nil; dm.dtarticulosalmacen.edit; dbedit1.SetFocus; end; procedure Tenvases_almacen.btALborrarClick(Sender: TObject); var observaciones:string; begin dm.dtarticulos_componentes.Delete; dm.dtarticulos_componentes.Refresh; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('select * from articulos_componentes where idempresa='+dm.dtarticulosalmacenide.Asstring+' and idarticuloalmacen='+dm.dtarticulosalmacenid.Asstring); qaux.open; qaux.First; observaciones:='LLEVA '; while not qaux.eof do begin observaciones:=observaciones+qaux.fields[4].asstring+' X '+qaux.fields[3].asstring+','; qaux.next; end; observaciones:=observaciones+' REVISADO EL '+datetostr(date()); qaux.close; qaux.SQL.Clear; qaux.SQL.Add('select sum(peso),sum(coste) from articulos_componentes where idempresa='+dm.dtarticulosalmacenide.Asstring+' and idarticuloalmacen='+dm.dtarticulosalmacenid.Asstring); qaux.open; dm.dtarticulosalmacen.Edit; dm.dtarticulosalmacentara.Value:=qaux.Fields[0].AsFloat; dm.dtarticulosalmacencosto.Value:=qaux.Fields[1].AsFloat; dm.dtarticulosalmacenobservaciones.Value:=observaciones; dm.dtarticulosalmacen.Refresh; end; procedure Tenvases_almacen.btALnuevoClick(Sender: TObject); var cantidad,idempresa,idarticuloalmacen,idarticulof:integer; observaciones:string; begin qaux.SQL.Clear; qaux.SQL.Add('select * from articulos_componentes where idempresa='+dm.dtarticulosalmacenide.Asstring+' and idarticuloalmacen='+dm.dtarticulosalmacenid.Asstring+' and idarticulof='+dmclientes.qarticulosfinalid.Asstring); qaux.Open; if qaux.RecordCount>0 then begin cantidad:=qaux.Fields[4].AsInteger; idempresa:=qaux.Fields[0].AsInteger; idarticuloalmacen:=qaux.Fields[1].AsInteger; idarticulof:=qaux.Fields[2].AsInteger; dm.dtarticulos_componentes.Locate('idempresa;idarticuloalmacen;idarticulof',vararrayof([idempresa,idarticuloalmacen,idarticulof]),[locaseinsensitive]); dm.dtarticulos_componentes.edit; dm.dtarticulos_componentescantidad.Value:=cantidad+1; // dm.dtarticulos_componentescoste.value:=dm.dtarticulos_componentescantidad.AsFloat*dm.dtarticulos_componentespreciocoste.AsFloat; // dm.dtarticulos_componentespeso.value:=dm.dtarticulos_componentescantidad.AsFloat*dm.dtarticulos_componentespeso.AsFloat; dm.dtarticulos_componentes.Post; end else begin dm.dtarticulos_componentes.Append; dm.dtarticulos_componentesidempresa.Value:=dm.dtarticulosalmacenide.AsInteger; dm.dtarticulos_componentesidarticuloalmacen.Value:=dm.dtarticulosalmacenid.AsInteger; dm.dtarticulos_componentesidarticulof.Value:=dmclientes.qarticulosfinalid.AsInteger; dm.dtarticulos_componentesdescripcion.Value:=dmclientes.qarticulosfinaldescripcion.Asstring; dm.dtarticulos_componentespeso.Value:=dmclientes.qarticulosfinalpeso.Asfloat; dm.dtarticulos_componentescantidad.Value:=1; // dm.dtarticulos_componentespreciocoste.Value:=dmclientes.qarticulosfinalpreciocoste.Asfloat; // dm.dtarticulos_componentescoste.Value:=dm.dtarticulos_componentescantidad.AsFloat*dm.dtarticulos_componentespreciocoste.AsFloat; dm.dtarticulos_componentes.Post; end; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('select * from articulos_componentes where idempresa='+dm.dtarticulosalmacenide.Asstring+' and idarticuloalmacen='+dm.dtarticulosalmacenid.Asstring); qaux.open; qaux.First; observaciones:='LLEVA '; while not qaux.eof do begin observaciones:=observaciones+qaux.fields[4].asstring+' X '+qaux.fields[3].asstring+','; qaux.next; end; observaciones:=observaciones+' REVISADO EL '+datetostr(date()); qaux.close; qaux.SQL.Clear; qaux.SQL.Add('select sum(peso),sum(coste) from articulos_componentes where idempresa='+dm.dtarticulosalmacenide.Asstring+' and idarticuloalmacen='+dm.dtarticulosalmacenid.Asstring); qaux.open; dm.dtarticulosalmacen.Edit; dm.dtarticulosalmacentara.Value:=qaux.Fields[0].AsFloat; dm.dtarticulosalmacencosto.Value:=qaux.Fields[1].AsFloat; dm.dtarticulosalmacenobservaciones.Value:=observaciones; dm.dtarticulosalmacen.Refresh; end; procedure Tenvases_almacen.btEAborrarClick(Sender: TObject); begin dm.dtarticulosalmacen.delete; dm.qarticulosalmacen.Refresh; end; procedure Tenvases_almacen.btEAnuevoClick(Sender: TObject); begin qaux.SQL.Clear; qaux.SQL.Add('select max(id)+1 from articulos_almacen'); qaux.Open; dm.dtarticulosalmacen.MasterSource:=nil; dm.dtarticulosalmacen.append; dm.dtarticulosalmacenactivo.Value:=1; dbedit1.SetFocus; dbedit1.Text:=qaux.Fields[0].AsString; end; procedure Tenvases_almacen.DBEdit4Exit(Sender: TObject); begin dm.dtarticulosalmacendescripcion.Value:=dm.dtarticulosalmacendescripcion2.AsString; end; procedure Tenvases_almacen.DBGrid1TitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=dm.qarticulosalmacen.SortType; dm.qarticulosalmacen.SortedFields:=Column.FieldName; If st = stAscending then dm.qarticulosalmacen.SortType:=stDescending else dm.qarticulosalmacen.SortType:=stAscending; dm.dsqarticulosalmacen.DataSet.First; end; procedure Tenvases_almacen.todoscomponentesClick(Sender: TObject); begin { if todoscomponentes.Checked=true then begin dmclientes.vertodos:=1; dmclientes.qarticulosfinal.Close; dmclientes.qarticulosfinal.SQL.Clear; dmclientes.qarticulosfinal.SQL.add('select * from articulosf order by descripcion asc'); dmclientes.qarticulosfinal.Open; end else begin dmclientes.vertodos:=0; dmclientes.qarticulosfinal.Close; dmclientes.qarticulosfinal.SQL.Clear; dmclientes.qarticulosfinal.SQL.add('select * from articulosf where activo=1 order by descripcion asc'); dmclientes.qarticulosfinal.Open; end;} end; procedure Tenvases_almacen.tbuscarcomponentesChange(Sender: TObject); begin dmclientes.filtro:='%'+tbuscarcomponentes.Text+'%'; dmclientes.vertodosmateriales:=0; dmclientes.qarticulosfinal.Close; dmclientes.qarticulosfinal.open; end; procedure Tenvases_almacen.btEAguardarClick(Sender: TObject); begin dm.dtarticulosalmacen.Post; dm.qarticulosalmacen.Refresh; dm.qarticulosalmacen.Locate('id',dm.dtarticulosalmacenid.AsInteger,[locaseinsensitive,lopartialkey]); dm.dtarticulosalmacen.MasterSource:=dm.dsqarticulosalmacen; end; procedure Tenvases_almacen.FormClose(Sender: TObject; var Action: TCloseAction); begin dm.qarticulosalmacen.close; dmclientes.qarticulosfinal.close; dmclientes.filtro:=''; dmclientes.vertodos:=0; dmclientes.vertodosmateriales:=0; end; procedure Tenvases_almacen.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tenvases_almacen.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is tdbgrid) then begin key:=','; end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tenvases_almacen.FormShow(Sender: TObject); begin if not dm.qarticulosalmacen.Active then dm.qarticulosalmacen.Open else dm.qarticulosalmacen.Refresh; if not dmclientes.qarticulosfinal.Active then dmclientes.qarticulosfinal.open else dmclientes.qarticulosfinal.refresh; if not dm.dtarticulos_componentes.Active then dm.dtarticulos_componentes.open else dm.dtarticulos_componentes.refresh; end; procedure Tenvases_almacen.tbuscarChange(Sender: TObject); begin dm.filtro:='%'+tbuscar.Text+'%'; if todosarticulos.Checked then dm.vertodos:=1 else dm.vertodos:=0; dm.qarticulosalmacen.Close; dm.qarticulosalmacen.open; end; procedure Tenvases_almacen.todosarticulosClick(Sender: TObject); begin if todosarticulos.Checked=true then begin dm.vertodos:=1; dm.qarticulosalmacen.Close; dm.qarticulosalmacen.Open; end else begin dm.vertodos:=0; dm.qarticulosalmacen.Close; dm.qarticulosalmacen.Open; end; end; end. ======================================== FICHERO: fepis.pas ======================================== unit fepis; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls; type Tepis = class(TForm) Panel1: TPanel; Panel2: TPanel; DBGrid1: TDBGrid; Panel3: TPanel; Panel4: TPanel; DBGrid2: TDBGrid; Panel7: TPanel; btAcancelar: TButton; btAmodificar: TButton; btAborrar: TButton; btAnuevo: TButton; btAguardar: TButton; dsqepis: TDataSource; qidepis: TZQuery; qepis: TZQuery; qepisid: TIntegerField; qepiside: TIntegerField; qepisdescripcion: TWideStringField; qidepisid: TLargeintField; procedure btAnuevoClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure btAguardarClick(Sender: TObject); procedure btAmodificarClick(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var epis: Tepis; implementation {$R *.dfm} uses datos; procedure Tepis.btAborrarClick(Sender: TObject); begin qepis.Delete; end; procedure Tepis.btAcancelarClick(Sender: TObject); begin qepis.Cancel; end; procedure Tepis.btAguardarClick(Sender: TObject); begin qepis.Post; end; procedure Tepis.btAmodificarClick(Sender: TObject); begin qepis.Edit; end; procedure Tepis.btAnuevoClick(Sender: TObject); begin qidepis.Close; qidepis.Prepare; qidepis.ParamByName('empresa').AsInteger:=dm.tempresaid.asinteger; qidepis.open; qepis.append; qepisid.Value:=qidepisid.asinteger; qepiside.value:=dm.tempresaid.asinteger; dbgrid2.setfocus; end; procedure Tepis.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tepis.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tepis.FormShow(Sender: TObject); begin qepis.Open; end; end. ======================================== FICHERO: ffacturas.pas ======================================== unit ffacturas; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.DBCtrls, Vcl.Mask, Vcl.ExtCtrls, Vcl.ComCtrls, Data.DB, math, ZAbstractRODataset, ZAbstractDataset, ZDataset, frxClass, frxDBSet, datos, ComObj, Excel2000, frxExportPDF, frxExportBaseDialog, wincrypt; type Tfacturas = class(TForm) pestañas: TPageControl; tabdetalles: TTabSheet; Panel8: TPanel; Panel9: TPanel; btfcancelar: TButton; btfmodificar: TButton; btfborrar: TButton; btfnuevo: TButton; btfguardar: TButton; btfimprimir: TButton; btfimportar: TButton; btfsiguiente: TButton; btfanterior: TButton; Panel10: TPanel; Label16: TLabel; Label17: TLabel; DBText1: TDBText; DBText2: TDBText; DBText16: TDBText; DBText17: TDBText; DBText18: TDBText; DBText19: TDBText; DBText20: TDBText; DBText21: TDBText; DBText22: TDBText; DBText23: TDBText; DBText24: TDBText; DBText25: TDBText; DBText26: TDBText; paneldatos: TPanel; Label18: TLabel; Label19: TLabel; Label20: TLabel; Label21: TLabel; Label22: TLabel; Label23: TLabel; comboseries: TDBLookupComboBox; DBEdit10: TDBEdit; comboclientes: TDBLookupComboBox; combodestinos: TDBLookupComboBox; DBEdit11: TDBEdit; DBMemo4: TDBMemo; Panel12: TPanel; Label28: TLabel; Label29: TLabel; Label30: TLabel; Panel13: TPanel; DBGrid4: TDBGrid; DBEdit12: TDBEdit; DBEdit13: TDBEdit; DBEdit14: TDBEdit; DBEdit15: TDBEdit; DBEdit16: TDBEdit; DBEdit17: TDBEdit; DBEdit18: TDBEdit; DBGrid5: TDBGrid; Panel14: TPanel; Button16: TButton; tablistado: TTabSheet; DBGrid6: TDBGrid; infdetallefactura: TfrxDBDataset; inffactura: TfrxDBDataset; inffacturaivas: TfrxDBDataset; informe: TfrxReport; dsfacturas: TDataSource; facturas: TZQuery; dsfacturasdetalle: TDataSource; facturasdetalle: TZQuery; dsqseries: TDataSource; dsqclientes: TDataSource; qclientes: TZQuery; qseries: TZQuery; dsqdestinos: TDataSource; qdestinos: TZQuery; qdestinoscodigo: TWideStringField; qdestinosidcliente: TIntegerField; qdestinosidempresa: TIntegerField; qdestinosdescripcion: TWideStringField; qdestinosseleccionado: TIntegerField; qdestinosactivo: TIntegerField; qdestinosdireccion: TWideStringField; qdestinospoblacion: TWideStringField; qdestinoscodpost: TWideStringField; qdestinosprovincia: TWideStringField; qdestinospais: TWideStringField; dsqfacturasiva: TDataSource; qfacturasiva: TZQuery; qalbaranes: TZQuery; qalbaranesdetalle: TZQuery; dsqalbaranes: TDataSource; dsqalbaranesdetalle: TDataSource; facturasid: TIntegerField; facturasidempresa: TIntegerField; facturasidcliente: TIntegerField; facturasiddestino: TWideStringField; facturasnif: TWideStringField; facturasdireccion: TWideStringField; facturaspoblacion: TWideStringField; facturasprovincia: TWideStringField; facturascodpost: TWideStringField; facturasfecha: TDateField; facturasreferencia: TWideStringField; facturastelefono: TWideStringField; facturasnomcliente: TWideStringField; facturaspaiscliente: TWideStringField; facturasnomdestino: TWideStringField; facturasdirecciondestino: TWideStringField; facturaspoblaciondestino: TWideStringField; facturascodpostdestino: TWideStringField; facturasprovinciadestino: TWideStringField; facturaspaisdestino: TWideStringField; facturasneto: TFloatField; facturastotal: TFloatField; facturasdocumento: TWideStringField; facturasdescuento_lin: TFloatField; facturasdescuento_com: TFloatField; facturasdescuento_pp: TFloatField; facturasdescuento_total: TFloatField; facturastotaliva: TFloatField; facturasobservaciones: TWideStringField; facturasdetalleid: TIntegerField; facturasdetalleidempresa: TIntegerField; facturasdetalleidfactura: TIntegerField; facturasdetalleidarticulo: TWideStringField; facturasdetallecal: TWideStringField; facturasdetallelote: TWideStringField; facturasdetallecantidad: TFloatField; facturasdetalleprecio: TFloatField; facturasdetalledescuento: TFloatField; facturasdetalletotaldescuento: TFloatField; facturasdetallebase: TFloatField; facturasdetalletipoiva: TFloatField; facturasdetalleiva: TFloatField; facturasdetalletotal: TFloatField; qserieside: TIntegerField; qseriesid: TWideStringField; qseriesfechainicio: TDateField; qseriesfechafin: TDateField; qseriesnum_pedcliente: TIntegerField; qseriesnum_albaran: TIntegerField; qseriesnum_factura: TIntegerField; qseriesnum_expedicion: TIntegerField; qseriesnum_pedproveedor: TIntegerField; qclientesid: TIntegerField; qclientesIdempresa: TIntegerField; qclientesnif: TWideStringField; qclientesnombre: TWideStringField; qclientesnombre_corto: TWideStringField; qclientesdireccion: TWideStringField; qclientespoblacion: TWideStringField; qclientescodpost: TWideStringField; qclientesprovincia: TWideStringField; qclientestelefono: TWideStringField; qclientestelefono2: TWideStringField; qclientesmovil: TWideStringField; qclientesemail: TWideStringField; qclientespersonacontacto: TWideStringField; qclientescodigomercado: TIntegerField; qclientesactivo: TIntegerField; qclientesobservaciones: TWideStringField; qclientesccontable: TIntegerField; qclientesdescuento: TFloatField; qclientespais: TWideStringField; qalbaranesid: TIntegerField; qalbaranesidempresa: TIntegerField; qalbaranesidcliente: TIntegerField; qalbaranesiddestino: TWideStringField; qalbaranesnif: TWideStringField; qalbaranesdireccion: TWideStringField; qalbaranespoblacion: TWideStringField; qalbaranesprovincia: TWideStringField; qalbaranescodpost: TWideStringField; qalbaranesfecha: TDateField; qalbaranesreferencia: TWideStringField; qalbaranestelefono: TWideStringField; qalbaranesnomcliente: TWideStringField; qalbaranespaiscliente: TWideStringField; qalbaranesnomdestino: TWideStringField; qalbaranesdirecciondestino: TWideStringField; qalbaranespoblaciondestino: TWideStringField; qalbaranescodpostdestino: TWideStringField; qalbaranesprovinciadestino: TWideStringField; qalbaranespaisdestino: TWideStringField; qalbaranesneto: TFloatField; qalbaranestotal: TFloatField; qalbaranesfacturado: TIntegerField; qalbaranesdocumento: TWideStringField; qalbaranesdescuento_lin: TFloatField; qalbaranesdescuento_com: TFloatField; qalbaranesdescuento_pp: TFloatField; qalbaranesdescuento_total: TFloatField; qalbaranestotaliva: TFloatField; qalbaranesobservaciones: TWideStringField; qalbaranesidfactura: TIntegerField; qalbaranesdetalleid: TIntegerField; qalbaranesdetalleidempresa: TIntegerField; qalbaranesdetalleidalbaran: TIntegerField; qalbaranesdetalleidarticulo: TWideStringField; qalbaranesdetalledescripcion: TWideStringField; qalbaranesdetallecal: TWideStringField; qalbaranesdetallelote: TWideStringField; qalbaranesdetallecantidad: TFloatField; qalbaranesdetalleprecio: TFloatField; qalbaranesdetalledescuento: TFloatField; qalbaranesdetalletotaldescuento: TFloatField; qalbaranesdetallebase: TFloatField; qalbaranesdetalletipoiva: TFloatField; qalbaranesdetalleiva: TFloatField; qalbaranesdetalletotal: TFloatField; dsqalbaranes2: TDataSource; qalbaranes2: TZQuery; dsqalbaranesdetalle2: TDataSource; qalbaranesdetalle2: TZQuery; qfacturasivaidfactura: TIntegerField; qfacturasivaide: TIntegerField; qfacturasivabase: TFloatField; qfacturasivatipo: TFloatField; qfacturasivaiva: TFloatField; qalbaranes2id: TIntegerField; qalbaranes2idempresa: TIntegerField; qalbaranes2idcliente: TIntegerField; qalbaranes2iddestino: TWideStringField; qalbaranes2nif: TWideStringField; qalbaranes2direccion: TWideStringField; qalbaranes2poblacion: TWideStringField; qalbaranes2provincia: TWideStringField; qalbaranes2codpost: TWideStringField; qalbaranes2fecha: TDateField; qalbaranes2referencia: TWideStringField; qalbaranes2telefono: TWideStringField; qalbaranes2nomcliente: TWideStringField; qalbaranes2paiscliente: TWideStringField; qalbaranes2nomdestino: TWideStringField; qalbaranes2direcciondestino: TWideStringField; qalbaranes2poblaciondestino: TWideStringField; qalbaranes2codpostdestino: TWideStringField; qalbaranes2provinciadestino: TWideStringField; qalbaranes2paisdestino: TWideStringField; qalbaranes2neto: TFloatField; qalbaranes2total: TFloatField; qalbaranes2facturado: TIntegerField; qalbaranes2documento: TWideStringField; qalbaranes2descuento_lin: TFloatField; qalbaranes2descuento_com: TFloatField; qalbaranes2descuento_pp: TFloatField; qalbaranes2descuento_total: TFloatField; qalbaranes2totaliva: TFloatField; qalbaranes2observaciones: TWideStringField; qalbaranes2idfactura: TIntegerField; qalbaranesdetalle2id: TIntegerField; qalbaranesdetalle2idempresa: TIntegerField; qalbaranesdetalle2idalbaran: TIntegerField; qalbaranesdetalle2idarticulo: TWideStringField; qalbaranesdetalle2descripcion: TWideStringField; qalbaranesdetalle2cal: TWideStringField; qalbaranesdetalle2lote: TWideStringField; qalbaranesdetalle2cantidad: TFloatField; qalbaranesdetalle2precio: TFloatField; qalbaranesdetalle2descuento: TFloatField; qalbaranesdetalle2totaldescuento: TFloatField; qalbaranesdetalle2base: TFloatField; qalbaranesdetalle2tipoiva: TFloatField; qalbaranesdetalle2iva: TFloatField; qalbaranesdetalle2total: TFloatField; qaux: TZQuery; facturasserie: TWideStringField; facturasdetalleserie: TWideStringField; qalbaranes2serie: TWideStringField; qalbaranesdetalle2serie: TWideStringField; qalbaranesserie: TWideStringField; qalbaranesdetalleserie: TWideStringField; qfacturasivaserie: TWideStringField; qseriesimp_albaran: TWideStringField; qseriesimp_factura: TWideStringField; facturasbultos: TFloatField; facturaskilos: TFloatField; facturasidformapago: TIntegerField; Label31: TLabel; comboformapago: TDBLookupComboBox; qformaspago: TZQuery; dsqformaspago: TDataSource; qformaspagoide: TIntegerField; qformaspagoid: TIntegerField; qformaspagocodigo: TWideStringField; qformaspagodescripcion: TWideStringField; qformaspagodias: TIntegerField; qclientesidformapago: TIntegerField; qalbaranesdetallebultos: TFloatField; qalbaranesdetalle2bultos: TFloatField; dsqarticulos: TDataSource; qarticulos: TZReadOnlyQuery; qtipos_iva: TZReadOnlyQuery; DataSource1: TDataSource; qtipos_ivaid: TIntegerField; qtipos_ivadescripcion: TWideStringField; qtipos_ivatipo: TIntegerField; qtipos_ivatipo_req: TFloatField; qarticulosidempresa: TIntegerField; qarticulosid: TIntegerField; qarticuloscodigo: TWideStringField; qarticulosdescripcion: TWideStringField; qarticulosfamilia: TIntegerField; qarticulosprovhab: TIntegerField; qarticulostipoiva: TIntegerField; qarticulospreciocoste: TFloatField; qarticulosmargen: TFloatField; qarticulosbeneficio: TFloatField; qarticulospvp: TFloatField; qarticulosstock: TFloatField; qarticulosult_preciocompra: TFloatField; qarticulosfacturable: TIntegerField; qarticulosobservaciones: TWideStringField; qarticulosimagen: TBlobField; qarticulosactivo: TIntegerField; qarticulosvalor_almacen: TFloatField; qarticulosstock_minimo: TFloatField; qarticulosavisar_stock: TIntegerField; qarticuloscontrolar_traza: TIntegerField; qarticulospeso: TFloatField; listaimpresion: TComboBox; facturasdetallebultos: TFloatField; Panel11: TPanel; gridfacturasaexcel: TDBGrid; qfacturasclientes: TZReadOnlyQuery; dsqfacturasclientes: TDataSource; SaveDialog1: TSaveDialog; qclientesexento_iva: TIntegerField; facturascobrado: TIntegerField; DBCheckBox2: TDBCheckBox; Panel15: TPanel; listaclientes: TZQuery; listaclientesnif: TWideStringField; listaclientesnomcliente: TWideStringField; listadestinos: TZQuery; dslistadestinos: TDataSource; dslistacliente: TDataSource; listadestinosnomdestino: TWideStringField; btfiltrar: TButton; frxPDFExport1: TfrxPDFExport; qconta_subcta: TZQuery; qconta_subctacuenta: TWideStringField; qconta_subctatitulo: TWideStringField; qconta_subctanif: TWideStringField; qconta_subctadomicilio: TWideStringField; qconta_subctapoblacion: TWideStringField; qconta_subctaprovincia: TWideStringField; qconta_subctacodpost: TWideStringField; qconta_subctaint1: TWideStringField; qclientes_conta: TZQuery; qclientes_contanif: TWideStringField; qclientes_contanombre: TWideStringField; qclientes_contadireccion: TWideStringField; qclientes_contapoblacion: TWideStringField; qclientes_contacodpost: TWideStringField; qclientes_contaprovincia: TWideStringField; qclientes_contaccontable: TIntegerField; qconta_diario: TZQuery; qconta_diarioasiento: TWideStringField; qconta_diariofecha: TWideStringField; qconta_diariocuenta: TWideStringField; qconta_diariocontrapartida: TWideStringField; qconta_diarioconcepto: TWideStringField; qconta_diariofactura: TWideStringField; qconta_diariofecha_recep: TWideStringField; qconta_diarioiva: TWideStringField; qconta_diariorec_equiv: TWideStringField; qconta_diariodocumento: TWideStringField; qconta_diarioserie: TWideStringField; qconta_diarioaccion: TWideStringField; qconta_diariooperacioniva: TWideStringField; qconta_diarioorigen: TWideStringField; qconta_diariotipoapunte: TWideStringField; qconta_diarioimpdebe: TWideStringField; qconta_diarioimphaber: TWideStringField; qconta_diariobaseimpo: TWideStringField; qaux2: TZQuery; qaux2serie: TWideStringField; qaux2idfactura: TIntegerField; qaux2ide: TIntegerField; qaux2base: TFloatField; qaux2tipo: TFloatField; qaux2iva: TFloatField; qclientes_contaid: TIntegerField; qconta_diariointerno1: TWideStringField; qconta_diariointerno2: TWideStringField; qconta_diariointerno3: TWideStringField; qconta_diariointerno4: TWideStringField; qconta_diariointerno5: TWideStringField; qconta_diariointerno6: TWideStringField; qconta_diariointerno7: TWideStringField; qconta_diariointerno8: TWideStringField; qconta_diariointerno9: TWideStringField; qconta_diariointerno10: TWideStringField; qconta_diariointerno11: TWideStringField; qconta_diariointerno12: TWideStringField; qconta_diariointerno13: TWideStringField; qaux3: TZQuery; WideStringField1: TWideStringField; IntegerField1: TIntegerField; IntegerField2: TIntegerField; FloatField1: TFloatField; FloatField2: TFloatField; FloatField3: TFloatField; facturasdetalleidalbaran: TIntegerField; btacumulados: TButton; DBGridacumulados: TDBGrid; dsfacturasacumuladas: TDataSource; facturasacumuladas: TZQuery; facturasacumuladasidempresa: TIntegerField; facturasacumuladasidcliente: TIntegerField; facturasacumuladasnif: TWideStringField; facturasacumuladasnomcliente: TWideStringField; facturasacumuladassumtotal: TFloatField; Label1: TLabel; Edit1: TEdit; Button1: TButton; facturascc_pago: TWideStringField; facturasccid: TIntegerField; facturascccuentabancaria: TWideStringField; Label9: TLabel; Label3: TLabel; Label8: TLabel; Label10: TLabel; combocuenta: TDBLookupComboBox; Label4: TLabel; DBText3: TDBText; Label5: TLabel; costetrans: TDBEdit; DBText4: TDBText; DBText5: TDBText; DBText6: TDBText; DBText7: TDBText; Label6: TLabel; comision: TDBEdit; Label7: TLabel; facturascomision: TFloatField; facturascoste_transporte: TFloatField; facturaspeso_bruto: TFloatField; facturasprov_transporte: TWideStringField; facturaskilosventa: TFloatField; facturasnumpalets: TFloatField; facturasdetallecoste_transporte: TFloatField; facturasdetallecoste_otros: TFloatField; facturasdetallecoste_comision: TFloatField; Button2: TButton; Button5: TButton; qcuentas: TZReadOnlyQuery; qcuentaside: TIntegerField; qcuentasid: TIntegerField; qcuentasbanco: TWideStringField; qcuentascciban: TWideStringField; qcuentasccentidad: TWideStringField; qcuentasccoficina: TWideStringField; qcuentasccdc: TWideStringField; qcuentascccc: TWideStringField; dsqcuentas: TDataSource; qalbaranesdetallecoste_transporte: TFloatField; qalbaranesdetallecoste_otros: TFloatField; qalbaranesdetallecoste_comision: TFloatField; qalbaranesdetalle2coste_transporte: TFloatField; qalbaranesdetalle2coste_otros: TFloatField; qalbaranesdetalle2coste_comision: TFloatField; Panel2: TPanel; Panel3: TPanel; Panel4: TPanel; Label11: TLabel; Label2: TLabel; Edit2: TEdit; comboserie2: TDBLookupComboBox; Label34: TLabel; Label35: TLabel; fdesde: TDateTimePicker; fhasta: TDateTimePicker; Label32: TLabel; Label33: TLabel; combolistcliente: TDBLookupComboBox; Button8: TButton; combolistdestinos: TDBLookupComboBox; Button7: TButton; Button3: TButton; Button9: TButton; dsqseries2: TDataSource; qseries2: TZReadOnlyQuery; qseries2ide: TIntegerField; qseries2id: TWideStringField; qseries2fechainicio: TDateField; qseries2fechafin: TDateField; qseries2num_pedcliente: TIntegerField; qseries2num_albaran: TIntegerField; qseries2num_factura: TIntegerField; qseries2num_expedicion: TIntegerField; qseries2num_pedproveedor: TIntegerField; qseries2imp_albaran: TWideStringField; qseries2imp_factura: TWideStringField; qseries2activo: TIntegerField; qseries2num_presupuesto: TIntegerField; facturasdetallepesobruto: TFloatField; facturasdetalledescripcion: TWideStringField; Button4: TButton; qfacturasclientesserie: TWideStringField; qfacturasclientesid: TIntegerField; qfacturasclientesidempresa: TIntegerField; qfacturasclientesidcliente: TIntegerField; qfacturasclientesiddestino: TWideStringField; qfacturasclientesnif: TWideStringField; qfacturasclientesdireccion: TWideStringField; qfacturasclientespoblacion: TWideStringField; qfacturasclientesprovincia: TWideStringField; qfacturasclientescodpost: TWideStringField; qfacturasclientesfecha: TDateField; qfacturasclientesreferencia: TWideStringField; qfacturasclientestelefono: TWideStringField; qfacturasclientesnomcliente: TWideStringField; qfacturasclientespaiscliente: TWideStringField; qfacturasclientesnomdestino: TWideStringField; qfacturasclientesdirecciondestino: TWideStringField; qfacturasclientespoblaciondestino: TWideStringField; qfacturasclientescodpostdestino: TWideStringField; qfacturasclientesprovinciadestino: TWideStringField; qfacturasclientespaisdestino: TWideStringField; qfacturasclientesneto: TFloatField; qfacturasclientestotal: TFloatField; qfacturasclientescobrado: TIntegerField; qfacturasclientesdocumento: TWideStringField; qfacturasclientesdescuento_lin: TFloatField; qfacturasclientesdescuento_com: TFloatField; qfacturasclientesdescuento_pp: TFloatField; qfacturasclientesdescuento_total: TFloatField; qfacturasclientestotaliva: TFloatField; qfacturasclientesobservaciones: TWideStringField; qfacturasclientesbultos: TFloatField; qfacturasclienteskilos: TFloatField; qfacturasclientesidformapago: TIntegerField; qfacturasclientescc_pago: TWideStringField; qfacturasclientesccid: TIntegerField; qfacturasclientescccuentabancaria: TWideStringField; qfacturasclientescomision: TFloatField; qfacturasclientescoste_transporte: TFloatField; qfacturasclientespeso_bruto: TFloatField; qfacturasclientesprov_transporte: TWideStringField; qfacturasclienteskilosventa: TFloatField; qfacturasclientesnumpalets: TFloatField; qfacturasclientesid_1: TIntegerField; qfacturasclientesidempresa_1: TIntegerField; qfacturasclientesserie_1: TWideStringField; qfacturasclientesidfactura: TIntegerField; qfacturasclientesidarticulo: TWideStringField; qfacturasclientesdescripcion: TWideStringField; qfacturasclientescal: TWideStringField; qfacturasclienteslote: TWideStringField; qfacturasclientesbultos_1: TFloatField; qfacturasclientescantidad: TFloatField; qfacturasclientesprecio: TFloatField; qfacturasclientesdescuento: TFloatField; qfacturasclientestotaldescuento: TFloatField; qfacturasclientesbase: TFloatField; qfacturasclientestipoiva: TFloatField; qfacturasclientesiva: TFloatField; qfacturasclientestotal_1: TFloatField; qfacturasclientesidalbaran: TIntegerField; qfacturasclientescoste_otros: TFloatField; qfacturasclientescoste_comision: TFloatField; qfacturasclientespesobruto: TFloatField; qfacturasclientesparcela: TWideStringField; qfacturasclientes2: TZReadOnlyQuery; dsqfacturasclientes2: TDataSource; gridfacturasaexcel2: TDBGrid; qfacturasclientes2serie: TWideStringField; qfacturasclientes2id: TIntegerField; qfacturasclientes2idempresa: TIntegerField; qfacturasclientes2idcliente: TIntegerField; qfacturasclientes2iddestino: TWideStringField; qfacturasclientes2nif: TWideStringField; qfacturasclientes2direccion: TWideStringField; qfacturasclientes2poblacion: TWideStringField; qfacturasclientes2provincia: TWideStringField; qfacturasclientes2codpost: TWideStringField; qfacturasclientes2fecha: TDateField; qfacturasclientes2referencia: TWideStringField; qfacturasclientes2telefono: TWideStringField; qfacturasclientes2nomcliente: TWideStringField; qfacturasclientes2paiscliente: TWideStringField; qfacturasclientes2nomdestino: TWideStringField; qfacturasclientes2direcciondestino: TWideStringField; qfacturasclientes2poblaciondestino: TWideStringField; qfacturasclientes2codpostdestino: TWideStringField; qfacturasclientes2provinciadestino: TWideStringField; qfacturasclientes2paisdestino: TWideStringField; qfacturasclientes2neto: TFloatField; qfacturasclientes2total: TFloatField; qfacturasclientes2cobrado: TIntegerField; qfacturasclientes2documento: TWideStringField; qfacturasclientes2descuento_lin: TFloatField; qfacturasclientes2descuento_com: TFloatField; qfacturasclientes2descuento_pp: TFloatField; qfacturasclientes2descuento_total: TFloatField; qfacturasclientes2totaliva: TFloatField; qfacturasclientes2observaciones: TWideStringField; qfacturasclientes2bultos: TFloatField; qfacturasclientes2kilos: TFloatField; qfacturasclientes2idformapago: TIntegerField; qfacturasclientes2cc_pago: TWideStringField; qfacturasclientes2ccid: TIntegerField; qfacturasclientes2cccuentabancaria: TWideStringField; qfacturasclientes2comision: TFloatField; qfacturasclientes2coste_transporte: TFloatField; qfacturasclientes2peso_bruto: TFloatField; qfacturasclientes2prov_transporte: TWideStringField; qfacturasclientes2kilosventa: TFloatField; qfacturasclientes2numpalets: TFloatField; qfacturasclientes2serie_1: TWideStringField; qfacturasclientes2idfactura: TIntegerField; qfacturasclientes2ide: TIntegerField; qfacturasclientes2base: TFloatField; qfacturasclientes2tipo: TFloatField; qfacturasclientes2iva: TFloatField; Button6: TButton; comboformulario: TDBLookupComboBox; dsqformularios: TDataSource; qformularios: TZReadOnlyQuery; qformularioside: TIntegerField; qformulariosid: TIntegerField; qformulariosformulario: TWideStringField; qformulariosdescripcion: TWideStringField; qformulariosaplicar_a: TWideStringField; qformulariospordefecto: TIntegerField; infformaspago: TfrxDBDataset; facturasdetalletipore: TFloatField; facturasdetallere: TFloatField; qfacturasivare: TFloatField; qfacturasivatipore: TFloatField; DBEdit1: TDBEdit; Label12: TLabel; facturastotalre: TFloatField; qfacturasclientes2transporte_kilo: TFloatField; qfacturasclientescoste_transporte_1: TFloatField; qalbaranesdetallepesobruto: TFloatField; qalbaranesdetalleidfactura: TIntegerField; qalbaranesdetalle2pesobruto: TFloatField; qalbaranesdetalle2idfactura: TIntegerField; facturasretencion: TFloatField; facturastotalretencion: TFloatField; Label13: TLabel; Label14: TLabel; DBEdit2: TDBEdit; DBEdit3: TDBEdit; qalbaranesbultos: TFloatField; qalbaraneskilos: TFloatField; qalbaranesidformapago: TIntegerField; qalbaranescc_pago: TWideStringField; qalbaranescoste_transporte: TFloatField; qalbaranespeso_bruto: TFloatField; qalbaranesprov_transporte: TWideStringField; qalbaranesccid: TIntegerField; qalbaranescccuentabancaria: TWideStringField; qalbaranescomision: TFloatField; qalbaraneskilosventa: TFloatField; qalbaranesnumpalets: TFloatField; facturasdetallepalets: TFloatField; facturasfacturarporbultos: TIntegerField; DBCheckBox1: TDBCheckBox; qcalcularporbultos: TZQuery; WideStringField2: TWideStringField; IntegerField3: TIntegerField; IntegerField4: TIntegerField; FloatField4: TFloatField; FloatField5: TFloatField; FloatField6: TFloatField; qcalcularporcantidad: TZQuery; WideStringField3: TWideStringField; IntegerField5: TIntegerField; IntegerField6: TIntegerField; FloatField7: TFloatField; FloatField8: TFloatField; FloatField9: TFloatField; facturasdetallegrupo: TZQuery; facturasdetalleresumen: TZQuery; facturasdetallegrupoidempresa: TIntegerField; facturasdetallegrupoidfactura: TIntegerField; facturasdetallegrupocantidad: TFloatField; facturasdetallegrupoprecio: TFloatField; facturasdetallegrupodescuento: TFloatField; facturasdetallegrupobase: TFloatField; facturasdetallegrupodescripcion: TWideStringField; facturasdetallegrupocal: TWideStringField; facturasdetallegrupobultos: TFloatField; facturasdetallegrupotipoiva: TFloatField; facturasdetallegrupoiva: TFloatField; facturasdetallegrupototal: TFloatField; facturasdetallegrupoid: TIntegerField; facturasdetallegrupoidarticulo: TWideStringField; facturasdetallegrupototaldescuento: TFloatField; facturasdetallegrupolote: TWideStringField; facturasdetallegruposerie: TWideStringField; facturasdetallegrupoidalbaran: TIntegerField; facturasdetallegrupocoste_transporte: TFloatField; facturasdetallegrupocoste_otros: TFloatField; facturasdetallegrupocoste_comision: TFloatField; facturasdetallegrupopesobruto: TFloatField; facturasdetallegrupotipore: TFloatField; facturasdetallegrupore: TFloatField; facturasdetallegrupopalets: TFloatField; facturasdetalleresumenid: TIntegerField; facturasdetalleresumenidempresa: TIntegerField; facturasdetalleresumenidfactura: TIntegerField; facturasdetalleresumencantidad: TFloatField; facturasdetalleresumenprecio: TFloatField; facturasdetalleresumendescuento: TFloatField; facturasdetalleresumenbase: TFloatField; facturasdetalleresumendescripcion: TWideStringField; facturasdetalleresumencal: TWideStringField; facturasdetalleresumenbultos: TFloatField; facturasdetalleresumentipoiva: TFloatField; facturasdetalleresumeniva: TFloatField; facturasdetalleresumentotal: TFloatField; facturasdetalleresumenidarticulo: TWideStringField; facturasdetalleresumentotaldescuento: TFloatField; facturasdetalleresumenlote: TWideStringField; facturasdetalleresumenserie: TWideStringField; facturasdetalleresumenidalbaran: TIntegerField; facturasdetalleresumencoste_transporte: TFloatField; facturasdetalleresumencoste_otros: TFloatField; facturasdetalleresumencoste_comision: TFloatField; facturasdetalleresumenpesobruto: TFloatField; facturasdetalleresumentipore: TFloatField; facturasdetalleresumenre: TFloatField; facturasdetalleresumenpalets: TFloatField; dsqfacturasdetalleresumen: TDataSource; inffacturasresumen: TfrxDBDataset; qactualizarids: TZReadOnlyQuery; qborraridfacturaids: TZReadOnlyQuery; Button10: TButton; qfacturasagrupado: TZReadOnlyQuery; qfacturasagrupadoidempresa: TIntegerField; qfacturasagrupadoserie: TWideStringField; qfacturasagrupadoidfactura: TIntegerField; qfacturasagrupadoidcliente: TIntegerField; qfacturasagrupadocliente: TWideStringField; qfacturasagrupadodescripcion: TWideStringField; qfacturasagrupadolote: TWideStringField; qfacturasagrupadocajas: TFloatField; qfacturasagrupadoenvase: TWideStringField; qfacturasagrupadoreferencia: TWideStringField; qfacturasagrupadoformato: TWideStringField; qfacturasagrupadokilos: TFloatField; qfacturasagrupadopreciokilo: TFloatField; qfacturasagrupadopreciocaja: TFloatField; qfacturasagrupadototal: TFloatField; qfacturasagrupadovariedad: TWideStringField; qfacturasagrupadoorigen: TWideStringField; qfacturasagrupadoparcela: TWideStringField; dsqfacturasagrupado: TDataSource; gridagrupados: TDBGrid; btncargarcertificados: TButton; cbCertificados: TComboBox; procedure dsfacturasStateChange(Sender: TObject); procedure dsfacturasDataChange(Sender: TObject; Field: TField); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure btfimportarClick(Sender: TObject); procedure btfnuevoClick(Sender: TObject); procedure comboseriesCloseUp(Sender: TObject); procedure comboseriesEnter(Sender: TObject); procedure comboclientesCloseUp(Sender: TObject); procedure alba(Sender: TObject); procedure combodestinosCloseUp(Sender: TObject); procedure btfborrarClick(Sender: TObject); procedure btfmodificarClick(Sender: TObject); procedure btfguardarClick(Sender: TObject); procedure facturasdetalleBeforePost(DataSet: TDataSet); procedure facturasdetalleAfterPost(DataSet: TDataSet); procedure Button16Click(Sender: TObject); procedure DBGrid6TitleClick(Column: TColumn); procedure btfcancelarClick(Sender: TObject); procedure btfanteriorClick(Sender: TObject); procedure btfsiguienteClick(Sender: TObject); procedure btfimprimirClick(Sender: TObject); procedure DBGrid5KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DBGrid5ColExit(Sender: TObject); procedure qarticulosBeforeOpen(DataSet: TDataSet); procedure Button3Click(Sender: TObject); procedure tablistadoShow(Sender: TObject); procedure btfiltrarClick(Sender: TObject); procedure DBGrid6DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure Button7Click(Sender: TObject); procedure Button8Click(Sender: TObject); procedure Button9Click(Sender: TObject); procedure btacumuladosClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure dsqseries2DataChange(Sender: TObject; Field: TField); procedure Button4Click(Sender: TObject); procedure Button6Click(Sender: TObject); procedure qfacturasclientes2CalcFields(DataSet: TDataSet); procedure qfacturasclientesCalcFields(DataSet: TDataSet); procedure facturasBeforeDelete(DataSet: TDataSet); procedure facturasBeforePost(DataSet: TDataSet); procedure DBGrid6DblClick(Sender: TObject); procedure facturasdetalleBeforeDelete(DataSet: TDataSet); procedure Button10Click(Sender: TObject); procedure btncargarcertificadosClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar = nil); end; var facturas: Tfacturas; filtro, iddetalle: string; implementation {$R *.dfm} uses fselectalbaranes, fbuscararticulos, ftraza_materiales2, certificatemanager; procedure Tfacturas.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 Tfacturas.btfcancelarClick(Sender: TObject); begin facturas.Cancel; paneldatos.Enabled := False; pestañas.TabIndex := 0; end; procedure Tfacturas.btfguardarClick(Sender: TObject); var empresa, serie, id: string; begin empresa := facturasidempresa.AsString; serie := facturasserie.AsString; id := facturasid.AsString; qaux.sql.clear; facturas.Post; if facturasfacturarporbultos.asinteger=1 then begin qcalcularporbultos.prepare; qcalcularporbultos.ParamByName('FACTURA').AsInteger:=facturasid.AsInteger; qcalcularporbultos.ParamByName('EMPRESA').AsInteger:=facturasidempresa.AsInteger; qcalcularporbultos.ParamByName('SERIE').AsString:=facturasserie.AsString; qcalcularporbultos.ExecSQL; end; if facturasfacturarporbultos.asinteger=0 then begin qcalcularporcantidad.prepare; qcalcularporcantidad.ParamByName('FACTURA').AsInteger:=facturasid.AsInteger; qcalcularporcantidad.ParamByName('EMPRESA').AsInteger:=facturasidempresa.AsInteger; qcalcularporcantidad.ParamByName('SERIE').AsString:=facturasserie.AsString; qcalcularporcantidad.ExecSQL; end; comboserie2.KeyValue := facturasserie.AsString; qaux.sql.clear; qaux.sql.Add('select max(id) from facturas where idempresa=' + empresa + ' and serie=' + '''' + serie + ''''); qaux.Open; qseries.edit; qseriesnum_factura.Value := qaux.Fields[0].AsInteger + 1; qseries.Post; facturasdetalle.Open; qfacturasiva.Open; facturas.Refresh; facturasdetalle.Refresh; facturas.Locate('serie,id', vararrayof([serie, id]), [locaseinsensitive]); qfacturasiva.Open; qfacturasiva.Refresh; Panel3.Enabled := False; comboserie2.KeyValue := qseriesid.AsString; facturas.Close; facturas.sql.clear; facturas.sql.Add('select * from facturas where serie=' + '''' + serie + '''' + ' order by serie desc,id desc'); facturas.Open; facturas.Locate('serie,id', vararrayof([serie, id]), [locaseinsensitive]); qfacturasiva.Refresh; paneldatos.Enabled := False; end; procedure Tfacturas.btfimportarClick(Sender: TObject); var empresa,idfactura,idalbaran:string; serie,pesobruto,pesoneto,pesonetoteorico,numpalets:string; begin seleccionaralbaranes := Tseleccionaralbaranes.Create(nil); try seleccionaralbaranes.showmodal(); finally seleccionaralbaranes.Free; end; empresa := facturasidempresa.AsString; idfactura := facturasid.AsString; serie := facturasserie.AsString; facturas.Refresh; facturas.Locate('serie;id', vararrayof([serie, idfactura]), [locaseinsensitive]); qfacturasiva.Refresh; qborraridfacturaids.Close; qborraridfacturaids.Prepare; qborraridfacturaids.ParamByName('EMPRESA').Asstring:=empresa; qborraridfacturaids.ParamByName('IDFACTURA').Asstring:=serie+'/'+idfactura; qborraridfacturaids.ExecSQL; qactualizarids.Close; qactualizarids.Prepare; qactualizarids.ParamByName('IDFACTURA').AsString:=serie+'/'+idfactura; qactualizarids.ParamByName('SERIE').Asstring:=serie; qactualizarids.ParamByName('EMPRESA').Asstring:=empresa; qactualizarids.ParamByName('FACTURA').Asstring:=idfactura; qactualizarids.ExecSQL; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('select sum(peso_bruto-tara0),sum(peso_neto),sum(peso_neto_teorico),sum(num_palets) from ea_pesadas where idfactura='+''''+serie+'/'+idfactura+''''+' and idempresa='+facturasidempresa.asstring); qaux.open; pesobruto:=qaux.fields[0].asstring; pesobruto:=stringreplace(pesobruto,',','.',[rfreplaceall]); pesoneto:=qaux.fields[1].asstring; pesoneto:=stringreplace(pesoneto,',','.',[rfreplaceall]); pesonetoteorico:=qaux.fields[2].asstring; pesonetoteorico:=stringreplace(pesonetoteorico,',','.',[rfreplaceall]); numpalets:=qaux.fields[3].asstring; numpalets:=stringreplace(numpalets,',','.',[rfreplaceall]); qaux.SQL.Clear; qaux.SQL.Add('update facturas set peso_bruto='+pesobruto+',kilos='+pesoneto+',kilosventa='+pesonetoteorico+',numpalets='+numpalets+' where serie='+''''+serie+''''+' and id='+idfactura+' and idempresa='+facturasidempresa.AsString); qaux.execsql; facturas.refresh; facturas.Locate('serie,id',vararrayof([serie,idfactura]),[locaseinsensitive]) end; procedure Tfacturas.btfimprimirClick(Sender: TObject); var filtro, documento, formapago, pesobruto: string; desg_ivas, tipo, tipore, base, iva, re: string; x: Integer; fecha: tdate; begin pestañas.TabIndex := 1; facturasdetalleresumen.close; facturasdetalleresumen.prepare; facturasdetalleresumen.ParamByName('SERIE').AsString:=facturasserie.AsString; facturasdetalleresumen.ParamByName('IDFACTURA').AsInteger:=facturasid.Asinteger; facturasdetalleresumen.ParamByName('EMPRESA').AsInteger:=facturasidempresa.AsInteger; facturasdetalleresumen.Open; if listaimpresion.ItemIndex = 0 then begin // facturasdetalle.sql.clear; // facturasdetalle.sql.Add // ('select idempresa,idfactura,sum(cantidad) as cantidad,precio,descuento,sum(base) as base,descripcion,cal,sum(bultos) as bultos,tipoiva,sum(iva) as iva,sum(total) as total,id,' // + '''''' + ' as idarticulo,sum(totaldescuento) as totaldescuento,' + // '''''' + ' as lote,serie,idalbaran '); // facturasdetalle.sql.Add // (',coste_transporte,coste_otros,coste_comision,sum(pesobruto) as pesobruto,tipore,re,sum(palets) as palets from facturas_detalles group by idempresa,idfactura,descripcion,cal,precio,idalbaran order by id'); facturasdetallegrupo.Close; facturasdetallegrupo.prepare; facturasdetallegrupo.ParamByName('SERIE').AsString:=facturasserie.AsString; facturasdetallegrupo.ParamByName('IDFACTURA').AsInteger:=facturasid.Asinteger; facturasdetallegrupo.ParamByName('EMPRESA').AsInteger:=facturasidempresa.AsInteger; facturasdetallegrupo.Open; dsfacturasdetalle.DataSet:=facturasdetallegrupo; end; if listaimpresion.ItemIndex = 1 then begin facturasdetalle.Close; facturasdetalle.prepare; facturasdetalle.ParamByName('SERIE').AsString:=facturasserie.AsString; facturasdetalle.ParamByName('IDFACTURA').AsInteger:=facturasid.Asinteger; facturasdetalle.ParamByName('EMPRESA').AsInteger:=facturasidempresa.AsInteger; facturasdetalle.Open; dsfacturasdetalle.DataSet:=facturasdetalle; end; filtro := 'id='; filtro := filtro + facturasid.AsString; filtro := filtro + ' and serie=' + '''' + facturasserie.AsString + ''''; if comboformulario.KeyValue = null then documento := qseriesimp_factura.AsString else documento := qformulariosformulario.AsString; facturas.Filter := filtro; facturas.filtered := True; fecha := facturasfecha.AsDateTime; fecha := fecha + qformaspagodias.AsInteger; formapago := 'FORMA DE PAGO: ' + qformaspagodescripcion.AsString + ' FECHA DE VENCIMIENTO EL ' + DATETOSTR(fecha); pesobruto := 'PESO BRUTO: ' + facturaspeso_bruto.AsString; qfacturasiva.First; desg_ivas := ''; while not qfacturasiva.Eof do begin if qfacturasivabase.AsFloat <> 0 then begin tipo := format('%2d', [qfacturasivatipo.AsInteger]); tipore := format('%4.2f', [qfacturasivatipore.AsFloat]); base := format('%10.2f', [qfacturasivabase.AsFloat]); iva := format('%8.2f', [qfacturasivaiva.AsFloat]); re := format('%8.2f', [qfacturasivare.AsFloat]); desg_ivas := desg_ivas + base + ' ' + tipo + ' ' + iva + ' ' + tipore + ' ' + re; end; qfacturasiva.Next; end; inffactura.DataSource := dsfacturas; infdetallefactura.DataSource := dsfacturasdetalle; inffacturasresumen.DataSource := dsqfacturasdetalleresumen; informe.Report.clear; informe.LoadFromFile('c:\agrigest\informes\' + documento + '.fr3'); informe.Variables.Variables['FORMAPAGO'] := QUOTEDSTR(formapago); informe.Variables.Variables['DESGIVAS'] := QUOTEDSTR(desg_ivas); informe.Variables.Variables['PESOBRUTO'] := QUOTEDSTR(pesobruto); informe.ShowReport(); informe.clear; // informe.Variables.Variables['TITULO']:=QUOTEDSTR(panel100.Caption); dsfacturasdetalle.DataSet:=facturasdetalle; facturas.filtered := false; end; procedure Tfacturas.btfmodificarClick(Sender: TObject); begin pestañas.TabIndex := 0; paneldatos.Enabled := True; facturas.edit; qclientes.Close; qclientes.sql.clear; qclientes.sql.Add('select * from clientes order by nombre'); qclientes.Open; qdestinos.Close; qdestinos.sql.clear; qdestinos.sql.Add('select * from clientes_destinos order by descripcion'); qdestinos.Open; end; procedure Tfacturas.btacumuladosClick(Sender: TObject); var dia, mes, anyo: Word; filtro, filtro2, tdesde, thasta: string; begin decodedate(fdesde.Date, anyo, mes, dia); tdesde := '''' + floattostr(anyo) + '/' + floattostr(mes) + '/' + floattostr(dia) + ''''; decodedate(fhasta.Date, anyo, mes, dia); thasta := '''' + floattostr(anyo) + '/' + floattostr(mes) + '/' + floattostr(dia) + ''''; filtro := ' where fecha>=' + tdesde + ' and fecha<=' + thasta; if (combolistcliente.Text <> '') and (combolistcliente.Text <> ' TODOS') then begin filtro := filtro + ' and nif=' + '''' + listaclientesnif.AsString + ''''; end; if (combolistdestinos.Text <> '') and (combolistdestinos.Text <> ' TODOS') then begin filtro := filtro + ' and nomdestino=' + '''' + listadestinosnomdestino.AsString + ''''; end; filtro := filtro + ' group by idcliente order by nomcliente'; facturasacumuladas.Close; facturasacumuladas.sql.clear; facturasacumuladas.sql.Add ('select idempresa,idcliente,nif,nomcliente,sum(total) from facturas ' + filtro); facturasacumuladas.Open; DBGridacumulados.BringToFront; DBGrid6.Visible := False; DBGridacumulados.Visible := True; end; procedure Tfacturas.btfanteriorClick(Sender: TObject); begin facturas.Next; end; procedure Tfacturas.btfborrarClick(Sender: TObject); begin pestañas.TabIndex := 1; facturasdetalle.Open; if facturas.RecordCount > 0 then begin facturas.Delete; facturasdetalle.Refresh; qalbaranes.Refresh; qalbaranes2.Refresh; qalbaranesdetalle.Refresh; qalbaranesdetalle2.Refresh; qfacturasiva.Refresh; end; end; procedure Tfacturas.btfnuevoClick(Sender: TObject); begin pestañas.TabIndex := 0; paneldatos.Enabled := True; comboseries.SetFocus; comboseries.KeyValue := qseriesid.AsString; // fechaalbaran.Date:=date; facturas.Append; qclientes.Close; qclientes.sql.clear; qclientes.sql.Add('select * from clientes order by nombre'); qclientes.Open; qdestinos.Close; qdestinos.sql.clear; qdestinos.sql.Add('select * from clientes_destinos order by descripcion'); qdestinos.Open; facturasdetalle.Close; qfacturasiva.Close; facturasfecha.Value := Date; end; procedure Tfacturas.btfsiguienteClick(Sender: TObject); begin facturas.Prior; end; procedure Tfacturas.Button10Click(Sender: TObject); var vserie,vidcliente,viddestino,archivo:string; vdesde,vhasta:tdate; begin vserie:='%'; vidcliente:='%'; viddestino:='%'; vdesde:=fdesde.Date; vhasta:=fhasta.Date; vserie:=comboserie2.KeyValue; if listaclientesnif.asstring<>' ' then vidcliente:=listaclientesnomcliente.asstring; if listadestinosnomdestino.asstring<>'' then viddestino:=listadestinosnomdestino.asstring; qfacturasagrupado.Prepare; qfacturasagrupado.ParamByName('SERIE').AsString:=vserie; qfacturasagrupado.ParamByName('IDCLIENTE').AsString:=vidcliente; qfacturasagrupado.ParamByName('IDDESTINO').AsString:=viddestino; qfacturasagrupado.ParamByName('DESDE').AsDate:=vdesde; qfacturasagrupado.ParamByName('HASTA').AsDate:=vhasta; qfacturasagrupado.Open; SaveDialog1.FileName := 'FACTURAS AGRUPADAS CLIENTES.xlsx'; SaveDialog1.Execute(); archivo := SaveDialog1.FileName; try ExportaraExcel(archivo, 'facturas', gridagrupados); finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure Tfacturas.btnCargarCertificadosClick(Sender: TObject); // O como se llame tu botón var CertList: TList; // Usamos TList clásico, no TObjectList<> i: Integer; CertInfo: TCertificateInfo; begin // Primero, limpiamos el ComboBox de cualquier certificado anterior for i := 0 to cbCertificados.Items.Count - 1 do begin // Liberamos el contexto del certificado que guardamos en el ComboBox CertFreeCertificateContext(PCCERT_CONTEXT(cbCertificados.Items.Objects[i])); end; cbCertificados.Clear; // ¡Llamamos a la función del CertificateManager! // Esta nos devuelve un TList que SÍ es compatible con XE3 CertList := TCertificateLoader.GetPersonalCertificates; try if CertList.Count = 0 then begin ShowMessage('No se encontraron certificados con clave privada.'); end else begin // Llenamos el ComboBox usando un bucle FOR clásico for i := 0 to CertList.Count - 1 do begin CertInfo := TCertificateInfo(CertList[i]); // Guardamos el nombre y el puntero al contexto del certificado cbCertificados.Items.AddObject(CertInfo.FriendlyName, CertInfo.Context); end; cbCertificados.ItemIndex := 0; end; finally // ¡MUY IMPORTANTE! // Liberamos la lista y TODOS los objetos TCertificateInfo que contiene. // Los "Context" ya están a salvo en el ComboBox. while CertList.Count > 0 do begin TCertificateInfo(CertList[0]).Free; CertList.Delete(0); end; CertList.Free; end; end; procedure Tfacturas.Button16Click(Sender: TObject); var serie, id: string; begin if facturasdetalle.RecordCount > 0 then begin serie := facturasserie.AsString; id := facturasid.AsString; facturasdetalle.Delete; // 1 facturas.Refresh; // facturas.Locate('serie;id',vararrayof([serie,id]),[locaseinsensitive,lopartialkey]); qfacturasiva.Refresh; end; end; procedure Tfacturas.Button1Click(Sender: TObject); var precio, serie, id: string; I: Integer; begin serie := facturasserie.AsString; id := facturasid.AsString; if facturasdetalle.RecordCount > 0 then begin precio := stringreplace((Edit1.Text), '.', ',', [rfreplaceall]); if DBGrid5.Selectedrows.Count > 0 then begin for I := 0 to DBGrid5.Selectedrows.Count - 1 do begin facturasdetalle.GotoBookmark((DBGrid5.Selectedrows[I])); facturasdetalle.edit; facturasdetalleprecio.Value := strtofloat(precio); facturasdetalle.Post; end; end else begin facturasdetalle.First; while not facturasdetalle.Eof do begin if facturasdetallecantidad.AsFloat > 0 then begin facturasdetalle.edit; facturasdetalleprecio.Value := strtofloat(precio); facturasdetalle.Post; end; facturasdetalle.Next; end; end; end; facturasdetalle.Refresh; facturas.Refresh; facturas.Locate('serie,id', vararrayof([serie, id]), [locaseinsensitive]); end; procedure Tfacturas.Button2Click(Sender: TObject); var id, codcomision, empresa, serie: string; coste_trans, cantidad, comision: real; begin codcomision := dm.tempresacodcomision.AsString; empresa := facturasidempresa.AsString; serie := facturasserie.AsString; id := facturasid.AsString; facturasdetalle.Append; DBGrid5.Fields[0].Value := codcomision; filtro := facturasdetalleidarticulo.AsString; qarticulos.Close; qarticulos.filtered := True; qarticulos.Open; if qarticulos.RecordCount > 0 then begin qtipos_iva.Open; facturasdetalledescripcion.Value := qarticulosdescripcion.AsString; if qclientesexento_iva.AsInteger = 0 then facturasdetalletipoiva.Value := qtipos_ivatipo.AsFloat else facturasdetalletipoiva.Value := 0; end; DBGrid5.Fields[7].Value := -1; DBGrid5.Fields[8].Value := facturasneto.AsFloat * (facturascomision.AsFloat / 100); facturasdetalle.Post; qaux.Close; qaux.sql.clear; qaux.sql.Add ('select sum(cantidad),sum(total) from facturas_detalles where lote is not null and idempresa=' + empresa + ' and serie=' + '''' + serie + '''' + ' and idalbaran=' + facturasid.AsString); qaux.Open; cantidad := qaux.Fields[0].AsFloat; if (cantidad > 0) and (facturascoste_transporte.AsFloat > 0) then begin coste_trans := facturascoste_transporte.AsFloat / cantidad; qaux.Close; qaux.sql.clear; qaux.sql.Add('update facturas_detalles set coste_transporte=cantidad*' + stringreplace(floattostr(coste_trans), ',', '.', [rfreplaceall]) + ' where lote is not null and idempresa=' + empresa + ' and serie=' + '''' + serie + '''' + ' and idalbaran=' + facturasid.AsString + ' and idarticulo<>(select codcomision from empresa where id=' + facturasidempresa.AsString + ') and idarticulo<>(select codtransporte from empresa where id=' + facturasidempresa.AsString + ')'); qaux.execsql; end; comision := facturascomision.AsFloat / 100; qaux.Close; qaux.sql.clear; qaux.sql.Add('update facturas_detalles set coste_comision=total*' + stringreplace(floattostr(comision), ',', '.', [rfreplaceall]) + ' where idempresa=' + empresa + ' and serie=' + '''' + serie + '''' + ' and idfactura=' + facturasid.AsString + ' and idarticulo<>(select codcomision from empresa where id=' + facturasidempresa.AsString + ') and idarticulo<>(select codtransporte from empresa where id=' + facturasidempresa.AsString + ')'); qaux.execsql; facturas.Refresh; facturas.Locate('serie,id', vararrayof([serie, id]), [locaseinsensitive]); facturasdetalle.Refresh; facturasdetalle.Last; qfacturasiva.Refresh; end; procedure Tfacturas.Button3Click(Sender: TObject); var archivo: string; dia, mes, anyo: Word; filtro, tdesde, thasta: string; begin decodedate(fdesde.Date, anyo, mes, dia); tdesde := '''' + floattostr(anyo) + '/' + floattostr(mes) + '/' + floattostr(dia) + ''''; decodedate(fhasta.Date, anyo, mes, dia); thasta := '''' + floattostr(anyo) + '/' + floattostr(mes) + '/' + floattostr(dia) + ''''; filtro := ' where f.fecha>=' + tdesde + ' and f.fecha<=' + thasta; if (combolistcliente.Text <> '') and (combolistcliente.Text <> ' TODOS') then begin filtro := filtro + ' and nif=' + '''' + listaclientesnif.AsString + ''''; end; if (combolistdestinos.Text <> '') and (combolistdestinos.Text <> ' TODOS') then begin filtro := filtro + ' and nomdestino=' + '''' + listadestinosnomdestino.AsString + ''''; end; filtro := filtro + ' and f.idempresa=fi.ide and f.serie=fi.serie and f.id=fi.idfactura and fi.base>0'; qfacturasclientes2.Close; qfacturasclientes2.sql.clear; qfacturasclientes2.sql.Add('select * from facturas f,facturas_iva fi ' + filtro); qfacturasclientes2.Open; SaveDialog1.FileName := 'FACTURAS CLIENTES.xlsx'; SaveDialog1.Execute(); archivo := SaveDialog1.FileName; try if DBGridacumulados.Visible then ExportaraExcel(archivo, 'Acumulados', DBGridacumulados) else begin ExportaraExcel(archivo, 'facturas', gridfacturasaexcel2); end; finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure Tfacturas.Button4Click(Sender: TObject); var archivo: string; dia, mes, anyo: Word; filtro, tdesde, thasta: string; begin decodedate(fdesde.Date, anyo, mes, dia); tdesde := '''' + floattostr(anyo) + '/' + floattostr(mes) + '/' + floattostr(dia) + ''''; decodedate(fhasta.Date, anyo, mes, dia); thasta := '''' + floattostr(anyo) + '/' + floattostr(mes) + '/' + floattostr(dia) + ''''; filtro := ' where f.fecha>=' + tdesde + ' and f.fecha<=' + thasta; if (combolistcliente.Text <> '') and (combolistcliente.Text <> ' TODOS') then begin filtro := filtro + ' and nif=' + '''' + listaclientesnif.AsString + ''''; end; if (combolistdestinos.Text <> '') and (combolistdestinos.Text <> ' TODOS') then begin filtro := filtro + ' and nomdestino=' + '''' + listadestinosnomdestino.AsString + ''''; end; filtro := filtro + ' '; qfacturasclientes.sql.clear; qfacturasclientes.sql.Add ('(select f.serie as s,f.id as numfact,f.*,fd.*,l.parcela from facturas f,facturas_detalles fd,lotes l ' + filtro + ' and l.idempresa=fd.idempresa and l.codigo=fd.lote and f.idempresa=fd.idempresa and f.serie=fd.serie and f.id=fd.idfactura ) '); qfacturasclientes.sql.Add(' union ALL '); qfacturasclientes.sql.Add('(select f.serie as s,f.id as numfact,f.*,fd.*,' + '''' + ' ' + '''' + ' as parcela from facturas f,facturas_detalles fd ' + filtro + ' and fd.lote is null and f.idempresa=fd.idempresa and f.serie=fd.serie and f.id=fd.idfactura) order by s,numfact desc'); qfacturasclientes.Open; SaveDialog1.FileName := 'FACTURAS CLIENTES DETALLADO.xlsx'; SaveDialog1.Execute(); archivo := SaveDialog1.FileName; try // if dbgridacumulados.visible then Exportaraexcel(archivo,'Acumulados',dbgridacumulados) // else ExportaraExcel(archivo, 'facturas', gridfacturasaexcel); finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure Tfacturas.Button5Click(Sender: TObject); var id, codtransporte, empresa, serie: string; coste_trans, cantidad, comision: real; begin id := facturasid.AsString; empresa := facturasidempresa.AsString; serie := facturasserie.AsString; codtransporte := dm.tempresacodtransporte.AsString; facturasdetalle.Append; DBGrid5.Fields[0].Value := codtransporte; filtro := facturasdetalleidarticulo.AsString; qarticulos.Close; qarticulos.Open; if qarticulos.RecordCount > 0 then begin qtipos_iva.Open; facturasdetalledescripcion.Value := qarticulosdescripcion.AsString; if qclientesexento_iva.AsInteger = 0 then facturasdetalletipoiva.Value := qtipos_ivatipo.AsFloat else facturasdetalletipoiva.Value := 0; end; DBGrid5.Fields[7].Value := -1; DBGrid5.Fields[8].Value := facturascoste_transporte.AsFloat; facturasdetalle.Post; qaux.Close; qaux.sql.clear; qaux.sql.Add ('select sum(cantidad),sum(total) from facturas_detalles where lote is not null and idempresa=' + empresa + ' and serie=' + '''' + serie + '''' + ' and idalbaran=' + facturasid.AsString); qaux.Open; cantidad := qaux.Fields[0].AsFloat; if (cantidad > 0) and (facturascoste_transporte.AsFloat > 0) then begin coste_trans := facturascoste_transporte.AsFloat / cantidad; qaux.Close; qaux.sql.clear; qaux.sql.Add('update facturas_detalles set coste_transporte=cantidad*' + stringreplace(floattostr(coste_trans), ',', '.', [rfreplaceall]) + ' where lote is not null and idempresa=' + empresa + ' and serie=' + '''' + serie + '''' + ' and idalbaran=' + facturasid.AsString + ' and idarticulo<>(select codcomision from empresa where id=' + facturasidempresa.AsString + ') and idarticulo<>(select codtransporte from empresa where id=' + facturasidempresa.AsString + ')'); qaux.execsql; end; comision := facturascomision.AsFloat / 100; qaux.Close; qaux.sql.clear; qaux.sql.Add('update facturas_detalles set coste_comision=total*' + stringreplace(floattostr(comision), ',', '.', [rfreplaceall]) + ' where idempresa=' + empresa + ' and serie=' + '''' + serie + '''' + ' and idalbaran=' + facturasid.AsString + ' and idarticulo<>(select codcomision from empresa where id=' + facturasidempresa.AsString + ') and idarticulo<>(select codtransporte from empresa where id=' + facturasidempresa.AsString + ')'); qaux.execsql; facturas.Refresh; facturas.Locate('serie,id', vararrayof([serie, id]), [locaseinsensitive]); facturasdetalle.Refresh; facturasdetalle.Last; qfacturasiva.Refresh; end; procedure Tfacturas.Button6Click(Sender: TObject); begin traza_materiales2 := Ttraza_materiales2.Create(nil); try traza_materiales2.qpesadas.Close; traza_materiales2.qpesadas.sql.clear; traza_materiales2.qpesadas.sql.Add ('select mat.idea,mat.idea2,mat.idaf,af.descripcion,mat.cantidad,mat.lote,e.documento as doc_compra,p.nombre as proveedor,:documento as documento from ea_materiales mat ,articulosf af,entradas_detalle ed,entradas e,proveedores p where'); traza_materiales2.qpesadas.sql.Add ('mat.idaf=af.id and mat.ide=af.idempresa and mat.idaf=ed.id_propio and mat.lote=ed.lote and ed.identrada=e.id and mat.ide=e.idempresa and e.idproveedor=p.id and'); traza_materiales2.qpesadas.sql.Add (' (ide,idea,idea2) in (select idempresa,id,idea from ea_pesadas where idfactura=:documento) order by idaf,idea,idea2'); traza_materiales2.qpesadas.ParamByName('documento').AsString := facturasserie.AsString + '/' + facturasid.AsString; traza_materiales2.qpesadas.prepare; traza_materiales2.qpesadas.Open; traza_materiales2.DBGrid2.Columns[0].Title.Caption := 'Factura';; traza_materiales2.showmodal(); finally traza_materiales2.Free; end; end; procedure Tfacturas.Button7Click(Sender: TObject); begin combolistcliente.KeyValue := null; btfiltrar.click; end; procedure Tfacturas.Button8Click(Sender: TObject); begin combolistdestinos.KeyValue := null; btfiltrar.click; end; procedure Tfacturas.Button9Click(Sender: TObject); var clicuenta, clititulo, clinif, clidomicilio, clipoblacion, cliprovincia, clicodpost: string; dasiento, dfecha, dcuenta, dcontrapartida, dconcepto, dfactura, dfecha_recep, diva, drec_equiv, ddocumento, dserie, daccion, doperacioniva, dorigen, dtipoapunte, dimpdebe, dimphaber, dbaseimpo: string; archivo, tdia, tmes, tanyo, sconta: string; fichero: textfile; x: Integer; dia, mes, anyo: Word; begin /// ///////////////// exportanto fichero subcuentas //////////////////// qclientes_conta.Open; qclientes_conta.First; qaux.Close; qaux.sql.clear; qaux.sql.Add('delete from conta_subcta'); qaux.execsql; qconta_subcta.Close; qconta_subcta.Open; while not qclientes_conta.Eof do begin qconta_subcta.Append; clicuenta := qclientes_contaccontable.AsString; clicuenta := clicuenta + StringOfChar(' ', 12 - length(clicuenta)); qconta_subctacuenta.Value := clicuenta; clititulo := qclientes_contanombre.AsString; clititulo := clititulo + StringOfChar(' ', 40 - length(clititulo)); qconta_subctatitulo.Value := clititulo; clinif := qclientes_contanif.AsString; clinif := clinif + StringOfChar(' ', 15 - length(clinif)); qconta_subctanif.Value := clinif; clidomicilio := qclientes_contadireccion.AsString; Delete(clidomicilio, 35, clidomicilio.length - 35); clidomicilio := clidomicilio + StringOfChar(' ', 35 - length(clidomicilio)); qconta_subctadomicilio.Value := clidomicilio; clipoblacion := qclientes_contapoblacion.AsString; clipoblacion := clipoblacion + StringOfChar(' ', 25 - length(clipoblacion)); qconta_subctapoblacion.Value := clipoblacion; cliprovincia := qclientes_contaprovincia.AsString; cliprovincia := cliprovincia + StringOfChar(' ', 20 - length(cliprovincia)); qconta_subctaprovincia.Value := cliprovincia; clicodpost := qclientes_contacodpost.AsString; clicodpost := clicodpost + StringOfChar(' ', 7 - length(clicodpost)); qconta_subctacodpost.Value := clicodpost; qconta_subcta.Post; qclientes_conta.Next; end; qconta_subcta.Append; clicuenta := '70000000'; clicuenta := clicuenta + StringOfChar(' ', 12 - length(clicuenta)); qconta_subctacuenta.Value := clicuenta; clititulo := ''; clititulo := clititulo + StringOfChar(' ', 40 - length(clititulo)); qconta_subctatitulo.Value := clititulo; clinif := ''; clinif := clinif + StringOfChar(' ', 15 - length(clinif)); qconta_subctanif.Value := clinif; clidomicilio := ''; Delete(clidomicilio, 35, clidomicilio.length - 35); clidomicilio := clidomicilio + StringOfChar(' ', 35 - length(clidomicilio)); qconta_subctadomicilio.Value := clidomicilio; clipoblacion := ''; // qclientes_contapoblacion.AsString; clipoblacion := clipoblacion + StringOfChar(' ', 25 - length(clipoblacion)); qconta_subctapoblacion.Value := clipoblacion; cliprovincia := ''; // qclientes_contaprovincia.AsString; cliprovincia := cliprovincia + StringOfChar(' ', 20 - length(cliprovincia)); qconta_subctaprovincia.Value := cliprovincia; clicodpost := ''; // qclientes_contacodpost.AsString; clicodpost := clicodpost + StringOfChar(' ', 7 - length(clicodpost)); qconta_subctacodpost.Value := clicodpost; qconta_subcta.Post; qconta_subcta.Append; clicuenta := '47701000'; clicuenta := clicuenta + StringOfChar(' ', 12 - length(clicuenta)); qconta_subctacuenta.Value := clicuenta; clititulo := ''; clititulo := clititulo + StringOfChar(' ', 40 - length(clititulo)); qconta_subctatitulo.Value := clititulo; clinif := ''; clinif := clinif + StringOfChar(' ', 15 - length(clinif)); qconta_subctanif.Value := clinif; clidomicilio := ''; Delete(clidomicilio, 35, clidomicilio.length - 35); clidomicilio := clidomicilio + StringOfChar(' ', 35 - length(clidomicilio)); qconta_subctadomicilio.Value := clidomicilio; clipoblacion := ''; // qclientes_contapoblacion.AsString; clipoblacion := clipoblacion + StringOfChar(' ', 25 - length(clipoblacion)); qconta_subctapoblacion.Value := clipoblacion; cliprovincia := ''; // qclientes_contaprovincia.AsString; cliprovincia := cliprovincia + StringOfChar(' ', 20 - length(cliprovincia)); qconta_subctaprovincia.Value := cliprovincia; clicodpost := ''; // qclientes_contacodpost.AsString; clicodpost := clicodpost + StringOfChar(' ', 7 - length(clicodpost)); qconta_subctacodpost.Value := clicodpost; qconta_subcta.Post; qconta_subcta.Append; clicuenta := '47700004'; clicuenta := clicuenta + StringOfChar(' ', 12 - length(clicuenta)); qconta_subctacuenta.Value := clicuenta; clititulo := ''; clititulo := clititulo + StringOfChar(' ', 40 - length(clititulo)); qconta_subctatitulo.Value := clititulo; clinif := ''; clinif := clinif + StringOfChar(' ', 15 - length(clinif)); qconta_subctanif.Value := clinif; clidomicilio := ''; Delete(clidomicilio, 35, clidomicilio.length - 35); clidomicilio := clidomicilio + StringOfChar(' ', 35 - length(clidomicilio)); qconta_subctadomicilio.Value := clidomicilio; clipoblacion := ''; // qclientes_contapoblacion.AsString; clipoblacion := clipoblacion + StringOfChar(' ', 25 - length(clipoblacion)); qconta_subctapoblacion.Value := clipoblacion; cliprovincia := ''; // qclientes_contaprovincia.AsString; cliprovincia := cliprovincia + StringOfChar(' ', 20 - length(cliprovincia)); qconta_subctaprovincia.Value := cliprovincia; clicodpost := ''; // qclientes_contacodpost.AsString; clicodpost := clicodpost + StringOfChar(' ', 7 - length(clicodpost)); qconta_subctacodpost.Value := clicodpost; qconta_subcta.Post; qconta_subcta.Append; clicuenta := '47700010'; clicuenta := clicuenta + StringOfChar(' ', 12 - length(clicuenta)); qconta_subctacuenta.Value := clicuenta; clititulo := ''; clititulo := clititulo + StringOfChar(' ', 40 - length(clititulo)); qconta_subctatitulo.Value := clititulo; clinif := ''; clinif := clinif + StringOfChar(' ', 15 - length(clinif)); qconta_subctanif.Value := clinif; clidomicilio := ''; Delete(clidomicilio, 35, clidomicilio.length - 35); clidomicilio := clidomicilio + StringOfChar(' ', 35 - length(clidomicilio)); qconta_subctadomicilio.Value := clidomicilio; clipoblacion := ''; // qclientes_contapoblacion.AsString; clipoblacion := clipoblacion + StringOfChar(' ', 25 - length(clipoblacion)); qconta_subctapoblacion.Value := clipoblacion; cliprovincia := ''; // qclientes_contaprovincia.AsString; cliprovincia := cliprovincia + StringOfChar(' ', 20 - length(cliprovincia)); qconta_subctaprovincia.Value := cliprovincia; clicodpost := ''; // qclientes_contacodpost.AsString; clicodpost := clicodpost + StringOfChar(' ', 7 - length(clicodpost)); qconta_subctacodpost.Value := clicodpost; qconta_subcta.Post; qconta_subcta.Append; clicuenta := '47700002'; clicuenta := clicuenta + StringOfChar(' ', 12 - length(clicuenta)); qconta_subctacuenta.Value := clicuenta; clititulo := ''; clititulo := clititulo + StringOfChar(' ', 40 - length(clititulo)); qconta_subctatitulo.Value := clititulo; clinif := ''; clinif := clinif + StringOfChar(' ', 15 - length(clinif)); qconta_subctanif.Value := clinif; clidomicilio := ''; Delete(clidomicilio, 35, clidomicilio.length - 35); clidomicilio := clidomicilio + StringOfChar(' ', 35 - length(clidomicilio)); qconta_subctadomicilio.Value := clidomicilio; clipoblacion := ''; // qclientes_contapoblacion.AsString; clipoblacion := clipoblacion + StringOfChar(' ', 25 - length(clipoblacion)); qconta_subctapoblacion.Value := clipoblacion; cliprovincia := ''; // qclientes_contaprovincia.AsString; cliprovincia := cliprovincia + StringOfChar(' ', 20 - length(cliprovincia)); qconta_subctaprovincia.Value := cliprovincia; clicodpost := ''; // qclientes_contacodpost.AsString; clicodpost := clicodpost + StringOfChar(' ', 7 - length(clicodpost)); qconta_subctacodpost.Value := clicodpost; qconta_subcta.Post; qconta_subcta.Append; clicuenta := '47700021'; clicuenta := clicuenta + StringOfChar(' ', 12 - length(clicuenta)); qconta_subctacuenta.Value := clicuenta; clititulo := ''; clititulo := clititulo + StringOfChar(' ', 40 - length(clititulo)); qconta_subctatitulo.Value := clititulo; clinif := ''; clinif := clinif + StringOfChar(' ', 15 - length(clinif)); qconta_subctanif.Value := clinif; clidomicilio := ''; Delete(clidomicilio, 35, clidomicilio.length - 35); clidomicilio := clidomicilio + StringOfChar(' ', 35 - length(clidomicilio)); qconta_subctadomicilio.Value := clidomicilio; clipoblacion := ''; // qclientes_contapoblacion.AsString; clipoblacion := clipoblacion + StringOfChar(' ', 25 - length(clipoblacion)); qconta_subctapoblacion.Value := clipoblacion; cliprovincia := ''; // qclientes_contaprovincia.AsString; cliprovincia := cliprovincia + StringOfChar(' ', 20 - length(cliprovincia)); qconta_subctaprovincia.Value := cliprovincia; clicodpost := ''; // qclientes_contacodpost.AsString; clicodpost := clicodpost + StringOfChar(' ', 7 - length(clicodpost)); qconta_subctacodpost.Value := clicodpost; qconta_subcta.Post; SaveDialog1.FileName := 'subcta.txt'; SaveDialog1.Execute(); archivo := SaveDialog1.FileName; try assignfile(fichero, archivo); rewrite(fichero); qconta_subcta.First; while not qconta_subcta.Eof do begin writeln(fichero, qconta_subctacuenta.AsString + qconta_subctatitulo.AsString + qconta_subctanif.AsString + qconta_subctadomicilio.AsString + qconta_subctapoblacion.AsString + qconta_subctaprovincia.AsString + qconta_subctacodpost.AsString + qconta_subctaint1.AsString); qconta_subcta.Next; end; finally closefile(fichero); showmessage('Los datos han sido exportados correctamente'); end; /// ///////////////// exportanto fichero diario //////////////////// facturas.First; qaux.Close; qaux.sql.clear; qaux.sql.Add('delete from conta_diario'); qaux.execsql; qconta_diario.Close; qconta_diario.Open; x := 1; while not facturas.Eof do begin qaux.Close; qaux.sql.clear; qaux.sql.Add('select seriecontable from series_numericas where id=' + '''' + facturasserie.AsString + '''' + ' and ide=' + facturasidempresa.AsString); qaux.Open; sconta := qaux.Fields[0].AsString; qaux.Close; qaux.sql.clear; qaux.sql.Add('select tipocliente from clientes where id=' + facturasidcliente.AsString); qaux.Open; if qaux.Fields[0].AsString = 'NACIONAL' then dorigen := 'N'; if qaux.Fields[0].AsString = 'INTRACOMUNITARIO' then dorigen := 'I'; if qaux.Fields[0].AsString = 'EXTRANJERO' then dorigen := 'E'; qconta_diario.Append; dasiento := inttostr(x); dasiento := StringOfChar(' ', 6 - length(dasiento)) + dasiento; qconta_diarioasiento.Value := dasiento; decodedate(facturasfecha.AsDateTime, anyo, mes, dia); tdia := floattostr(dia); tdia := StringOfChar('0', 2 - length(tdia)) + tdia; tmes := floattostr(mes); tmes := StringOfChar('0', 2 - length(tmes)) + tmes; tanyo := floattostr(anyo); tanyo := StringOfChar('0', 4 - length(tanyo)) + tanyo; dfecha := tanyo + tmes + tdia; dfecha := dfecha + StringOfChar(' ', 8 - length(dfecha)); qconta_diariofecha.Value := dfecha; qaux.Close; qaux.sql.clear; qaux.sql.Add('select ccontable from clientes where id=' + facturasidcliente.AsString); qaux.Open; dcuenta := qaux.Fields[0].AsString; dcuenta := dcuenta + StringOfChar(' ', 12 - length(dcuenta)); qconta_diariocuenta.Value := dcuenta; dcontrapartida := ''; dcontrapartida := dcontrapartida + StringOfChar(' ', 12 - length(dcontrapartida)); qconta_diariocontrapartida.Value := dcontrapartida; decodedate(facturasfecha.AsDateTime, anyo, mes, dia); tdia := floattostr(dia); tdia := StringOfChar('0', 2 - length(tdia)) + tdia; tmes := floattostr(mes); tmes := StringOfChar('0', 2 - length(tmes)) + tmes; tanyo := floattostr(anyo); tanyo := StringOfChar('0', 4 - length(tanyo)) + tanyo; dconcepto := 'F' + facturasserie.AsString + '' + facturasid.AsString + ' ' + tdia + '' + tmes + ' ' + qaux.Fields[0].AsString; dconcepto := dconcepto + StringOfChar(' ', 25 - length(dconcepto)); dconcepto := Copy(dconcepto, 0, 25); qconta_diarioconcepto.Value := dconcepto; dfactura := facturasid.AsString; dfactura := StringOfChar(' ', 8 - length(dfactura)) + dfactura; qconta_diariofactura.Value := dfactura; dfecha_recep := ''; dfecha_recep := dfecha_recep + StringOfChar(' ', 8 - length(dfecha_recep)); qconta_diariofecha_recep.Value := dfecha_recep; diva := '0.00'; diva := StringOfChar(' ', 5 - length(diva)) + diva; qconta_diarioiva.Value := diva; drec_equiv := '0.00'; drec_equiv := StringOfChar(' ', 5 - length(drec_equiv)) + drec_equiv; qconta_diariorec_equiv.Value := drec_equiv; ddocumento := facturasid.AsString; ddocumento := StringOfChar('0', 10 - length(ddocumento)) + ddocumento; qconta_diariodocumento.Value := ddocumento; dserie := sconta; dserie := dserie + StringOfChar(' ', 1 - length(dserie)); qconta_diarioserie.Value := dserie; daccion := 'A'; daccion := daccion + StringOfChar(' ', 1 - length(daccion)); qconta_diarioaccion.Value := daccion; doperacioniva := 'R'; doperacioniva := doperacioniva + StringOfChar(' ', 1 - length(doperacioniva)); qconta_diariooperacioniva.Value := doperacioniva; dorigen := dorigen + StringOfChar(' ', 1 - length(dorigen)); qconta_diarioorigen.Value := dorigen; dtipoapunte := ' '; dtipoapunte := dtipoapunte + StringOfChar(' ', 1 - length(dtipoapunte)); qconta_diariotipoapunte.Value := dtipoapunte; dimpdebe := stringreplace(format('%5.2f', [facturastotal.AsFloat]), ',', '.', [rfreplaceall]); dimpdebe := StringOfChar(' ', 16 - length(dimpdebe)) + dimpdebe; qconta_diarioimpdebe.Value := dimpdebe; dimphaber := '0.00'; dimphaber := StringOfChar(' ', 16 - length(dimphaber)) + dimphaber; qconta_diarioimphaber.Value := dimphaber; dbaseimpo := stringreplace(format('%5.2f', [facturasneto.AsFloat]), ',', '.', [rfreplaceall]); // '0.00'; dbaseimpo := StringOfChar(' ', 16 - length(dbaseimpo)) + dbaseimpo; qconta_diariobaseimpo.Value := dbaseimpo; qconta_diario.Post; /// / inserto la contrapartida qconta_diario.Append; dasiento := inttostr(x); dasiento := StringOfChar(' ', 6 - length(dasiento)) + dasiento; qconta_diarioasiento.Value := dasiento; decodedate(facturasfecha.AsDateTime, anyo, mes, dia); tdia := floattostr(dia); tdia := StringOfChar('0', 2 - length(tdia)) + tdia; tmes := floattostr(mes); tmes := StringOfChar('0', 2 - length(tmes)) + tmes; tanyo := floattostr(anyo); tanyo := StringOfChar('0', 4 - length(tanyo)) + tanyo; dfecha := tanyo + tmes + tdia; dfecha := dfecha + StringOfChar(' ', 8 - length(dfecha)); qconta_diariofecha.Value := dfecha; qaux.Close; qaux.sql.clear; qaux.sql.Add('select ccontable from clientes where id=' + facturasidcliente.AsString); qaux.Open; dcuenta := '70000000'; // qaux.Fields[0].AsString; dcuenta := dcuenta + StringOfChar(' ', 12 - length(dcuenta)); qconta_diariocuenta.Value := dcuenta; dcontrapartida := qaux.Fields[0].AsString;; dcontrapartida := dcontrapartida + StringOfChar(' ', 12 - length(dcontrapartida)); qconta_diariocontrapartida.Value := dcontrapartida; decodedate(facturasfecha.AsDateTime, anyo, mes, dia); tdia := floattostr(dia); tdia := StringOfChar('0', 2 - length(tdia)) + tdia; tmes := floattostr(mes); tmes := StringOfChar('0', 2 - length(tmes)) + tmes; tanyo := floattostr(anyo); tanyo := StringOfChar('0', 4 - length(tanyo)) + tanyo; dconcepto := 'F' + facturasserie.AsString + '' + facturasid.AsString + ' ' + tdia + '' + tmes + ' ' + qaux.Fields[0].AsString; dconcepto := dconcepto + StringOfChar(' ', 25 - length(dconcepto)); dconcepto := Copy(dconcepto, 0, 25); qconta_diarioconcepto.Value := dconcepto; dfactura := facturasid.AsString; dfactura := StringOfChar(' ', 8 - length(dfactura)) + dfactura; qconta_diariofactura.Value := dfactura; dfecha_recep := ''; dfecha_recep := dfecha_recep + StringOfChar(' ', 8 - length(dfecha_recep)); qconta_diariofecha_recep.Value := dfecha_recep; diva := '0.00'; diva := StringOfChar(' ', 5 - length(diva)) + diva; qconta_diarioiva.Value := diva; drec_equiv := '0.00'; drec_equiv := StringOfChar(' ', 5 - length(drec_equiv)) + drec_equiv; qconta_diariorec_equiv.Value := drec_equiv; ddocumento := facturasid.AsString; ddocumento := StringOfChar('0', 10 - length(ddocumento)) + ddocumento; qconta_diariodocumento.Value := ddocumento; dserie := sconta; dserie := dserie + StringOfChar(' ', 1 - length(dserie)); qconta_diarioserie.Value := dserie; daccion := 'A'; daccion := daccion + StringOfChar(' ', 1 - length(daccion)); qconta_diarioaccion.Value := daccion; doperacioniva := 'R'; doperacioniva := doperacioniva + StringOfChar(' ', 1 - length(doperacioniva)); qconta_diariooperacioniva.Value := doperacioniva; dorigen := dorigen + StringOfChar(' ', 1 - length(dorigen)); qconta_diarioorigen.Value := dorigen; dtipoapunte := 'V'; dtipoapunte := dtipoapunte + StringOfChar(' ', 1 - length(dtipoapunte)); qconta_diariotipoapunte.Value := dtipoapunte; dimpdebe := '0.00'; // facturastotal.asstring; dimpdebe := StringOfChar(' ', 16 - length(dimpdebe)) + dimpdebe; qconta_diarioimpdebe.Value := dimpdebe; dimphaber := stringreplace(format('%16.2f', [(facturastotal.AsFloat - facturastotaliva.AsFloat)]), ',', '.', [rfreplaceall]); // '0.00'; dimphaber := StringOfChar(' ', 16 - length(dimphaber)) + dimphaber; qconta_diarioimphaber.Value := dimphaber; dbaseimpo := stringreplace(format('%5.2f', [facturasneto.AsFloat]), ',', '.', [rfreplaceall]); // '0.00'; dbaseimpo := StringOfChar(' ', 16 - length(dbaseimpo)) + dbaseimpo; qconta_diariobaseimpo.Value := dbaseimpo; qconta_diario.Post; /// / inserto los apuntes de iva qaux2.Close; qaux2.sql.clear; qaux2.sql.Add('select * from facturas_iva where ide=+' + facturasidempresa.AsString + ' and serie=' + '''' + facturasserie.AsString + '''' + ' and idfactura=' + facturasid.AsString + ' order by tipo'); qaux2.Open; if qaux2.RecordCount > 0 then begin while not qaux2.Eof do begin if qaux2base.AsInteger > 0 then begin qconta_diario.Append; dasiento := inttostr(x); dasiento := StringOfChar(' ', 6 - length(dasiento)) + dasiento; qconta_diarioasiento.Value := dasiento; decodedate(facturasfecha.AsDateTime, anyo, mes, dia); tdia := floattostr(dia); tdia := StringOfChar('0', 2 - length(tdia)) + tdia; tmes := floattostr(mes); tmes := StringOfChar('0', 2 - length(tmes)) + tmes; tanyo := floattostr(anyo); tanyo := StringOfChar('0', 4 - length(tanyo)) + tanyo; dfecha := tanyo + tmes + tdia; dfecha := dfecha + StringOfChar(' ', 8 - length(dfecha)); qconta_diariofecha.Value := dfecha; qaux.Close; qaux.sql.clear; qaux.sql.Add('select ccontable from clientes where id=' + facturasidcliente.AsString); qaux.Open; if qaux2tipo.AsInteger = 0 then dcuenta := '47701000'; // qaux.Fields[0].AsString; if qaux2tipo.AsInteger = 2 then dcuenta := '47700002'; // qaux.Fields[0].AsString; if qaux2tipo.AsInteger = 4then dcuenta := '47700004'; // qaux.Fields[0].AsString; if qaux2tipo.AsInteger = 10 then dcuenta := '47700010'; // qaux.Fields[0].AsString; if qaux2tipo.AsInteger = 21 then dcuenta := '47700021'; // qaux.Fields[0].AsString; if dorigen = 'E' then dcuenta := '47702000'; // qaux.Fields[0].AsString; dcuenta := dcuenta + StringOfChar(' ', 12 - length(dcuenta)); qconta_diariocuenta.Value := dcuenta; dcontrapartida := qaux.Fields[0].AsString;; dcontrapartida := dcontrapartida + StringOfChar(' ', 12 - length(dcontrapartida)); qconta_diariocontrapartida.Value := dcontrapartida; decodedate(facturasfecha.AsDateTime, anyo, mes, dia); tdia := floattostr(dia); tdia := StringOfChar('0', 2 - length(tdia)) + tdia; tmes := floattostr(mes); tmes := StringOfChar('0', 2 - length(tmes)) + tmes; tanyo := floattostr(anyo); tanyo := StringOfChar('0', 4 - length(tanyo)) + tanyo; dconcepto := 'F' + facturasserie.AsString + '' + facturasid.AsString + ' ' + tdia + '' + tmes + ' ' + qaux.Fields[0].AsString; dconcepto := dconcepto + StringOfChar(' ', 25 - length(dconcepto)); dconcepto := Copy(dconcepto, 0, 25); qconta_diarioconcepto.Value := dconcepto; dfactura := facturasid.AsString; dfactura := StringOfChar(' ', 8 - length(dfactura)) + dfactura; qconta_diariofactura.Value := dfactura; dfecha_recep := ''; dfecha_recep := dfecha_recep + StringOfChar(' ', 8 - length(dfecha_recep)); qconta_diariofecha_recep.Value := dfecha_recep; diva := stringreplace(format('%5.2f', [qaux2tipo.AsFloat]), ',', '.', [rfreplaceall]); // '0.00'; diva := StringOfChar(' ', 5 - length(diva)) + diva; qconta_diarioiva.Value := diva; drec_equiv := '0.00'; drec_equiv := StringOfChar(' ', 5 - length(drec_equiv)) + drec_equiv; qconta_diariorec_equiv.Value := drec_equiv; ddocumento := facturasid.AsString; ddocumento := StringOfChar('0', 10 - length(ddocumento)) + ddocumento; qconta_diariodocumento.Value := ddocumento; dserie := sconta; dserie := dserie + StringOfChar(' ', 1 - length(dserie)); qconta_diarioserie.Value := dserie; daccion := 'A'; daccion := daccion + StringOfChar(' ', 1 - length(daccion)); qconta_diarioaccion.Value := daccion; doperacioniva := 'R'; doperacioniva := doperacioniva + StringOfChar(' ', 1 - length(doperacioniva)); qconta_diariooperacioniva.Value := doperacioniva; dorigen := dorigen + StringOfChar(' ', 1 - length(dorigen)); qconta_diarioorigen.Value := dorigen; dtipoapunte := 'I'; dtipoapunte := dtipoapunte + StringOfChar(' ', 1 - length(dtipoapunte)); qconta_diariotipoapunte.Value := dtipoapunte; dimpdebe := '0.00'; // facturastotal.asstring; dimpdebe := StringOfChar(' ', 16 - length(dimpdebe)) + dimpdebe; qconta_diarioimpdebe.Value := dimpdebe; dimphaber := stringreplace(format('%16.2f', [qaux2iva.AsFloat]), ',', '.', [rfreplaceall]); // '0.00'; dimphaber := StringOfChar(' ', 16 - length(dimphaber)) + dimphaber; qconta_diarioimphaber.Value := dimphaber; dbaseimpo := stringreplace(format('%16.2f', [qaux2base.AsFloat]), ',', '.', [rfreplaceall]); // '0.00'; dbaseimpo := StringOfChar(' ', 16 - length(dbaseimpo)) + dbaseimpo; qconta_diariobaseimpo.Value := dbaseimpo; qconta_diario.Post; end; qaux2.Next; end; end; facturas.Next; x := x + 1; end; SaveDialog1.FileName := 'diario.txt'; SaveDialog1.Execute(); archivo := SaveDialog1.FileName; try Deletefile(archivo); assignfile(fichero, archivo); rewrite(fichero); qconta_diario.First; while not qconta_diario.Eof do begin writeln(fichero, qconta_diarioasiento.AsString, qconta_diariofecha.AsString, qconta_diariocuenta.AsString, qconta_diariocontrapartida.AsString, qconta_diariointerno1.AsString, qconta_diarioconcepto.AsString, qconta_diariointerno2.AsString, qconta_diariofactura.AsString, qconta_diariointerno3.AsString, qconta_diariofecha_recep.AsString, qconta_diariointerno4.AsString, qconta_diarioiva.AsString, qconta_diariorec_equiv.AsString, qconta_diariodocumento.AsString, qconta_diariointerno5.AsString, qconta_diariointerno6.AsString, qconta_diariointerno7.AsString, qconta_diariointerno8.AsString, qconta_diariointerno9.AsString, qconta_diarioserie.AsString, qconta_diarioaccion.AsString, qconta_diariooperacioniva.AsString, qconta_diarioorigen.AsString, qconta_diariotipoapunte.AsString, qconta_diariointerno10.AsString, qconta_diariointerno11.AsString, qconta_diariointerno12.AsString, qconta_diarioimpdebe.AsString, qconta_diarioimphaber.AsString, qconta_diariobaseimpo.AsString, qconta_diariointerno13.AsString); qconta_diario.Next; end; finally closefile(fichero); showmessage('Los datos han sido exportados correctamente'); end; end; procedure Tfacturas.btfiltrarClick(Sender: TObject); var dia, mes, anyo: Word; filtro, filtro2, tdesde, thasta: string; begin decodedate(fdesde.Date, anyo, mes, dia); tdesde := '''' + floattostr(anyo) + '/' + floattostr(mes) + '/' + floattostr(dia) + ''''; decodedate(fhasta.Date, anyo, mes, dia); thasta := '''' + floattostr(anyo) + '/' + floattostr(mes) + '/' + floattostr(dia) + ''''; filtro := ' where fecha>=' + tdesde + ' and fecha<=' + thasta + ' and serie=' + '''' + qseries2id.AsString + ''''; if (combolistcliente.Text <> '') and (combolistcliente.Text <> ' TODOS') then begin filtro := filtro + ' and nif=' + '''' + listaclientesnif.AsString + ''''; end; if (combolistdestinos.Text <> '') and (combolistdestinos.Text <> ' TODOS') then begin filtro := filtro + ' and nomdestino=' + '''' + listadestinosnomdestino.AsString + ''''; end; filtro := filtro + ' order by serie desc,id desc'; facturas.Close; facturas.sql.clear; facturas.sql.Add('select * from facturas ' + filtro); facturas.Open; DBGrid6.BringToFront; DBGrid6.Visible := True; DBGridacumulados.Visible := False; end; procedure Tfacturas.comboseriesCloseUp(Sender: TObject); begin facturasid.Value := qseriesnum_factura.AsInteger; end; procedure Tfacturas.comboseriesEnter(Sender: TObject); begin comboseries.DropDown; end; procedure Tfacturas.DBGrid5ColExit(Sender: TObject); begin if facturasdetalle.State in [dsedit, dsinsert] then begin if DBGrid5.SelectedIndex = 0 then begin filtro := facturasdetalleidarticulo.AsString; qarticulos.Close; qarticulos.Open; if qarticulos.RecordCount > 0 then begin qtipos_iva.Open; facturasdetalledescripcion.Value := qarticulosdescripcion.AsString; if qclientesexento_iva.AsInteger = 0 then facturasdetalletipoiva.Value := qtipos_ivatipo.AsFloat else facturasdetalletipoiva.Value := 0; qtipos_ivatipo.AsFloat; end; end; end; end; procedure Tfacturas.DBGrid5KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = 115) then begin buscararticulos := Tbuscararticulos.Create(nil); try fbuscararticulos.padre := facturas.Name; fbuscararticulos.filtro := facturasdetalleidarticulo.AsString; buscararticulos.Edit1.Text := facturasdetalleidarticulo.AsString; buscararticulos.showmodal(); finally if facturasdetalle.State in [dsbrowse] then facturasdetalle.edit; facturasdetalleidarticulo.Value := buscararticulos.qarticuloscodigo.AsString; facturasdetalledescripcion.Value := buscararticulos.qarticulosdescripcion.AsString; facturasdetalletipoiva.Value := buscararticulos.qtipos_ivatipo.AsFloat; buscararticulos.Free; end; end; end; procedure Tfacturas.DBGrid6DblClick(Sender: TObject); begin pestañas.TabIndex := 0; end; procedure Tfacturas.DBGrid6DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if facturascobrado.AsInteger = 0 then begin DBGrid6.Canvas.brush.Color := rojo; end; if facturascobrado.AsInteger = 1 then begin DBGrid6.Canvas.brush.Color := verde; end; DBGrid6.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure Tfacturas.DBGrid6TitleClick(Column: TColumn); var st: ZAbstractRODataset.TSortType; begin st := facturas.SortType; facturas.SortedFields := Column.FieldName; If st = stAscending then facturas.SortType := stDescending else facturas.SortType := stAscending; dsfacturas.DataSet.First; end; procedure Tfacturas.comboclientesCloseUp(Sender: TObject); begin facturasnomcliente.Value := qclientesnombre.AsString; facturasnif.Value := qclientesnif.AsString; facturasdireccion.Value := qclientesdireccion.AsString; facturasprovincia.Value := qclientesprovincia.AsString; facturaspoblacion.Value := qclientespoblacion.AsString; facturascodpost.Value := qclientescodpost.AsString; facturaspaiscliente.Value := qclientespais.AsString; facturasidformapago.Value := qclientesidformapago.AsInteger; end; procedure Tfacturas.combodestinosCloseUp(Sender: TObject); begin facturasnomdestino.Value := qdestinosdescripcion.AsString; facturasdirecciondestino.Value := qdestinosdireccion.AsString; facturasprovinciadestino.Value := qdestinosprovincia.AsString; facturaspoblaciondestino.Value := qdestinospoblacion.AsString; facturascodpostdestino.Value := qdestinoscodpost.AsString; facturaspaisdestino.Value := qdestinospais.AsString; end; procedure Tfacturas.dsfacturasDataChange(Sender: TObject; Field: TField); begin if (facturas.State in [dsbrowse]) and (facturas.RecordCount > 0) then begin qalbaranes2.Close; qalbaranes2.sql.clear; qalbaranes2.sql.Add ('select * from albaranes where (idempresa,serie,id) in (select idempresa,serie,idalbaran from albaranes_detalles where'); qalbaranes2.sql.Add(' idfactura=' + facturasid.AsString + ' and serie=' + '''' + facturasserie.AsString + '''' + ' and idempresa=' + facturasidempresa.AsString + ') order by serie desc, id desc'); qalbaranes2.Open; qalbaranesdetalle2.sql.clear; qalbaranesdetalle2.sql.Add('select * from albaranes_detalles where serie=' + '''' + facturasserie.AsString + '''' + ' and idfactura=' + facturasid.AsString + ' and idempresa=' + facturasidempresa.AsString + ' order by idarticulo'); qalbaranesdetalle2.Open; qclientes.Close; qclientes.sql.clear; qclientes.sql.Add('select * from clientes where idempresa=' + facturasidempresa.AsString + ' and id=' + facturasidcliente.AsString); qclientes.Open; qdestinos.Close; qdestinos.sql.clear; qdestinos.sql.Add('select * from clientes_destinos where idempresa=' + facturasidempresa.AsString + ' and idcliente=' + facturasidcliente.AsString + ' and codigo=' + '''' + facturasiddestino.AsString + ''''); qdestinos.Open; facturasdetalle.Close; facturasdetalle.prepare; facturasdetalle.ParamByName('SERIE').AsString:=facturasserie.AsString; facturasdetalle.ParamByName('IDFACTURA').AsInteger:=facturasid.Asinteger; facturasdetalle.ParamByName('EMPRESA').AsInteger:=facturasidempresa.AsInteger; facturasdetalle.Open; qfacturasiva.Close; qfacturasiva.Prepare; qfacturasiva.ParamByName('SERIE').AsString:=facturasserie.AsString; qfacturasiva.ParamByName('IDFACTURA').AsInteger:=facturasid.Asinteger; qfacturasiva.ParamByName('EMPRESA').AsInteger:=facturasidempresa.AsInteger; qfacturasiva.Open; end; end; procedure Tfacturas.dsfacturasStateChange(Sender: TObject); begin if facturas.State in [dsedit, dsinsert] then begin btfnuevo.Enabled := False; btfmodificar.Enabled := False; btfborrar.Enabled := False; btfcancelar.Enabled := True; btfguardar.Enabled := True; btfanterior.Enabled := False; btfsiguiente.Enabled := False; btfimportar.Enabled := False; btfimprimir.Enabled := False; qdestinos.Close; qclientes.Close; qdestinos.LinkedFields := 'Idempresa;idcliente'; qdestinos.MasterFields := 'Idempresa;id'; qdestinos.Mastersource := dsqclientes; qclientes.Open; qdestinos.Open; end else begin btfnuevo.Enabled := True; btfmodificar.Enabled := True; btfborrar.Enabled := True; btfcancelar.Enabled := False; btfguardar.Enabled := False; btfanterior.Enabled := True; btfsiguiente.Enabled := True; btfimportar.Enabled := True; btfimprimir.Enabled := True; qclientes.Close; qdestinos.Close; qdestinos.LinkedFields := ''; qdestinos.MasterFields := ''; qdestinos.Mastersource := nil; qclientes.Open; qdestinos.Open; end; end; procedure Tfacturas.dsqseries2DataChange(Sender: TObject; Field: TField); begin facturas.Close; facturas.sql.clear; facturas.sql.Add('select * from facturas where serie=' + '''' + qseries2id.AsString + '''' + ' order by serie desc,id desc'); facturas.Open; end; procedure Tfacturas.facturasBeforeDelete(DataSet: TDataSet); begin case dm.PedirConfirmacion('¿Confirma que desea borrar esta factura?', True, True, False) of mrno: Abort; end; end; procedure Tfacturas.facturasBeforePost(DataSet: TDataSet); var cuenta:string; begin if combocuenta.KeyValue = null then begin facturascccuentabancaria.Value := ''; end else begin cuenta:= qcuentascciban.AsString + qcuentasccentidad.AsString + qcuentasccoficina.AsString + qcuentasccdc.AsString + qcuentascccc.AsString; if facturas.State in [dsedit,dsinsert] then facturascccuentabancaria.Value :=cuenta; end; end; procedure Tfacturas.facturasdetalleAfterPost(DataSet: TDataSet); var serie, id, idfactura, pesobruto, pesoneto, pesonetoteorico, numpalets: string; begin serie := facturasserie.AsString; id := facturasid.AsString; idfactura := serie + '/' + id; qfacturasiva.Refresh; if iddetalle <> '' then facturasdetalle.Locate('id', iddetalle, [locaseinsensitive]) else facturasdetalle.Last; qaux.sql.clear; qaux.sql.Add('select * from ea_pesadas where idfactura=' + '''' + idfactura + '''' + ' and idempresa=' + facturasidempresa.AsString); qaux.Open; if qaux.RecordCount > 0 then begin qaux.sql.clear; qaux.sql.Add ('select sum(peso_bruto-tara0),sum(peso_neto),sum(peso_neto_teorico),sum(num_palets) from ea_pesadas where idfactura=' + '''' + idfactura + '''' + ' and idempresa=' + facturasidempresa.AsString); qaux.Open; pesobruto := qaux.Fields[0].AsString; pesobruto := stringreplace(pesobruto, ',', '.', [rfreplaceall]); pesoneto := qaux.Fields[1].AsString; pesoneto := stringreplace(pesoneto, ',', '.', [rfreplaceall]); pesonetoteorico := qaux.Fields[2].AsString; pesonetoteorico := stringreplace(pesonetoteorico, ',', '.', [rfreplaceall]); numpalets := qaux.Fields[3].AsString; numpalets := stringreplace(numpalets, ',', '.', [rfreplaceall]); qaux.sql.clear; qaux.sql.Add('update facturas set peso_bruto=' + pesobruto + ',kilos=+' + pesoneto + ',kilosventa=' + pesonetoteorico + ',numpalets=+' + numpalets + ' where serie=' + '''' + serie + '''' + ' and id=' + id + ' and idempresa=' + facturasidempresa.AsString);; qaux.execsql; end; facturas.Refresh; facturas.Locate('serie,id', vararrayof([serie, id]), [locaseinsensitive]) { var serie,id:string; begin serie:=facturasserie.AsString; id:=facturasid.AsString; facturas.Refresh; facturas.Locate('serie;id',vararrayof([serie,id]),[locaseinsensitive]); qfacturasiva.Refresh; if iddetalle<>'' then facturasdetalle.Locate('id',iddetalle,[locaseinsensitive]) else facturasdetalle.Last; } end; procedure Tfacturas.facturasdetalleBeforeDelete(DataSet: TDataSet); begin case dm.PedirConfirmacion('¿Confirma que desea borrar esta línea de factura?',true,true,false) of mrno:Abort; end; end; procedure Tfacturas.facturasdetalleBeforePost(DataSet: TDataSet); var iva, re, descuento: real; begin facturasdetalleidempresa.value:=facturasidempresa.asinteger; facturasdetalleidfactura.value:=facturasid.asinteger; facturasdetalleserie.Value:=facturasserie.AsString; if facturasdetalletipoiva.AsString = '' then facturasdetalletipoiva.Value := 0; if facturasdetalledescuento.AsString = '' then facturasdetalledescuento.Value := 0; if facturasdetalletipore.AsString = '' then facturasdetalletipore.Value := 0; facturasdetalleserie.Value := facturasserie.AsString; if facturasfacturarporbultos.asinteger=0 then begin facturasdetallebase.Value := roundto(facturasdetalleprecio.AsFloat * facturasdetallecantidad.AsFloat, -2); end else begin facturasdetallebase.Value := roundto(facturasdetalleprecio.AsFloat * facturasdetallebultos.AsFloat, -2); end; descuento := roundto(facturasdetallebase.AsFloat * (facturasdetalledescuento.AsFloat / 100), -2); facturasdetalletotaldescuento.Value := descuento; facturasdetalletotal.Value := roundto(facturasdetallebase.AsFloat - descuento, -2); iva := roundto(facturasdetalletotal.AsFloat * (facturasdetalletipoiva.AsFloat / 100), -2); re := roundto(facturasdetalletotal.AsFloat * (facturasdetalletipore.AsFloat / 100), -2); facturasdetalleiva.Value := iva; facturasdetallere.Value := re; if facturasdetalle.State in [dsedit] then iddetalle := facturasdetalleid.AsString else iddetalle := ''; end; procedure Tfacturas.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is TDBGrid) then begin if Key = 13 then Key := 9; end; end; procedure Tfacturas.FormKeyPress(Sender: TObject; var Key: Char); var formatos: tformatsettings; punto: string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto := formatos.DecimalSeparator; if punto = ',' then begin Key := upcase(Key); if (Key = '.') and (activecontrol is TDBEdit) then begin if (activecontrol as TDBEdit).Field.DataType in [ftFloat, ftCurrency, ftBCD, ftfmtbcd] then Key := ',' end; if (Key = '.') and (activecontrol is TDBGrid) then begin Key := ','; end; end; if (activecontrol is TDBGrid) then begin if Key = #13 then Key := #9; end; if (Key = #13) then begin Perform(WM_NextDLGCtl, 0, 0); Key := #0; end; end; procedure Tfacturas.alba(Sender: TObject); begin dm.tempresa.Open; qseries.Close; qseries2.Close; qdestinos.Close; qclientes.Close; qalbaranes.Close; qalbaranes2.Close; qalbaranesdetalle.Close; qalbaranesdetalle2.Close; facturas.Close; facturasdetalle.Close; qfacturasiva.Close; qformaspago.Close; qarticulos.Close; qtipos_iva.Close; qcuentas.Close; qfacturasiva.Close; qformularios.Close; qseries.Open; qseries2.Open; qdestinos.Open; qclientes.Open; qalbaranes.Open; qalbaranes2.Open; qalbaranesdetalle.Open; qalbaranesdetalle2.Open; facturas.Close; facturas.sql.clear; facturas.sql.Add('select * from facturas where serie=' + '''' + qseries2id.AsString + '''' + ' order by serie desc,id desc'); facturas.Open; //facturasdetalle.Open; //qfacturasiva.Open; qformaspago.Open; qarticulos.Open; qtipos_iva.Open; qcuentas.Open; qformularios.Open; pestañas.TabIndex := 1; comboserie2.KeyValue := qseries2id.AsString; comboformulario.KeyValue := null; end; procedure Tfacturas.qarticulosBeforeOpen(DataSet: TDataSet); var filtrolocal: string; begin filtrolocal := ''; filtrolocal := ' and (descripcion like(' + '''' + '%' + filtro + '%' + '''' + ') or codigo like(' + '''' + '%' + filtro + '%' + '''' + '))'; qarticulos.sql.clear; qarticulos.sql.Add('select * from articulosf where activo=1 and facturable=1' + filtrolocal + ' order by descripcion'); end; procedure Tfacturas.qfacturasclientes2CalcFields(DataSet: TDataSet); begin if (qfacturasclientes2coste_transporte.AsFloat > 0) and (qfacturasclientes2kilosventa.AsFloat > 0) then qfacturasclientes2transporte_kilo.Value := qfacturasclientes2coste_transporte.AsFloat / qfacturasclientes2kilosventa.AsFloat else qfacturasclientes2transporte_kilo.Value := 0; end; procedure Tfacturas.qfacturasclientesCalcFields(DataSet: TDataSet); begin if (qfacturasclientescoste_transporte.AsFloat > 0) and (qfacturasclienteskilosventa.AsFloat > 0) then qfacturasclientescoste_transporte_1.Value := (qfacturasclientescoste_transporte.AsFloat / qfacturasclienteskilosventa.AsFloat) * qfacturasclientescantidad.AsFloat else qfacturasclientescoste_transporte_1.Value := 0; end; procedure Tfacturas.tablistadoShow(Sender: TObject); begin fdesde.Date := strtodate('01/01/2000'); fhasta.Date := Date(); listaclientes.Close; listadestinos.Close; listaclientes.Open; listadestinos.Open; // btfiltrar.click end; end. ======================================== FICHERO: ffacturas_PORTATIL_ago.-04-174846-2020_Conflict.pas ======================================== unit ffacturas; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.DBCtrls, Vcl.Mask, Vcl.ExtCtrls, Vcl.ComCtrls, Data.DB,math, ZAbstractRODataset, ZAbstractDataset, ZDataset, frxClass, frxDBSet,datos, ComObj, Excel2000; type Tfacturas = class(TForm) PageControl1: TPageControl; TabSheet1: TTabSheet; Panel1: TPanel; Panel4: TPanel; Button1: TButton; Button2: TButton; Button5: TButton; Button6: TButton; Panel2: TPanel; Label6: TLabel; Label7: TLabel; DBText3: TDBText; DBText4: TDBText; DBText5: TDBText; DBText6: TDBText; DBText7: TDBText; DBText8: TDBText; DBText9: TDBText; DBText10: TDBText; DBText11: TDBText; DBText12: TDBText; DBText13: TDBText; DBText14: TDBText; DBText15: TDBText; Panel3: TPanel; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label15: TLabel; DBEdit1: TDBEdit; DBLookupComboBox2: TDBLookupComboBox; DBLookupComboBox3: TDBLookupComboBox; DBEdit2: TDBEdit; DBCheckBox1: TDBCheckBox; DBMemo1: TDBMemo; DBMemo2: TDBMemo; Panel5: TPanel; Label8: TLabel; Label9: TLabel; Label10: TLabel; Label11: TLabel; Label12: TLabel; Label13: TLabel; Label14: TLabel; Panel6: TPanel; DBGrid1: TDBGrid; DBEdit3: TDBEdit; DBEdit4: TDBEdit; DBEdit5: TDBEdit; DBEdit6: TDBEdit; DBEdit7: TDBEdit; DBEdit8: TDBEdit; DBEdit9: TDBEdit; DBGrid2: TDBGrid; Panel7: TPanel; Button4: TButton; TabSheet2: TTabSheet; DBGrid3: TDBGrid; PageControl2: TPageControl; TabSheet3: TTabSheet; Panel8: TPanel; Panel9: TPanel; btfcancelar: TButton; btfmodificar: TButton; btfborrar: TButton; btfnuevo: TButton; btfguardar: TButton; btfimprimir: TButton; btfimportar: TButton; btfsiguiente: TButton; btfanterior: TButton; Panel10: TPanel; Label16: TLabel; Label17: TLabel; DBText1: TDBText; DBText2: TDBText; DBText16: TDBText; DBText17: TDBText; DBText18: TDBText; DBText19: TDBText; DBText20: TDBText; DBText21: TDBText; DBText22: TDBText; DBText23: TDBText; DBText24: TDBText; DBText25: TDBText; DBText26: TDBText; paneldatos: TPanel; Label18: TLabel; Label19: TLabel; Label20: TLabel; Label21: TLabel; Label22: TLabel; Label23: TLabel; comboseries: TDBLookupComboBox; DBEdit10: TDBEdit; comboclientes: TDBLookupComboBox; combodestinos: TDBLookupComboBox; DBEdit11: TDBEdit; DBMemo4: TDBMemo; Panel12: TPanel; Label24: TLabel; Label25: TLabel; Label26: TLabel; Label27: TLabel; Label28: TLabel; Label29: TLabel; Label30: TLabel; Panel13: TPanel; DBGrid4: TDBGrid; DBEdit12: TDBEdit; DBEdit13: TDBEdit; DBEdit14: TDBEdit; DBEdit15: TDBEdit; DBEdit16: TDBEdit; DBEdit17: TDBEdit; DBEdit18: TDBEdit; DBGrid5: TDBGrid; Panel14: TPanel; Button16: TButton; TabSheet4: TTabSheet; DBGrid6: TDBGrid; infdetallefactura: TfrxDBDataset; inffactura: TfrxDBDataset; inffacturaivas: TfrxDBDataset; informe: TfrxReport; dsfacturas: TDataSource; facturas: TZQuery; dsfacturasdetalle: TDataSource; facturasdetalle: TZQuery; dsqseries: TDataSource; dsqclientes: TDataSource; qclientes: TZQuery; qseries: TZQuery; dsqdestinos: TDataSource; qdestinos: TZQuery; qdestinoscodigo: TWideStringField; qdestinosidcliente: TIntegerField; qdestinosidempresa: TIntegerField; qdestinosdescripcion: TWideStringField; qdestinosseleccionado: TIntegerField; qdestinosactivo: TIntegerField; qdestinosdireccion: TWideStringField; qdestinospoblacion: TWideStringField; qdestinoscodpost: TWideStringField; qdestinosprovincia: TWideStringField; qdestinospais: TWideStringField; dsqfacturasiva: TDataSource; qfacturasiva: TZQuery; qalbaranes: TZQuery; qalbaranesdetalle: TZQuery; dsqalbaranes: TDataSource; dsqalbaranesdetalle: TDataSource; facturasid: TIntegerField; facturasidempresa: TIntegerField; facturasidcliente: TIntegerField; facturasiddestino: TWideStringField; facturasnif: TWideStringField; facturasdireccion: TWideStringField; facturaspoblacion: TWideStringField; facturasprovincia: TWideStringField; facturascodpost: TWideStringField; facturasfecha: TDateField; facturasreferencia: TWideStringField; facturastelefono: TWideStringField; facturasnomcliente: TWideStringField; facturaspaiscliente: TWideStringField; facturasnomdestino: TWideStringField; facturasdirecciondestino: TWideStringField; facturaspoblaciondestino: TWideStringField; facturascodpostdestino: TWideStringField; facturasprovinciadestino: TWideStringField; facturaspaisdestino: TWideStringField; facturasneto: TFloatField; facturastotal: TFloatField; facturasdocumento: TWideStringField; facturasdescuento_lin: TFloatField; facturasdescuento_com: TFloatField; facturasdescuento_pp: TFloatField; facturasdescuento_total: TFloatField; facturastotaliva: TFloatField; facturasobservaciones: TWideStringField; facturasdetalleid: TIntegerField; facturasdetalleidempresa: TIntegerField; facturasdetalleidfactura: TIntegerField; facturasdetalleidarticulo: TWideStringField; facturasdetalledescripcion: TWideStringField; facturasdetallecal: TWideStringField; facturasdetallelote: TWideStringField; facturasdetallecantidad: TFloatField; facturasdetalleprecio: TFloatField; facturasdetalledescuento: TFloatField; facturasdetalletotaldescuento: TFloatField; facturasdetallebase: TFloatField; facturasdetalletipoiva: TFloatField; facturasdetalleiva: TFloatField; facturasdetalletotal: TFloatField; qserieside: TIntegerField; qseriesid: TWideStringField; qseriesfechainicio: TDateField; qseriesfechafin: TDateField; qseriesnum_pedcliente: TIntegerField; qseriesnum_albaran: TIntegerField; qseriesnum_factura: TIntegerField; qseriesnum_expedicion: TIntegerField; qseriesnum_pedproveedor: TIntegerField; qclientesid: TIntegerField; qclientesIdempresa: TIntegerField; qclientesnif: TWideStringField; qclientesnombre: TWideStringField; qclientesnombre_corto: TWideStringField; qclientesdireccion: TWideStringField; qclientespoblacion: TWideStringField; qclientescodpost: TWideStringField; qclientesprovincia: TWideStringField; qclientestelefono: TWideStringField; qclientestelefono2: TWideStringField; qclientesmovil: TWideStringField; qclientesemail: TWideStringField; qclientespersonacontacto: TWideStringField; qclientescodigomercado: TIntegerField; qclientesactivo: TIntegerField; qclientesobservaciones: TWideStringField; qclientesccontable: TIntegerField; qclientesdescuento: TFloatField; qclientespais: TWideStringField; qalbaranesid: TIntegerField; qalbaranesidempresa: TIntegerField; qalbaranesidcliente: TIntegerField; qalbaranesiddestino: TWideStringField; qalbaranesnif: TWideStringField; qalbaranesdireccion: TWideStringField; qalbaranespoblacion: TWideStringField; qalbaranesprovincia: TWideStringField; qalbaranescodpost: TWideStringField; qalbaranesfecha: TDateField; qalbaranesreferencia: TWideStringField; qalbaranestelefono: TWideStringField; qalbaranesnomcliente: TWideStringField; qalbaranespaiscliente: TWideStringField; qalbaranesnomdestino: TWideStringField; qalbaranesdirecciondestino: TWideStringField; qalbaranespoblaciondestino: TWideStringField; qalbaranescodpostdestino: TWideStringField; qalbaranesprovinciadestino: TWideStringField; qalbaranespaisdestino: TWideStringField; qalbaranesneto: TFloatField; qalbaranestotal: TFloatField; qalbaranesfacturado: TIntegerField; qalbaranesdocumento: TWideStringField; qalbaranesdescuento_lin: TFloatField; qalbaranesdescuento_com: TFloatField; qalbaranesdescuento_pp: TFloatField; qalbaranesdescuento_total: TFloatField; qalbaranestotaliva: TFloatField; qalbaranesobservaciones: TWideStringField; qalbaranesidfactura: TIntegerField; qalbaranesdetalleid: TIntegerField; qalbaranesdetalleidempresa: TIntegerField; qalbaranesdetalleidalbaran: TIntegerField; qalbaranesdetalleidarticulo: TWideStringField; qalbaranesdetalledescripcion: TWideStringField; qalbaranesdetallecal: TWideStringField; qalbaranesdetallelote: TWideStringField; qalbaranesdetallecantidad: TFloatField; qalbaranesdetalleprecio: TFloatField; qalbaranesdetalledescuento: TFloatField; qalbaranesdetalletotaldescuento: TFloatField; qalbaranesdetallebase: TFloatField; qalbaranesdetalletipoiva: TFloatField; qalbaranesdetalleiva: TFloatField; qalbaranesdetalletotal: TFloatField; dsqalbaranes2: TDataSource; qalbaranes2: TZQuery; dsqalbaranesdetalle2: TDataSource; qalbaranesdetalle2: TZQuery; qfacturasivaidfactura: TIntegerField; qfacturasivaide: TIntegerField; qfacturasivabase: TFloatField; qfacturasivatipo: TFloatField; qfacturasivaiva: TFloatField; qalbaranes2id: TIntegerField; qalbaranes2idempresa: TIntegerField; qalbaranes2idcliente: TIntegerField; qalbaranes2iddestino: TWideStringField; qalbaranes2nif: TWideStringField; qalbaranes2direccion: TWideStringField; qalbaranes2poblacion: TWideStringField; qalbaranes2provincia: TWideStringField; qalbaranes2codpost: TWideStringField; qalbaranes2fecha: TDateField; qalbaranes2referencia: TWideStringField; qalbaranes2telefono: TWideStringField; qalbaranes2nomcliente: TWideStringField; qalbaranes2paiscliente: TWideStringField; qalbaranes2nomdestino: TWideStringField; qalbaranes2direcciondestino: TWideStringField; qalbaranes2poblaciondestino: TWideStringField; qalbaranes2codpostdestino: TWideStringField; qalbaranes2provinciadestino: TWideStringField; qalbaranes2paisdestino: TWideStringField; qalbaranes2neto: TFloatField; qalbaranes2total: TFloatField; qalbaranes2facturado: TIntegerField; qalbaranes2documento: TWideStringField; qalbaranes2descuento_lin: TFloatField; qalbaranes2descuento_com: TFloatField; qalbaranes2descuento_pp: TFloatField; qalbaranes2descuento_total: TFloatField; qalbaranes2totaliva: TFloatField; qalbaranes2observaciones: TWideStringField; qalbaranes2idfactura: TIntegerField; qalbaranesdetalle2id: TIntegerField; qalbaranesdetalle2idempresa: TIntegerField; qalbaranesdetalle2idalbaran: TIntegerField; qalbaranesdetalle2idarticulo: TWideStringField; qalbaranesdetalle2descripcion: TWideStringField; qalbaranesdetalle2cal: TWideStringField; qalbaranesdetalle2lote: TWideStringField; qalbaranesdetalle2cantidad: TFloatField; qalbaranesdetalle2precio: TFloatField; qalbaranesdetalle2descuento: TFloatField; qalbaranesdetalle2totaldescuento: TFloatField; qalbaranesdetalle2base: TFloatField; qalbaranesdetalle2tipoiva: TFloatField; qalbaranesdetalle2iva: TFloatField; qalbaranesdetalle2total: TFloatField; qaux: TZQuery; facturasserie: TWideStringField; facturasdetalleserie: TWideStringField; qalbaranes2serie: TWideStringField; qalbaranesdetalle2serie: TWideStringField; qalbaranesserie: TWideStringField; qalbaranesdetalleserie: TWideStringField; qfacturasivaserie: TWideStringField; qseriesimp_albaran: TWideStringField; qseriesimp_factura: TWideStringField; facturasbultos: TFloatField; facturaskilos: TFloatField; facturasidformapago: TIntegerField; Label31: TLabel; comboformapago: TDBLookupComboBox; qformaspago: TZQuery; dsqformaspago: TDataSource; qformaspagoide: TIntegerField; qformaspagoid: TIntegerField; qformaspagocodigo: TWideStringField; qformaspagodescripcion: TWideStringField; qformaspagodias: TIntegerField; qclientesidformapago: TIntegerField; qalbaranesdetallebultos: TFloatField; qalbaranesdetalle2bultos: TFloatField; dsqarticulos: TDataSource; qarticulos: TZReadOnlyQuery; qtipos_iva: TZReadOnlyQuery; DataSource1: TDataSource; qtipos_ivaid: TIntegerField; qtipos_ivadescripcion: TWideStringField; qtipos_ivatipo: TIntegerField; qtipos_ivatipo_req: TFloatField; qarticulosidempresa: TIntegerField; qarticulosid: TIntegerField; qarticuloscodigo: TWideStringField; qarticulosdescripcion: TWideStringField; qarticulosfamilia: TIntegerField; qarticulosprovhab: TIntegerField; qarticulostipoiva: TIntegerField; qarticulospreciocoste: TFloatField; qarticulosmargen: TFloatField; qarticulosbeneficio: TFloatField; qarticulospvp: TFloatField; qarticulosstock: TFloatField; qarticulosult_preciocompra: TFloatField; qarticulosfacturable: TIntegerField; qarticulosobservaciones: TWideStringField; qarticulosimagen: TBlobField; qarticulosactivo: TIntegerField; qarticulosvalor_almacen: TFloatField; qarticulosstock_minimo: TFloatField; qarticulosavisar_stock: TIntegerField; qarticuloscontrolar_traza: TIntegerField; qarticulospeso: TFloatField; listaimpresion: TComboBox; facturasdetallebultos: TFloatField; Panel11: TPanel; Button3: TButton; gridfacturasaexcel: TDBGrid; qfacturasclientes: TZReadOnlyQuery; qfacturasclientesserie: TWideStringField; qfacturasclientesid: TIntegerField; qfacturasclientesidempresa: TIntegerField; qfacturasclientesidcliente: TIntegerField; qfacturasclientesiddestino: TWideStringField; qfacturasclientesnif: TWideStringField; qfacturasclientesdireccion: TWideStringField; qfacturasclientespoblacion: TWideStringField; qfacturasclientesprovincia: TWideStringField; qfacturasclientescodpost: TWideStringField; qfacturasclientesfecha: TDateField; qfacturasclientesreferencia: TWideStringField; qfacturasclientestelefono: TWideStringField; qfacturasclientesnomcliente: TWideStringField; qfacturasclientespaiscliente: TWideStringField; qfacturasclientesnomdestino: TWideStringField; qfacturasclientesdirecciondestino: TWideStringField; qfacturasclientespoblaciondestino: TWideStringField; qfacturasclientescodpostdestino: TWideStringField; qfacturasclientesprovinciadestino: TWideStringField; qfacturasclientespaisdestino: TWideStringField; qfacturasclientesneto: TFloatField; qfacturasclientestotal: TFloatField; qfacturasclientesfacturado: TIntegerField; qfacturasclientesdocumento: TWideStringField; qfacturasclientesdescuento_lin: TFloatField; qfacturasclientesdescuento_com: TFloatField; qfacturasclientesdescuento_pp: TFloatField; qfacturasclientesdescuento_total: TFloatField; qfacturasclientestotaliva: TFloatField; qfacturasclientesobservaciones: TWideStringField; qfacturasclientesbultos: TFloatField; qfacturasclienteskilos: TFloatField; qfacturasclientesidformapago: TIntegerField; qfacturasclientesserie_1: TWideStringField; qfacturasclientesidfactura: TIntegerField; qfacturasclienteside: TIntegerField; qfacturasclientesbase: TFloatField; qfacturasclientestipo: TFloatField; qfacturasclientesiva: TFloatField; dsqfacturasclientes: TDataSource; SaveDialog1: TSaveDialog; qclientesexento_iva: TIntegerField; facturascobrado: TIntegerField; DBCheckBox2: TDBCheckBox; Panel15: TPanel; listaclientes: TZQuery; listaclientesnif: TWideStringField; listaclientesnomcliente: TWideStringField; DBLookupComboBox1: TDBLookupComboBox; DBLookupComboBox4: TDBLookupComboBox; listadestinos: TZQuery; dslistadestinos: TDataSource; dslistacliente: TDataSource; listadestinosnomdestino: TWideStringField; Button7: TButton; Label32: TLabel; Label33: TLabel; Label34: TLabel; Label35: TLabel; DateTimePicker1: TDateTimePicker; DateTimePicker2: TDateTimePicker; procedure dsfacturasStateChange(Sender: TObject); procedure dsfacturasDataChange(Sender: TObject; Field: TField); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure btfimportarClick(Sender: TObject); procedure btfnuevoClick(Sender: TObject); procedure comboseriesCloseUp(Sender: TObject); procedure comboseriesEnter(Sender: TObject); procedure comboclientesEnter(Sender: TObject); procedure comboclientesCloseUp(Sender: TObject); procedure FormShow(Sender: TObject); procedure combodestinosEnter(Sender: TObject); procedure combodestinosCloseUp(Sender: TObject); procedure btfborrarClick(Sender: TObject); procedure btfmodificarClick(Sender: TObject); procedure btfguardarClick(Sender: TObject); procedure facturasdetalleBeforePost(DataSet: TDataSet); procedure facturasdetalleAfterPost(DataSet: TDataSet); procedure Button16Click(Sender: TObject); procedure DBGrid6TitleClick(Column: TColumn); procedure btfcancelarClick(Sender: TObject); procedure btfanteriorClick(Sender: TObject); procedure btfsiguienteClick(Sender: TObject); procedure btfimprimirClick(Sender: TObject); procedure DBGrid5KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure TabSheet4Enter(Sender: TObject); procedure DBGrid5ColExit(Sender: TObject); procedure qarticulosBeforeOpen(DataSet: TDataSet); procedure Button3Click(Sender: TObject); private { Private declarations } public { Public declarations } procedure ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar = nil); end; var facturas: Tfacturas; filtro,iddetalle:string; implementation {$R *.dfm} uses fselectalbaranes,fbuscararticulos; procedure TFacturas.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 Tfacturas.btfcancelarClick(Sender: TObject); begin facturas.Cancel; paneldatos.Enabled:=false; end; procedure Tfacturas.btfguardarClick(Sender: TObject); var empresa,serie:string; begin empresa:=facturasidempresa.AsString; serie:=facturasserie.AsString; qaux.sql.clear; facturas.Post; qaux.sql.clear; qaux.SQL.Add('select max(id) from facturas where idempresa='+empresa+' and serie='+''''+serie+''''); qaux.Open; qseries.edit; qseriesnum_factura.Value:=qaux.Fields[0].AsInteger+1; qseries.Post; facturasdetalle.open; qfacturasiva.open; facturas.Refresh; facturasdetalle.Refresh; qfacturasiva.Refresh; paneldatos.Enabled:=false; end; procedure Tfacturas.btfimportarClick(Sender: TObject); begin seleccionaralbaranes := Tseleccionaralbaranes.Create(nil); try seleccionaralbaranes.showmodal(); finally seleccionaralbaranes.Free; end; facturas.Refresh; qfacturasiva.refresh; end; procedure Tfacturas.btfimprimirClick(Sender: TObject); var filtro,documento,formapago:string; desg_ivas,tipo,base,iva:string; x:integer; fecha:tdate; begin if listaimpresion.ItemIndex=0 then begin facturasdetalle.Close; facturasdetalle.SQL.Clear; facturasdetalle.SQL.Add('select idempresa,idfactura,sum(cantidad) as cantidad,precio,descuento,sum(base) as base,descripcion,cal,sum(bultos) as bultos,tipoiva,sum(iva) as iva,sum(total) as total,id,'+''''''+' as idarticulo,sum(totaldescuento) as totaldescuento,'+''''''+' as lote,serie '); facturasdetalle.SQL.Add(' from facturas_detalles group by idempresa,idfactura,descripcion,cal,precio'); facturasdetalle.open; end; if listaimpresion.ItemIndex=1 then begin facturasdetalle.Close; facturasdetalle.SQL.Clear; facturasdetalle.SQL.Add('select * from facturas_detalles'); facturasdetalle.open; end; filtro:='id='; filtro:=filtro+facturasid.asstring; filtro:=filtro+' and serie='+''''+ facturasserie.AsString+''''; documento:=qseriesimp_factura.asstring; facturas.Filter:=filtro; facturas.filtered:=true; fecha:=facturasfecha.AsDateTime; fecha:=fecha+qformaspagodias.asinteger; formapago:='FORMA DE PAGO: '+qformaspagodescripcion.AsString+' FECHA DE VENCIMIENTO EL '+DATETOSTR(FECHA); qfacturasiva.First; desg_ivas:=''; while not qfacturasiva.Eof do begin if qfacturasivabase.AsFloat>0 then begin tipo:=format('%2d',[qfacturasivatipo.asinteger]); base:=format('%10.2f',[qfacturasivabase.Asfloat]); iva:=format('%8.2f',[qfacturasivaiva.asfloat]); desg_ivas:=desg_ivas+tipo+base+iva+' '; end; qfacturasiva.Next; end; inffactura.Datasource:=dsfacturas; infdetallefactura.Datasource:=dsfacturasdetalle; inffacturaivas.Datasource:=dsqfacturasiva; informe.Report.Clear; informe.LoadFromFile('c:\agrigest\informes\'+documento+'.fr3'); informe.Variables.Variables['FORMAPAGO']:=QUOTEDSTR(formapago); informe.Variables.Variables['DESGIVAS']:=QUOTEDSTR(desg_ivas); informe.ShowReport(); informe.Clear; // informe.Variables.Variables['TITULO']:=QUOTEDSTR(panel100.Caption); facturas.filtered:=false; end; procedure Tfacturas.btfmodificarClick(Sender: TObject); begin paneldatos.Enabled:=true; facturas.Edit; qclientes.Close; qclientes.SQL.Clear; qclientes.SQL.Add('select * from clientes order by nombre'); qclientes.open; qdestinos.Close; qdestinos.SQL.Clear; qdestinos.SQL.Add('select * from clientes_destinos order by descripcion'); qdestinos.open; end; procedure Tfacturas.btfanteriorClick(Sender: TObject); begin facturas.Next; end; procedure Tfacturas.btfborrarClick(Sender: TObject); begin facturasdetalle.open; if facturas.recordcount>0 then begin facturas.Delete; facturasdetalle.Refresh; qalbaranes.Refresh; qalbaranes2.Refresh; qalbaranesdetalle.Refresh; qalbaranesdetalle2.Refresh; qfacturasiva.refresh; end; end; procedure Tfacturas.btfnuevoClick(Sender: TObject); begin paneldatos.Enabled:=true; comboseries.SetFocus; comboseries.KeyValue:=qseriesid.Asstring; //fechaalbaran.Date:=date; facturas.Append; qclientes.Close; qclientes.SQL.Clear; qclientes.SQL.Add('select * from clientes order by nombre'); qclientes.open; qdestinos.Close; qdestinos.SQL.Clear; qdestinos.SQL.Add('select * from clientes_destinos order by descripcion'); qdestinos.open; facturasdetalle.Close; qfacturasiva.close; facturasfecha.Value:=date; end; procedure Tfacturas.btfsiguienteClick(Sender: TObject); begin facturas.Prior; end; procedure Tfacturas.Button16Click(Sender: TObject); var serie,id:string; begin if facturasdetalle.recordcount>0 then begin serie:=facturasserie.AsString; id:=facturasid.AsString; facturasdetalle.Delete; //1 facturas.Refresh; // facturas.Locate('serie;id',vararrayof([serie,id]),[locaseinsensitive,lopartialkey]); qfacturasiva.Refresh; end; end; procedure Tfacturas.Button3Click(Sender: TObject); var archivo:string; begin qfacturasclientes.Close; qfacturasclientes.SQL.Clear; qfacturasclientes.SQL.Add('select * from facturas f,facturas_iva fi where f.idempresa=fi.ide and f.serie=fi.serie and f.id=fi.idfactura order by f.serie,fecha desc,f.id desc'); qfacturasclientes.open; savedialog1.FileName:='FACTURAS CLIENTES.xls'; savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'facturas',gridfacturasaexcel); finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure Tfacturas.comboseriesCloseUp(Sender: TObject); begin facturasid.value:=qseriesnum_factura.AsInteger; end; procedure Tfacturas.comboseriesEnter(Sender: TObject); begin comboseries.DropDown; end; procedure Tfacturas.DBGrid5ColExit(Sender: TObject); begin if facturasdetalle.State in [dsedit,dsinsert] then begin if dbgrid5.SelectedIndex=0 then begin filtro:=facturasdetalleidarticulo.asstring; qarticulos.Close; qarticulos.Open; if qarticulos.RecordCount>0 then begin qtipos_iva.Open; facturasdetalledescripcion.value:=qarticulosdescripcion.AsString; if qclientesexento_iva.AsInteger=0 then facturasdetalletipoiva.value:=qtipos_ivatipo.Asfloat else facturasdetalletipoiva.value:=0; qtipos_ivatipo.Asfloat; end; end; end; end; procedure Tfacturas.DBGrid5KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (key=115) then begin buscararticulos := Tbuscararticulos.Create(nil); try fbuscararticulos.padre:=facturas.Name; fbuscararticulos.filtro:=facturasdetalleidarticulo.AsString; buscararticulos.Edit1.Text:=facturasdetalleidarticulo.AsString; buscararticulos.showmodal(); finally if facturasdetalle.State in [dsbrowse] then facturasdetalle.Edit; facturasdetalleidarticulo.Value:=buscararticulos.qarticuloscodigo.AsString; facturasdetalledescripcion.value:=buscararticulos.qarticulosdescripcion.AsString; facturasdetalletipoiva.value:=buscararticulos.qtipos_ivatipo.Asfloat; buscararticulos.Free; end; end; end; procedure Tfacturas.DBGrid6TitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=facturas.SortType; facturas.SortedFields:=Column.FieldName; If st = stAscending then facturas.SortType:=stDescending else facturas.SortType:=stAscending; dsfacturas.DataSet.First; end; procedure Tfacturas.comboclientesCloseUp(Sender: TObject); begin facturasnomcliente.value:=qclientesnombre.Asstring; facturasnif.value:=qclientesnif.Asstring; facturasdireccion.value:=qclientesdireccion.Asstring; facturasprovincia.value:=qclientesprovincia.Asstring; facturaspoblacion.Value:=qclientespoblacion.AsString; facturascodpost.value:=qclientescodpost.Asstring; facturaspaiscliente.value:=qclientespais.Asstring; facturasidformapago.Value:=qclientesidformapago.asinteger; end; procedure Tfacturas.comboclientesEnter(Sender: TObject); begin comboclientes.dropdown; end; procedure Tfacturas.combodestinosCloseUp(Sender: TObject); begin facturasnomdestino.value:=qdestinosdescripcion.Asstring; facturasdirecciondestino.value:=qdestinosdireccion.Asstring; facturasprovinciadestino.value:=qdestinosprovincia.Asstring; facturaspoblaciondestino.Value:=qdestinospoblacion.AsString; facturascodpostdestino.value:=qdestinoscodpost.Asstring; facturaspaisdestino.value:=qdestinospais.Asstring; end; procedure Tfacturas.combodestinosEnter(Sender: TObject); begin combodestinos.DropDown; end; procedure Tfacturas.dsfacturasDataChange(Sender: TObject; Field: TField); begin if (facturas.State in [dsbrowse]) and (facturas.recordcount>0) then begin qalbaranes2.Close; qalbaranes2.SQL.Clear; qalbaranes2.SQL.Add('select * from albaranes where'); qalbaranes2.SQL.Add(' idfactura='+facturasid.AsString+' and serie='+''''+facturasserie.AsString+''''+' and idempresa='+facturasidempresa.AsString+' order by serie desc, id desc'); qalbaranes2.Open; qclientes.Close; qclientes.SQL.Clear; qclientes.SQL.Add('select * from clientes where idempresa='+facturasidempresa.asstring+' and id='+facturasidcliente.asstring); qclientes.open; qdestinos.Close; qdestinos.SQL.Clear; qdestinos.SQL.Add('select * from clientes_destinos where idempresa='+facturasidempresa.asstring+' and idcliente='+facturasidcliente.asstring+' and codigo='+''''+facturasiddestino.asstring+''''); qdestinos.open; end; end; procedure Tfacturas.dsfacturasStateChange(Sender: TObject); begin if facturas.State in [dsedit,dsinsert] then begin btfnuevo.Enabled:=false; btfmodificar.Enabled:=false; btfborrar.Enabled:=false; btfcancelar.Enabled:=true; btfguardar.Enabled:=true; qdestinos.Close; qclientes.Close; qdestinos.LinkedFields:='Idempresa;idcliente'; qdestinos.MasterFields:='Idempresa;id'; qdestinos.Mastersource:=dsqclientes; qclientes.open; qdestinos.Open; end else begin btfnuevo.Enabled:=true; btfmodificar.Enabled:=true; btfborrar.Enabled:=true; btfcancelar.Enabled:=false; btfguardar.Enabled:=false; qclientes.Close; qdestinos.Close; qdestinos.LinkedFields:=''; qdestinos.MasterFields:=''; qdestinos.Mastersource:=nil; qclientes.open; qdestinos.Open; end; end; procedure Tfacturas.facturasdetalleAfterPost(DataSet: TDataSet); var serie,id:string; begin serie:=facturasserie.AsString; id:=facturasid.AsString; facturas.Refresh; facturas.Locate('serie;id',vararrayof([serie,id]),[locaseinsensitive]); qfacturasiva.Refresh; if iddetalle<>'' then facturasdetalle.Locate('id',iddetalle,[locaseinsensitive]) else facturasdetalle.Last; end; procedure Tfacturas.facturasdetalleBeforePost(DataSet: TDataSet); var iva,descuento:real; begin if facturasdetalletipoiva.AsString='' then facturasdetalletipoiva.Value:=0; if facturasdetalledescuento.AsString='' then facturasdetalledescuento.Value:=0; facturasdetalleserie.Value:=facturasserie.Asstring; facturasdetallebase.Value:=roundto(facturasdetalleprecio.AsFloat*facturasdetallecantidad.AsFloat,-2); descuento:=roundto(facturasdetallebase.AsFloat*(facturasdetalledescuento.AsFloat/100),-2); facturasdetalletotaldescuento.value:=descuento; facturasdetalletotal.Value:=roundto(facturasdetallebase.Asfloat-descuento,-2); iva:=roundto(facturasdetalletotal.AsFloat*(facturasdetalletipoiva.AsFloat/100),-2); facturasdetalleiva.Value:=iva; if facturasdetalle.State in [dsedit] then iddetalle:=facturasdetalleid.AsString else iddetalle:=''; end; procedure Tfacturas.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tfacturas.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is tdbgrid) then begin key:=','; end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tfacturas.FormShow(Sender: TObject); begin dm.tempresa.Open; qseries.Close; qdestinos.Close; qclientes.Close; qalbaranes.Close; qalbaranes2.close; qalbaranesdetalle.Close; qalbaranesdetalle2.Close; facturas.Close; facturasdetalle.Close; qfacturasiva.Close; qformaspago.Close; qarticulos.Close; qtipos_iva.Close; qseries.open; qdestinos.open; qclientes.open; qalbaranes.open; qalbaranes2.open; qalbaranesdetalle.open; qalbaranesdetalle2.open; facturas.open; facturasdetalle.open; qfacturasiva.open; qformaspago.open; qarticulos.open; qtipos_iva.open; end; procedure Tfacturas.qarticulosBeforeOpen(DataSet: TDataSet); var filtrolocal:string; begin filtrolocal:=''; filtrolocal:=' and (descripcion like('+''''+'%'+filtro+'%'+''''+') or codigo like('+''''+'%'+filtro+'%'+''''+'))'; qarticulos.SQL.Clear; qarticulos.SQL.Add('select * from articulosf where activo=1 and facturable=1'+filtrolocal+' order by descripcion'); end; procedure Tfacturas.TabSheet4Enter(Sender: TObject); begin facturas.Close; facturas.SQL.Clear; facturas.SQL.Add('select * from facturas order by serie desc,id desc'); facturas.Open; listaclientes.Close; listadestinos.Close; listaclientes.Open; listadestinos.Open; end; end. ======================================== FICHERO: ffacturas_PORTATIL_ago.-06-111832-2020_Conflict.pas ======================================== unit ffacturas; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.DBCtrls, Vcl.Mask, Vcl.ExtCtrls, Vcl.ComCtrls, Data.DB,math, ZAbstractRODataset, ZAbstractDataset, ZDataset, frxClass, frxDBSet,datos, ComObj, Excel2000; type Tfacturas = class(TForm) PageControl1: TPageControl; TabSheet1: TTabSheet; Panel1: TPanel; Panel4: TPanel; Button1: TButton; Button2: TButton; Button5: TButton; Button6: TButton; Panel2: TPanel; Label6: TLabel; Label7: TLabel; DBText3: TDBText; DBText4: TDBText; DBText5: TDBText; DBText6: TDBText; DBText7: TDBText; DBText8: TDBText; DBText9: TDBText; DBText10: TDBText; DBText11: TDBText; DBText12: TDBText; DBText13: TDBText; DBText14: TDBText; DBText15: TDBText; Panel3: TPanel; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label15: TLabel; DBEdit1: TDBEdit; DBLookupComboBox2: TDBLookupComboBox; DBLookupComboBox3: TDBLookupComboBox; DBEdit2: TDBEdit; DBCheckBox1: TDBCheckBox; DBMemo1: TDBMemo; DBMemo2: TDBMemo; Panel5: TPanel; Label8: TLabel; Label9: TLabel; Label10: TLabel; Label11: TLabel; Label12: TLabel; Label13: TLabel; Label14: TLabel; Panel6: TPanel; DBGrid1: TDBGrid; DBEdit3: TDBEdit; DBEdit4: TDBEdit; DBEdit5: TDBEdit; DBEdit6: TDBEdit; DBEdit7: TDBEdit; DBEdit8: TDBEdit; DBEdit9: TDBEdit; DBGrid2: TDBGrid; Panel7: TPanel; Button4: TButton; TabSheet2: TTabSheet; DBGrid3: TDBGrid; PageControl2: TPageControl; TabSheet3: TTabSheet; Panel8: TPanel; Panel9: TPanel; btfcancelar: TButton; btfmodificar: TButton; btfborrar: TButton; btfnuevo: TButton; btfguardar: TButton; btfimprimir: TButton; btfimportar: TButton; btfsiguiente: TButton; btfanterior: TButton; Panel10: TPanel; Label16: TLabel; Label17: TLabel; DBText1: TDBText; DBText2: TDBText; DBText16: TDBText; DBText17: TDBText; DBText18: TDBText; DBText19: TDBText; DBText20: TDBText; DBText21: TDBText; DBText22: TDBText; DBText23: TDBText; DBText24: TDBText; DBText25: TDBText; DBText26: TDBText; paneldatos: TPanel; Label18: TLabel; Label19: TLabel; Label20: TLabel; Label21: TLabel; Label22: TLabel; Label23: TLabel; comboseries: TDBLookupComboBox; DBEdit10: TDBEdit; comboclientes: TDBLookupComboBox; combodestinos: TDBLookupComboBox; DBEdit11: TDBEdit; DBMemo4: TDBMemo; Panel12: TPanel; Label24: TLabel; Label25: TLabel; Label26: TLabel; Label27: TLabel; Label28: TLabel; Label29: TLabel; Label30: TLabel; Panel13: TPanel; DBGrid4: TDBGrid; DBEdit12: TDBEdit; DBEdit13: TDBEdit; DBEdit14: TDBEdit; DBEdit15: TDBEdit; DBEdit16: TDBEdit; DBEdit17: TDBEdit; DBEdit18: TDBEdit; DBGrid5: TDBGrid; Panel14: TPanel; Button16: TButton; TabSheet4: TTabSheet; DBGrid6: TDBGrid; infdetallefactura: TfrxDBDataset; inffactura: TfrxDBDataset; inffacturaivas: TfrxDBDataset; informe: TfrxReport; dsfacturas: TDataSource; facturas: TZQuery; dsfacturasdetalle: TDataSource; facturasdetalle: TZQuery; dsqseries: TDataSource; dsqclientes: TDataSource; qclientes: TZQuery; qseries: TZQuery; dsqdestinos: TDataSource; qdestinos: TZQuery; qdestinoscodigo: TWideStringField; qdestinosidcliente: TIntegerField; qdestinosidempresa: TIntegerField; qdestinosdescripcion: TWideStringField; qdestinosseleccionado: TIntegerField; qdestinosactivo: TIntegerField; qdestinosdireccion: TWideStringField; qdestinospoblacion: TWideStringField; qdestinoscodpost: TWideStringField; qdestinosprovincia: TWideStringField; qdestinospais: TWideStringField; dsqfacturasiva: TDataSource; qfacturasiva: TZQuery; qalbaranes: TZQuery; qalbaranesdetalle: TZQuery; dsqalbaranes: TDataSource; dsqalbaranesdetalle: TDataSource; facturasid: TIntegerField; facturasidempresa: TIntegerField; facturasidcliente: TIntegerField; facturasiddestino: TWideStringField; facturasnif: TWideStringField; facturasdireccion: TWideStringField; facturaspoblacion: TWideStringField; facturasprovincia: TWideStringField; facturascodpost: TWideStringField; facturasfecha: TDateField; facturasreferencia: TWideStringField; facturastelefono: TWideStringField; facturasnomcliente: TWideStringField; facturaspaiscliente: TWideStringField; facturasnomdestino: TWideStringField; facturasdirecciondestino: TWideStringField; facturaspoblaciondestino: TWideStringField; facturascodpostdestino: TWideStringField; facturasprovinciadestino: TWideStringField; facturaspaisdestino: TWideStringField; facturasneto: TFloatField; facturastotal: TFloatField; facturasdocumento: TWideStringField; facturasdescuento_lin: TFloatField; facturasdescuento_com: TFloatField; facturasdescuento_pp: TFloatField; facturasdescuento_total: TFloatField; facturastotaliva: TFloatField; facturasobservaciones: TWideStringField; facturasdetalleid: TIntegerField; facturasdetalleidempresa: TIntegerField; facturasdetalleidfactura: TIntegerField; facturasdetalleidarticulo: TWideStringField; facturasdetalledescripcion: TWideStringField; facturasdetallecal: TWideStringField; facturasdetallelote: TWideStringField; facturasdetallecantidad: TFloatField; facturasdetalleprecio: TFloatField; facturasdetalledescuento: TFloatField; facturasdetalletotaldescuento: TFloatField; facturasdetallebase: TFloatField; facturasdetalletipoiva: TFloatField; facturasdetalleiva: TFloatField; facturasdetalletotal: TFloatField; qserieside: TIntegerField; qseriesid: TWideStringField; qseriesfechainicio: TDateField; qseriesfechafin: TDateField; qseriesnum_pedcliente: TIntegerField; qseriesnum_albaran: TIntegerField; qseriesnum_factura: TIntegerField; qseriesnum_expedicion: TIntegerField; qseriesnum_pedproveedor: TIntegerField; qclientesid: TIntegerField; qclientesIdempresa: TIntegerField; qclientesnif: TWideStringField; qclientesnombre: TWideStringField; qclientesnombre_corto: TWideStringField; qclientesdireccion: TWideStringField; qclientespoblacion: TWideStringField; qclientescodpost: TWideStringField; qclientesprovincia: TWideStringField; qclientestelefono: TWideStringField; qclientestelefono2: TWideStringField; qclientesmovil: TWideStringField; qclientesemail: TWideStringField; qclientespersonacontacto: TWideStringField; qclientescodigomercado: TIntegerField; qclientesactivo: TIntegerField; qclientesobservaciones: TWideStringField; qclientesccontable: TIntegerField; qclientesdescuento: TFloatField; qclientespais: TWideStringField; qalbaranesid: TIntegerField; qalbaranesidempresa: TIntegerField; qalbaranesidcliente: TIntegerField; qalbaranesiddestino: TWideStringField; qalbaranesnif: TWideStringField; qalbaranesdireccion: TWideStringField; qalbaranespoblacion: TWideStringField; qalbaranesprovincia: TWideStringField; qalbaranescodpost: TWideStringField; qalbaranesfecha: TDateField; qalbaranesreferencia: TWideStringField; qalbaranestelefono: TWideStringField; qalbaranesnomcliente: TWideStringField; qalbaranespaiscliente: TWideStringField; qalbaranesnomdestino: TWideStringField; qalbaranesdirecciondestino: TWideStringField; qalbaranespoblaciondestino: TWideStringField; qalbaranescodpostdestino: TWideStringField; qalbaranesprovinciadestino: TWideStringField; qalbaranespaisdestino: TWideStringField; qalbaranesneto: TFloatField; qalbaranestotal: TFloatField; qalbaranesfacturado: TIntegerField; qalbaranesdocumento: TWideStringField; qalbaranesdescuento_lin: TFloatField; qalbaranesdescuento_com: TFloatField; qalbaranesdescuento_pp: TFloatField; qalbaranesdescuento_total: TFloatField; qalbaranestotaliva: TFloatField; qalbaranesobservaciones: TWideStringField; qalbaranesidfactura: TIntegerField; qalbaranesdetalleid: TIntegerField; qalbaranesdetalleidempresa: TIntegerField; qalbaranesdetalleidalbaran: TIntegerField; qalbaranesdetalleidarticulo: TWideStringField; qalbaranesdetalledescripcion: TWideStringField; qalbaranesdetallecal: TWideStringField; qalbaranesdetallelote: TWideStringField; qalbaranesdetallecantidad: TFloatField; qalbaranesdetalleprecio: TFloatField; qalbaranesdetalledescuento: TFloatField; qalbaranesdetalletotaldescuento: TFloatField; qalbaranesdetallebase: TFloatField; qalbaranesdetalletipoiva: TFloatField; qalbaranesdetalleiva: TFloatField; qalbaranesdetalletotal: TFloatField; dsqalbaranes2: TDataSource; qalbaranes2: TZQuery; dsqalbaranesdetalle2: TDataSource; qalbaranesdetalle2: TZQuery; qfacturasivaidfactura: TIntegerField; qfacturasivaide: TIntegerField; qfacturasivabase: TFloatField; qfacturasivatipo: TFloatField; qfacturasivaiva: TFloatField; qalbaranes2id: TIntegerField; qalbaranes2idempresa: TIntegerField; qalbaranes2idcliente: TIntegerField; qalbaranes2iddestino: TWideStringField; qalbaranes2nif: TWideStringField; qalbaranes2direccion: TWideStringField; qalbaranes2poblacion: TWideStringField; qalbaranes2provincia: TWideStringField; qalbaranes2codpost: TWideStringField; qalbaranes2fecha: TDateField; qalbaranes2referencia: TWideStringField; qalbaranes2telefono: TWideStringField; qalbaranes2nomcliente: TWideStringField; qalbaranes2paiscliente: TWideStringField; qalbaranes2nomdestino: TWideStringField; qalbaranes2direcciondestino: TWideStringField; qalbaranes2poblaciondestino: TWideStringField; qalbaranes2codpostdestino: TWideStringField; qalbaranes2provinciadestino: TWideStringField; qalbaranes2paisdestino: TWideStringField; qalbaranes2neto: TFloatField; qalbaranes2total: TFloatField; qalbaranes2facturado: TIntegerField; qalbaranes2documento: TWideStringField; qalbaranes2descuento_lin: TFloatField; qalbaranes2descuento_com: TFloatField; qalbaranes2descuento_pp: TFloatField; qalbaranes2descuento_total: TFloatField; qalbaranes2totaliva: TFloatField; qalbaranes2observaciones: TWideStringField; qalbaranes2idfactura: TIntegerField; qalbaranesdetalle2id: TIntegerField; qalbaranesdetalle2idempresa: TIntegerField; qalbaranesdetalle2idalbaran: TIntegerField; qalbaranesdetalle2idarticulo: TWideStringField; qalbaranesdetalle2descripcion: TWideStringField; qalbaranesdetalle2cal: TWideStringField; qalbaranesdetalle2lote: TWideStringField; qalbaranesdetalle2cantidad: TFloatField; qalbaranesdetalle2precio: TFloatField; qalbaranesdetalle2descuento: TFloatField; qalbaranesdetalle2totaldescuento: TFloatField; qalbaranesdetalle2base: TFloatField; qalbaranesdetalle2tipoiva: TFloatField; qalbaranesdetalle2iva: TFloatField; qalbaranesdetalle2total: TFloatField; qaux: TZQuery; facturasserie: TWideStringField; facturasdetalleserie: TWideStringField; qalbaranes2serie: TWideStringField; qalbaranesdetalle2serie: TWideStringField; qalbaranesserie: TWideStringField; qalbaranesdetalleserie: TWideStringField; qfacturasivaserie: TWideStringField; qseriesimp_albaran: TWideStringField; qseriesimp_factura: TWideStringField; facturasbultos: TFloatField; facturaskilos: TFloatField; facturasidformapago: TIntegerField; Label31: TLabel; comboformapago: TDBLookupComboBox; qformaspago: TZQuery; dsqformaspago: TDataSource; qformaspagoide: TIntegerField; qformaspagoid: TIntegerField; qformaspagocodigo: TWideStringField; qformaspagodescripcion: TWideStringField; qformaspagodias: TIntegerField; qclientesidformapago: TIntegerField; qalbaranesdetallebultos: TFloatField; qalbaranesdetalle2bultos: TFloatField; dsqarticulos: TDataSource; qarticulos: TZReadOnlyQuery; qtipos_iva: TZReadOnlyQuery; DataSource1: TDataSource; qtipos_ivaid: TIntegerField; qtipos_ivadescripcion: TWideStringField; qtipos_ivatipo: TIntegerField; qtipos_ivatipo_req: TFloatField; qarticulosidempresa: TIntegerField; qarticulosid: TIntegerField; qarticuloscodigo: TWideStringField; qarticulosdescripcion: TWideStringField; qarticulosfamilia: TIntegerField; qarticulosprovhab: TIntegerField; qarticulostipoiva: TIntegerField; qarticulospreciocoste: TFloatField; qarticulosmargen: TFloatField; qarticulosbeneficio: TFloatField; qarticulospvp: TFloatField; qarticulosstock: TFloatField; qarticulosult_preciocompra: TFloatField; qarticulosfacturable: TIntegerField; qarticulosobservaciones: TWideStringField; qarticulosimagen: TBlobField; qarticulosactivo: TIntegerField; qarticulosvalor_almacen: TFloatField; qarticulosstock_minimo: TFloatField; qarticulosavisar_stock: TIntegerField; qarticuloscontrolar_traza: TIntegerField; qarticulospeso: TFloatField; listaimpresion: TComboBox; facturasdetallebultos: TFloatField; Panel11: TPanel; Button3: TButton; gridfacturasaexcel: TDBGrid; qfacturasclientes: TZReadOnlyQuery; qfacturasclientesserie: TWideStringField; qfacturasclientesid: TIntegerField; qfacturasclientesidempresa: TIntegerField; qfacturasclientesidcliente: TIntegerField; qfacturasclientesiddestino: TWideStringField; qfacturasclientesnif: TWideStringField; qfacturasclientesdireccion: TWideStringField; qfacturasclientespoblacion: TWideStringField; qfacturasclientesprovincia: TWideStringField; qfacturasclientescodpost: TWideStringField; qfacturasclientesfecha: TDateField; qfacturasclientesreferencia: TWideStringField; qfacturasclientestelefono: TWideStringField; qfacturasclientesnomcliente: TWideStringField; qfacturasclientespaiscliente: TWideStringField; qfacturasclientesnomdestino: TWideStringField; qfacturasclientesdirecciondestino: TWideStringField; qfacturasclientespoblaciondestino: TWideStringField; qfacturasclientescodpostdestino: TWideStringField; qfacturasclientesprovinciadestino: TWideStringField; qfacturasclientespaisdestino: TWideStringField; qfacturasclientesneto: TFloatField; qfacturasclientestotal: TFloatField; qfacturasclientesfacturado: TIntegerField; qfacturasclientesdocumento: TWideStringField; qfacturasclientesdescuento_lin: TFloatField; qfacturasclientesdescuento_com: TFloatField; qfacturasclientesdescuento_pp: TFloatField; qfacturasclientesdescuento_total: TFloatField; qfacturasclientestotaliva: TFloatField; qfacturasclientesobservaciones: TWideStringField; qfacturasclientesbultos: TFloatField; qfacturasclienteskilos: TFloatField; qfacturasclientesidformapago: TIntegerField; qfacturasclientesserie_1: TWideStringField; qfacturasclientesidfactura: TIntegerField; qfacturasclienteside: TIntegerField; qfacturasclientesbase: TFloatField; qfacturasclientestipo: TFloatField; qfacturasclientesiva: TFloatField; dsqfacturasclientes: TDataSource; SaveDialog1: TSaveDialog; qclientesexento_iva: TIntegerField; facturascobrado: TIntegerField; DBCheckBox2: TDBCheckBox; Panel15: TPanel; listaclientes: TZQuery; listaclientesnif: TWideStringField; listaclientesnomcliente: TWideStringField; combolistcliente: TDBLookupComboBox; combolistdestinos: TDBLookupComboBox; listadestinos: TZQuery; dslistadestinos: TDataSource; dslistacliente: TDataSource; listadestinosnomdestino: TWideStringField; Button7: TButton; Label32: TLabel; Label33: TLabel; Label34: TLabel; Label35: TLabel; fdesde: TDateTimePicker; fhasta: TDateTimePicker; procedure dsfacturasStateChange(Sender: TObject); procedure dsfacturasDataChange(Sender: TObject; Field: TField); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure btfimportarClick(Sender: TObject); procedure btfnuevoClick(Sender: TObject); procedure comboseriesCloseUp(Sender: TObject); procedure comboseriesEnter(Sender: TObject); procedure comboclientesEnter(Sender: TObject); procedure comboclientesCloseUp(Sender: TObject); procedure FormShow(Sender: TObject); procedure combodestinosEnter(Sender: TObject); procedure combodestinosCloseUp(Sender: TObject); procedure btfborrarClick(Sender: TObject); procedure btfmodificarClick(Sender: TObject); procedure btfguardarClick(Sender: TObject); procedure facturasdetalleBeforePost(DataSet: TDataSet); procedure facturasdetalleAfterPost(DataSet: TDataSet); procedure Button16Click(Sender: TObject); procedure DBGrid6TitleClick(Column: TColumn); procedure btfcancelarClick(Sender: TObject); procedure btfanteriorClick(Sender: TObject); procedure btfsiguienteClick(Sender: TObject); procedure btfimprimirClick(Sender: TObject); procedure DBGrid5KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DBGrid5ColExit(Sender: TObject); procedure qarticulosBeforeOpen(DataSet: TDataSet); procedure Button3Click(Sender: TObject); procedure TabSheet4Show(Sender: TObject); private { Private declarations } public { Public declarations } procedure ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar = nil); end; var facturas: Tfacturas; filtro,iddetalle:string; implementation {$R *.dfm} uses fselectalbaranes,fbuscararticulos; procedure TFacturas.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 Tfacturas.btfcancelarClick(Sender: TObject); begin facturas.Cancel; paneldatos.Enabled:=false; end; procedure Tfacturas.btfguardarClick(Sender: TObject); var empresa,serie:string; begin empresa:=facturasidempresa.AsString; serie:=facturasserie.AsString; qaux.sql.clear; facturas.Post; qaux.sql.clear; qaux.SQL.Add('select max(id) from facturas where idempresa='+empresa+' and serie='+''''+serie+''''); qaux.Open; qseries.edit; qseriesnum_factura.Value:=qaux.Fields[0].AsInteger+1; qseries.Post; facturasdetalle.open; qfacturasiva.open; facturas.Refresh; facturasdetalle.Refresh; qfacturasiva.Refresh; paneldatos.Enabled:=false; end; procedure Tfacturas.btfimportarClick(Sender: TObject); begin seleccionaralbaranes := Tseleccionaralbaranes.Create(nil); try seleccionaralbaranes.showmodal(); finally seleccionaralbaranes.Free; end; facturas.Refresh; qfacturasiva.refresh; end; procedure Tfacturas.btfimprimirClick(Sender: TObject); var filtro,documento,formapago:string; desg_ivas,tipo,base,iva:string; x:integer; fecha:tdate; begin if listaimpresion.ItemIndex=0 then begin facturasdetalle.Close; facturasdetalle.SQL.Clear; facturasdetalle.SQL.Add('select idempresa,idfactura,sum(cantidad) as cantidad,precio,descuento,sum(base) as base,descripcion,cal,sum(bultos) as bultos,tipoiva,sum(iva) as iva,sum(total) as total,id,'+''''''+' as idarticulo,sum(totaldescuento) as totaldescuento,'+''''''+' as lote,serie '); facturasdetalle.SQL.Add(' from facturas_detalles group by idempresa,idfactura,descripcion,cal,precio'); facturasdetalle.open; end; if listaimpresion.ItemIndex=1 then begin facturasdetalle.Close; facturasdetalle.SQL.Clear; facturasdetalle.SQL.Add('select * from facturas_detalles'); facturasdetalle.open; end; filtro:='id='; filtro:=filtro+facturasid.asstring; filtro:=filtro+' and serie='+''''+ facturasserie.AsString+''''; documento:=qseriesimp_factura.asstring; facturas.Filter:=filtro; facturas.filtered:=true; fecha:=facturasfecha.AsDateTime; fecha:=fecha+qformaspagodias.asinteger; formapago:='FORMA DE PAGO: '+qformaspagodescripcion.AsString+' FECHA DE VENCIMIENTO EL '+DATETOSTR(FECHA); qfacturasiva.First; desg_ivas:=''; while not qfacturasiva.Eof do begin if qfacturasivabase.AsFloat>0 then begin tipo:=format('%2d',[qfacturasivatipo.asinteger]); base:=format('%10.2f',[qfacturasivabase.Asfloat]); iva:=format('%8.2f',[qfacturasivaiva.asfloat]); desg_ivas:=desg_ivas+tipo+base+iva+' '; end; qfacturasiva.Next; end; inffactura.Datasource:=dsfacturas; infdetallefactura.Datasource:=dsfacturasdetalle; inffacturaivas.Datasource:=dsqfacturasiva; informe.Report.Clear; informe.LoadFromFile('c:\agrigest\informes\'+documento+'.fr3'); informe.Variables.Variables['FORMAPAGO']:=QUOTEDSTR(formapago); informe.Variables.Variables['DESGIVAS']:=QUOTEDSTR(desg_ivas); informe.ShowReport(); informe.Clear; // informe.Variables.Variables['TITULO']:=QUOTEDSTR(panel100.Caption); facturas.filtered:=false; end; procedure Tfacturas.btfmodificarClick(Sender: TObject); begin paneldatos.Enabled:=true; facturas.Edit; qclientes.Close; qclientes.SQL.Clear; qclientes.SQL.Add('select * from clientes order by nombre'); qclientes.open; qdestinos.Close; qdestinos.SQL.Clear; qdestinos.SQL.Add('select * from clientes_destinos order by descripcion'); qdestinos.open; end; procedure Tfacturas.btfanteriorClick(Sender: TObject); begin facturas.Next; end; procedure Tfacturas.btfborrarClick(Sender: TObject); begin facturasdetalle.open; if facturas.recordcount>0 then begin facturas.Delete; facturasdetalle.Refresh; qalbaranes.Refresh; qalbaranes2.Refresh; qalbaranesdetalle.Refresh; qalbaranesdetalle2.Refresh; qfacturasiva.refresh; end; end; procedure Tfacturas.btfnuevoClick(Sender: TObject); begin paneldatos.Enabled:=true; comboseries.SetFocus; comboseries.KeyValue:=qseriesid.Asstring; //fechaalbaran.Date:=date; facturas.Append; qclientes.Close; qclientes.SQL.Clear; qclientes.SQL.Add('select * from clientes order by nombre'); qclientes.open; qdestinos.Close; qdestinos.SQL.Clear; qdestinos.SQL.Add('select * from clientes_destinos order by descripcion'); qdestinos.open; facturasdetalle.Close; qfacturasiva.close; facturasfecha.Value:=date; end; procedure Tfacturas.btfsiguienteClick(Sender: TObject); begin facturas.Prior; end; procedure Tfacturas.Button16Click(Sender: TObject); var serie,id:string; begin if facturasdetalle.recordcount>0 then begin serie:=facturasserie.AsString; id:=facturasid.AsString; facturasdetalle.Delete; //1 facturas.Refresh; // facturas.Locate('serie;id',vararrayof([serie,id]),[locaseinsensitive,lopartialkey]); qfacturasiva.Refresh; end; end; procedure Tfacturas.Button3Click(Sender: TObject); var archivo:string; begin qfacturasclientes.Close; qfacturasclientes.SQL.Clear; qfacturasclientes.SQL.Add('select * from facturas f,facturas_iva fi where f.idempresa=fi.ide and f.serie=fi.serie and f.id=fi.idfactura order by f.serie,fecha desc,f.id desc'); qfacturasclientes.open; savedialog1.FileName:='FACTURAS CLIENTES.xls'; savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'facturas',gridfacturasaexcel); finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure Tfacturas.comboseriesCloseUp(Sender: TObject); begin facturasid.value:=qseriesnum_factura.AsInteger; end; procedure Tfacturas.comboseriesEnter(Sender: TObject); begin comboseries.DropDown; end; procedure Tfacturas.DBGrid5ColExit(Sender: TObject); begin if facturasdetalle.State in [dsedit,dsinsert] then begin if dbgrid5.SelectedIndex=0 then begin filtro:=facturasdetalleidarticulo.asstring; qarticulos.Close; qarticulos.Open; if qarticulos.RecordCount>0 then begin qtipos_iva.Open; facturasdetalledescripcion.value:=qarticulosdescripcion.AsString; if qclientesexento_iva.AsInteger=0 then facturasdetalletipoiva.value:=qtipos_ivatipo.Asfloat else facturasdetalletipoiva.value:=0; qtipos_ivatipo.Asfloat; end; end; end; end; procedure Tfacturas.DBGrid5KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (key=115) then begin buscararticulos := Tbuscararticulos.Create(nil); try fbuscararticulos.padre:=facturas.Name; fbuscararticulos.filtro:=facturasdetalleidarticulo.AsString; buscararticulos.Edit1.Text:=facturasdetalleidarticulo.AsString; buscararticulos.showmodal(); finally if facturasdetalle.State in [dsbrowse] then facturasdetalle.Edit; facturasdetalleidarticulo.Value:=buscararticulos.qarticuloscodigo.AsString; facturasdetalledescripcion.value:=buscararticulos.qarticulosdescripcion.AsString; facturasdetalletipoiva.value:=buscararticulos.qtipos_ivatipo.Asfloat; buscararticulos.Free; end; end; end; procedure Tfacturas.DBGrid6TitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=facturas.SortType; facturas.SortedFields:=Column.FieldName; If st = stAscending then facturas.SortType:=stDescending else facturas.SortType:=stAscending; dsfacturas.DataSet.First; end; procedure Tfacturas.comboclientesCloseUp(Sender: TObject); begin facturasnomcliente.value:=qclientesnombre.Asstring; facturasnif.value:=qclientesnif.Asstring; facturasdireccion.value:=qclientesdireccion.Asstring; facturasprovincia.value:=qclientesprovincia.Asstring; facturaspoblacion.Value:=qclientespoblacion.AsString; facturascodpost.value:=qclientescodpost.Asstring; facturaspaiscliente.value:=qclientespais.Asstring; facturasidformapago.Value:=qclientesidformapago.asinteger; end; procedure Tfacturas.comboclientesEnter(Sender: TObject); begin comboclientes.dropdown; end; procedure Tfacturas.combodestinosCloseUp(Sender: TObject); begin facturasnomdestino.value:=qdestinosdescripcion.Asstring; facturasdirecciondestino.value:=qdestinosdireccion.Asstring; facturasprovinciadestino.value:=qdestinosprovincia.Asstring; facturaspoblaciondestino.Value:=qdestinospoblacion.AsString; facturascodpostdestino.value:=qdestinoscodpost.Asstring; facturaspaisdestino.value:=qdestinospais.Asstring; end; procedure Tfacturas.combodestinosEnter(Sender: TObject); begin combodestinos.DropDown; end; procedure Tfacturas.dsfacturasDataChange(Sender: TObject; Field: TField); begin if (facturas.State in [dsbrowse]) and (facturas.recordcount>0) then begin qalbaranes2.Close; qalbaranes2.SQL.Clear; qalbaranes2.SQL.Add('select * from albaranes where'); qalbaranes2.SQL.Add(' idfactura='+facturasid.AsString+' and serie='+''''+facturasserie.AsString+''''+' and idempresa='+facturasidempresa.AsString+' order by serie desc, id desc'); qalbaranes2.Open; qclientes.Close; qclientes.SQL.Clear; qclientes.SQL.Add('select * from clientes where idempresa='+facturasidempresa.asstring+' and id='+facturasidcliente.asstring); qclientes.open; qdestinos.Close; qdestinos.SQL.Clear; qdestinos.SQL.Add('select * from clientes_destinos where idempresa='+facturasidempresa.asstring+' and idcliente='+facturasidcliente.asstring+' and codigo='+''''+facturasiddestino.asstring+''''); qdestinos.open; end; end; procedure Tfacturas.dsfacturasStateChange(Sender: TObject); begin if facturas.State in [dsedit,dsinsert] then begin btfnuevo.Enabled:=false; btfmodificar.Enabled:=false; btfborrar.Enabled:=false; btfcancelar.Enabled:=true; btfguardar.Enabled:=true; qdestinos.Close; qclientes.Close; qdestinos.LinkedFields:='Idempresa;idcliente'; qdestinos.MasterFields:='Idempresa;id'; qdestinos.Mastersource:=dsqclientes; qclientes.open; qdestinos.Open; end else begin btfnuevo.Enabled:=true; btfmodificar.Enabled:=true; btfborrar.Enabled:=true; btfcancelar.Enabled:=false; btfguardar.Enabled:=false; qclientes.Close; qdestinos.Close; qdestinos.LinkedFields:=''; qdestinos.MasterFields:=''; qdestinos.Mastersource:=nil; qclientes.open; qdestinos.Open; end; end; procedure Tfacturas.facturasdetalleAfterPost(DataSet: TDataSet); var serie,id:string; begin serie:=facturasserie.AsString; id:=facturasid.AsString; facturas.Refresh; facturas.Locate('serie;id',vararrayof([serie,id]),[locaseinsensitive]); qfacturasiva.Refresh; if iddetalle<>'' then facturasdetalle.Locate('id',iddetalle,[locaseinsensitive]) else facturasdetalle.Last; end; procedure Tfacturas.facturasdetalleBeforePost(DataSet: TDataSet); var iva,descuento:real; begin if facturasdetalletipoiva.AsString='' then facturasdetalletipoiva.Value:=0; if facturasdetalledescuento.AsString='' then facturasdetalledescuento.Value:=0; facturasdetalleserie.Value:=facturasserie.Asstring; facturasdetallebase.Value:=roundto(facturasdetalleprecio.AsFloat*facturasdetallecantidad.AsFloat,-2); descuento:=roundto(facturasdetallebase.AsFloat*(facturasdetalledescuento.AsFloat/100),-2); facturasdetalletotaldescuento.value:=descuento; facturasdetalletotal.Value:=roundto(facturasdetallebase.Asfloat-descuento,-2); iva:=roundto(facturasdetalletotal.AsFloat*(facturasdetalletipoiva.AsFloat/100),-2); facturasdetalleiva.Value:=iva; if facturasdetalle.State in [dsedit] then iddetalle:=facturasdetalleid.AsString else iddetalle:=''; end; procedure Tfacturas.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tfacturas.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is tdbgrid) then begin key:=','; end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tfacturas.FormShow(Sender: TObject); begin dm.tempresa.Open; qseries.Close; qdestinos.Close; qclientes.Close; qalbaranes.Close; qalbaranes2.close; qalbaranesdetalle.Close; qalbaranesdetalle2.Close; facturas.Close; facturasdetalle.Close; qfacturasiva.Close; qformaspago.Close; qarticulos.Close; qtipos_iva.Close; qseries.open; qdestinos.open; qclientes.open; qalbaranes.open; qalbaranes2.open; qalbaranesdetalle.open; qalbaranesdetalle2.open; facturas.open; facturasdetalle.open; qfacturasiva.open; qformaspago.open; qarticulos.open; qtipos_iva.open; end; procedure Tfacturas.qarticulosBeforeOpen(DataSet: TDataSet); var filtrolocal:string; begin filtrolocal:=''; filtrolocal:=' and (descripcion like('+''''+'%'+filtro+'%'+''''+') or codigo like('+''''+'%'+filtro+'%'+''''+'))'; qarticulos.SQL.Clear; qarticulos.SQL.Add('select * from articulosf where activo=1 and facturable=1'+filtrolocal+' order by descripcion'); end; procedure Tfacturas.TabSheet4Show(Sender: TObject); begin fdesde.Date:=date(); fhasta.Date:=date(); facturas.Close; facturas.SQL.Clear; facturas.SQL.Add('select * from facturas order by serie desc,id desc'); facturas.Open; listaclientes.Close; listadestinos.Close; listaclientes.Open; listadestinos.Open; end; end. ======================================== FICHERO: fformaspago.pas ======================================== unit formaspago; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls; type TForm2 = class(TForm) Panel13: TPanel; Panel17: TPanel; DBGrid3: TDBGrid; Panel7: TPanel; btAcancelar: TButton; btAmodificar: TButton; btAborrar: TButton; btAnuevo: TButton; btAguardar: TButton; qaux: TZQuery; qformaspago: TZQuery; qformaspagoide: TIntegerField; qformaspagoid: TIntegerField; qformaspagocodigo: TWideStringField; qformaspagodescripcion: TWideStringField; qformaspagodias: TIntegerField; dsqformaspago: TDataSource; private { Private declarations } public { Public declarations } end; var Form2: TForm2; implementation {$R *.dfm} end. ======================================== FICHERO: fformularios.pas ======================================== unit fformularios; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,Vcl.StdCtrls, Vcl.DBCtrls, Vcl.Mask, Vcl.ComCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls,datos, ZAbstractDataset, ZDataset, Data.DB, ZAbstractRODataset, ZAbstractTable,Excel2000, ComObj; type Tformularios = class(TForm) qformularios: TZQuery; DBGrid1: TDBGrid; dsqformularios: TDataSource; qformulariosid: TIntegerField; qformulariosformulario: TWideStringField; qformulariosdescripcion: TWideStringField; qformulariosaplicar_a: TWideStringField; qformularioside: TIntegerField; Panel7: TPanel; btAcancelar: TButton; btAmodificar: TButton; btAborrar: TButton; btAnuevo: TButton; btAguardar: TButton; qaux: TZQuery; gcrpagado: TDBCheckBox; qformulariospordefecto: TIntegerField; procedure btAnuevoClick(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure btAmodificarClick(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); procedure dsqformulariosStateChange(Sender: TObject); procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBGrid1CellClick(Column: TColumn); procedure qformulariosBeforePost(DataSet: TDataSet); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } procedure AppMessage(var Msg: Tmsg; var Handled:Boolean); end; var formularios: Tformularios; implementation {$R *.dfm} procedure Tformularios.AppMessage(var Msg: TMSg; Var Handled:Boolean); var actual : TWincontrol; begin if Msg.message = WM_KEYDOWN then begin // esto es para controlar que con la flecha abajo se desplegen las // listas if Msg.wParam = VK_DOWN then begin Actual := Screen.ActiveControl; if Actual is TDBLookupComboBox then if not TDBLookupComboBox(Screen.ActiveForm.ActiveControl).listVisible then TDBLookupComboBox(Screen.ActiveForm.ActiveControl).DropDown; // si utilizas las RX { if Actual is TRxDBLookupCombo then if not TRxDBLookupCombo(Screen.ActiveForm.ActiveControl).listVisible then TRxDBLookupCombo(Screen.ActiveForm.ActiveControl).DropDown; } if Actual is TComboBox then SendMessage(TComboBox(Screen.ActiveForm.ActiveControl).Handle,CB_SHOWDROPDOWN,-1,0); if (Actual is TCustomEdit) then Msg.wParam := VK_TAB; // se pueden añadir mas controles.... end; // y aqui es el control del intro. if Msg.wParam = VK_RETURN THEN begin Actual := Screen.ActiveControl; // para los edit. if (Actual is TCustomEdit) and not (Actual is TCustomMemo) then Msg.wParam := VK_TAB; // para los memo. Con ctrl + enter se salta de linea dentro del // memo, si solo es intro salta al siguiente control if (Actual is TCustomMemo) and (HiWord(GetKeyState(VK_CONTROL)) = 0)then Msg.wParam := VK_TAB; // para los lookup if Actual is TDBLookupComboBox then if not TDBLookupComboBox(Actual).listVisible then Msg.wParam := VK_TAB; // Si utilizas las RX { if Actual is TRxDBLookupCombo then if not TRxDBLookupCombo(Actual).listVisible then Msg.wParam := VK_TAB; } // Los combobox if Actual is TCustomComboBox then if not TCustomComboBox(Actual).DroppedDown then Msg.wParam := VK_TAB; // el radiobutton if Actual is TRadioButton then Msg.wParam := VK_TAB; // en el grid if Actual is TDBGrid then if (TDBGrid(Actual).ReadOnly) or (HiWord(GetKeyState(VK_CONTROL)) = 1)then Msg.wParam := VK_TAB; // o esto otro Con Ctrl + intro siguiente celda con // ctrl + shift + intro celda anterior // es complicado pero es por no liar con el intro solo // que siempre pasa de un control a otro. if Actual is TDBGrid then begin if (TDBGrid(Actual).ReadOnly) or (HiWord(GetKeyState(VK_CONTROL)) = 0) then Msg.wParam := VK_TAB else if not(HiWord(GetKeyState(VK_SHIFT)) = 0) then begin if TDBGrid(Actual).selectedindex > 0 then { increment the field } TDBGrid(Actual).selectedindex := TDBGrid(Actual).selectedindex -1 else TDBGrid(Actual).selectedindex := TDBGrid(Actual).fieldcount -1; end else begin if TDBGrid(Actual).selectedindex < (TDBGrid(Actual).fieldcount -1) then { increment the field } TDBGrid(Actual).selectedindex := TDBGrid(Actual).selectedindex +1 else TDBGrid(Actual).selectedindex := 0; end; end; // ListBox if Actual is TCustomListBox then Msg.wParam := VK_TAB; // TabControl // if Actual is TCustomTabControl then // Msg.wParam := VK_TAB; // Aqui se pondrían todos los controles que usamos en la // aplicación y necesitamos cambiar el tab por intro. // de esta forma te despreocupas de cuantos añades y es más // limpio el código end; end; end; procedure Tformularios.btAborrarClick(Sender: TObject); begin qformularios.Delete; end; procedure Tformularios.btAcancelarClick(Sender: TObject); begin qformularios.cancel; end; procedure Tformularios.btAguardarClick(Sender: TObject); begin qformularios.post; end; procedure Tformularios.btAmodificarClick(Sender: TObject); begin qformularios.edit; end; procedure Tformularios.btAnuevoClick(Sender: TObject); begin qaux.sql.clear; qaux.SQL.Add('select max(id)+1 from formatosimpresion'); qaux.Open; qformularios.append; dbgrid1.setfocus; qformulariosid.Value:=qaux.Fields[0].AsInteger; end; procedure Tformularios.DBGrid1CellClick(Column: TColumn); begin if column.Field.FieldName ='pordefecto' then begin if qformulariospordefecto.asinteger=1 then begin qformularios.Edit; qformulariospordefecto.Value:=0; qformularios.Post; dbgrid1.selectedIndex:=1; end else begin qformularios.Edit; qformulariospordefecto.Value:=1; qformularios.Post; qformularios.Refresh; dbgrid1.SelectedIndex:=1; end; end; end; procedure Tformularios.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); const IsChecked : array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED); var DrawState: Integer; DrawRect: TRect; begin if (gdFocused in State) then begin if (Column.Field.FieldName = 'pordefecto') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'pordefecto') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; // DrawState := ISChecked[Column.Field.Asboolean]; DBgrid1.Canvas.FillRect(Rect); DrawFrameControl(DBgrid1.Canvas.Handle, DrawRect, DFC_BUTTON, DrawState); end; end; end; procedure Tformularios.dsqformulariosStateChange(Sender: TObject); begin if qformularios.State in [dsedit,dsinsert] then begin btanuevo.Enabled:=false; btamodificar.Enabled:=false; btaborrar.Enabled:=false; btacancelar.Enabled:=true; btaguardar.Enabled:=true; end else begin btanuevo.Enabled:=true; btamodificar.Enabled:=true; btaborrar.Enabled:=true; btacancelar.Enabled:=false; btaguardar.Enabled:=false; end; end; procedure Tformularios.FormCreate(Sender: TObject); var I: Integer; begin Application.OnMessage := AppMessage; gcrpagado.DataField := 'pagado'; gcrpagado.Visible := False; gcrpagado.SendToBack; gcrpagado.Color := DBGrid1.Color; gcrpagado.Caption := ''; gcrpagado.ValueChecked := '0'; gcrpagado.ValueUnChecked := '1'; end; procedure Tformularios.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tformularios.FormKeyPress(Sender: TObject; var Key: Char); begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tformularios.FormShow(Sender: TObject); begin dm.tempresa.Open; qformularios.Open; end; procedure Tformularios.qformulariosBeforePost(DataSet: TDataSet); begin qformularioside.Value:=dm.tempresaid.asinteger; end; end. ======================================== FICHERO: fgastos.pas ======================================== unit fgastos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ImgList, Vcl.Menus; type TForm1 = class(TForm) private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} end. ======================================== FICHERO: fgenerartratamientos.pas ======================================== unit fgenerartratamientos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, ZAbstractDataset, ZDataset, Data.DB, Vcl.Grids, Vcl.DBGrids, ZAbstractRODataset, Vcl.DBCtrls; type Tgenerartratamientos = class(TForm) Button1: TButton; vfecha: TDateTimePicker; qrecomendaciones: TZReadOnlyQuery; em: TDBGrid; Label1: TLabel; dsqrecomendaciones: TDataSource; qrecomendacionesid: TIntegerField; qrecomendacionesdescripcion: TWideStringField; qrecomendacionesobservaciones: TWideStringField; qrecomendacionesfecha: TDateField; qrecomendacionesvelocidad: TFloatField; qrecomendacionesnum_boquillas: TIntegerField; qrecomendacionestipo_boquilla: TWideStringField; qrecomendacionespresion: TIntegerField; qrecomendacioneslitros_hect: TIntegerField; qrecomendacionesdesc_boquilla: TWideStringField; qrecomendacioneslitros_minuto: TFloatField; qrecomendacionesidparcela: TWideStringField; qrecomendacionesparcela: TWideStringField; qrecomendacionessuperficie: TFloatField; qidtratamiento: TZReadOnlyQuery; qtratamientos: TZQuery; qidtratamientoid: TLargeintField; qrecomendacionesdetalle: TZReadOnlyQuery; qrecomendacionesdetalleide: TIntegerField; qrecomendacionesdetalleidt: TIntegerField; qrecomendacionesdetalleidaf: TIntegerField; qrecomendacionesdetalleidma: TIntegerField; qrecomendacionesdetalledescripcion_af: TWideStringField; qrecomendacionesdetalledescripcion_ma: TWideStringField; qrecomendacionesdetallecantidad_base: TFloatField; qrecomendacionesdetalledosis: TFloatField; qrecomendacionesdetalleunidad_medida: TWideStringField; qrecomendacionesdetalleregistro: TWideStringField; qrecomendacionesdetalleplazo: TIntegerField; qrecomendacionesdetalleficha: TBlobField; qrecomendacionesdetallecantidad_mezcla: TIntegerField; qrecomendacionesdetallecantidad_materia: TFloatField; qrecomendacionesdetalleorden: TIntegerField; qtratamientosdetalle: TZQuery; qtratamientosdetalleide: TIntegerField; qtratamientosdetalleidt: TIntegerField; qtratamientosdetalleidaf: TIntegerField; qtratamientosdetalleidma: TIntegerField; qtratamientosdetalledescripcion_af: TWideStringField; qtratamientosdetalledescripcion_ma: TWideStringField; qtratamientosdetallecantidad_base: TFloatField; qtratamientosdetalledosis: TFloatField; qtratamientosdetalleunidad_medida: TWideStringField; qtratamientosdetalleregistro: TWideStringField; qtratamientosdetalleplazo: TIntegerField; qtratamientosdetalleficha: TBlobField; qtratamientosdetallecantidad_mezcla: TFloatField; qtratamientosdetallecantidad_materia: TFloatField; qtratamientosdetalleen_cuaderno: TIntegerField; qtratamientosdetalleidconsumo: TIntegerField; qtratamientosdetalleorden: TIntegerField; qtratamientosdetalleidentrada: TIntegerField; qtratamientosdetallefecha: TDateField; qtratamientoside: TIntegerField; qtratamientosid: TIntegerField; qtratamientosfecha: TDateField; qtratamientosidcc: TWideStringField; qtratamientosdesc_cc: TWideStringField; qtratamientosresponsable: TWideStringField; qtratamientosidrecomendacion: TIntegerField; qtratamientoscontabilizado: TIntegerField; qtratamientosnif_responsable: TWideStringField; qtratamientosobservaciones: TWideStringField; qtratamientosoperario: TWideStringField; qtratamientosidjustificacion: TIntegerField; qtratamientoscondiciones_metereologicas: TWideStringField; qtratamientoshora_fin: TTimeField; qtratamientostractor: TWideStringField; qtratamientosdeposito: TWideStringField; qtratamientosvelocidad: TFloatField; qtratamientospresion: TIntegerField; qtratamientosboquilla: TWideStringField; qtratamientosventilador: TWideStringField; qtratamientosmostrar: TIntegerField; qtratamientosvariedad: TWideStringField; qtratamientosnum_boquillas: TIntegerField; qtratamientoslitros_hect: TIntegerField; qtratamientosdesc_boquilla: TWideStringField; qtratamientoslitros_minutos: TFloatField; qtratamientossuperficie: TFloatField; qtratamientosfecha_fin: TDateField; qtratamientoshora_inicio: TTimeField; qtratamientosfecha_inicio: TDateField; qtratamientosancho_calle: TFloatField; qrecomendacionesvariedad: TWideStringField; qrecomendacioneside: TIntegerField; qrecomendacionesidtb: TIntegerField; qtratamientosdetallecantidadprevista_mezcla: TFloatField; qtratamientosdetallecantidadprevista_materia: TFloatField; qrecomendacionescodpar: TWideStringField; qresponsables: TZReadOnlyQuery; dsqresponsables: TDataSource; qresponsablesnombre: TWideStringField; comboresponsables: TDBLookupComboBox; Label2: TLabel; qresponsablesnif: TWideStringField; qrecomendacionesdistancialineal: TIntegerField; qrecomendacionesancho_calle_1: TFloatField; qrecomendacionestipo: TWideStringField; qrecomendacioneslitroshectarea: TFloatField; qrecomendacionesancho_calle: TFloatField; qrecomendacionesventilador: TWideStringField; procedure Button1Click(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } vrecomendacion,vempresa:integer; end; var generartratamientos: Tgenerartratamientos; implementation {$R *.dfm} procedure Tgenerartratamientos.Button1Click(Sender: TObject); var vid:integer; begin qrecomendaciones.First; qidtratamiento.Close; qidtratamiento.Open; vid:=qidtratamientoid.asinteger; qtratamientos.Open; qtratamientosdetalle.Open; while not qrecomendaciones.Eof do begin qtratamientos.Append; qtratamientoside.value:=qrecomendacioneside.Asinteger; qtratamientosid.value:=vid; qtratamientosidcc.value:=qrecomendacionescodpar.Asstring; qtratamientosdesc_cc.value:=qrecomendacionesparcela.Asstring; qtratamientosfecha.value:=vfecha.Date; qtratamientosidrecomendacion.value:=qrecomendacionesid.Asinteger; qtratamientosobservaciones.value:=qrecomendacionesobservaciones.Asstring; qtratamientosidrecomendacion.value:=qrecomendacionesid.Asinteger; qtratamientosvelocidad.value:=qrecomendacionesvelocidad.Asfloat; qtratamientospresion.value:=qrecomendacionespresion.Asinteger; qtratamientosboquilla.value:=qrecomendacionesdesc_boquilla.Asstring; qtratamientosvariedad.value:=qrecomendacionesvariedad.Asstring; qtratamientosnum_boquillas.value:=qrecomendacionesnum_boquillas.Asinteger; qtratamientoslitros_hect.value:=trunc(qrecomendacioneslitroshectarea.AsFloat); qtratamientosdesc_boquilla.value:=qrecomendacionesdesc_boquilla.Asstring; qtratamientosnif_responsable.value:=qresponsablesnif.asstring; qtratamientosresponsable.value:=qresponsablesnombre.AsString; qtratamientoslitros_minutos.value:=qrecomendacioneslitros_minuto.Asfloat; qtratamientosancho_calle.value:=qrecomendacionesancho_calle_1.Asfloat; qtratamientossuperficie.value:=qrecomendacionessuperficie.Asfloat; qtratamientosventilador.value:=qrecomendacionesventilador.Asstring; qtratamientos.post; while not qrecomendacionesdetalle.Eof do begin qtratamientosdetalle.append; qtratamientosdetalleide.value:=qrecomendacionesdetalleide.Asinteger; qtratamientosdetalleidt.value:=vid; qtratamientosdetalleidaf.value:=qrecomendacionesdetalleidaf.Asinteger; qtratamientosdetalleidma.value:=qrecomendacionesdetalleidma.Asinteger; qtratamientosdetalledescripcion_af.value:=qrecomendacionesdetalledescripcion_af.Asstring; qtratamientosdetalledescripcion_ma.value:=qrecomendacionesdetalledescripcion_ma.Asstring; qtratamientosdetallecantidad_base.value:=qrecomendacionesdetallecantidad_base.Asfloat; qtratamientosdetalledosis.value:=qrecomendacionesdetalledosis.Asfloat; qtratamientosdetalleunidad_medida.value:=qrecomendacionesdetalleunidad_medida.Asstring; qtratamientosdetalleregistro.value:=qrecomendacionesdetalleregistro.Asstring; qtratamientosdetalleplazo.value:=qrecomendacionesdetalleplazo.Asinteger; qtratamientosdetallecantidadprevista_mezcla.value:=TRUNC(qrecomendacioneslitroshectarea.Asinteger*qrecomendacionessuperficie.AsFloat); qtratamientosdetallecantidadprevista_materia.value:=((qrecomendacioneslitros_hect.Asinteger*qrecomendacionessuperficie.AsFloat)/qrecomendacionesdetallecantidad_base.asfloat)*qrecomendacionesdetalledosis.asfloat; qtratamientosdetalleen_cuaderno.value:=1; qtratamientosdetalleorden.value:=qrecomendacionesdetalleorden.Asinteger; qtratamientosdetallefecha.value:=vfecha.Date; qtratamientosdetalle.post; qrecomendacionesdetalle.Next; end; vid:=vid+1; qrecomendacionesdetalle.First; qrecomendaciones.Next; end; showmessage('¡¡¡¡ TRATAMIENTOS GENERADOS CORRECTAMENTE ¡¡¡¡'); end; procedure Tgenerartratamientos.FormShow(Sender: TObject); begin vfecha.Date:=date(); qrecomendaciones.Prepare; qrecomendaciones.ParamByName('EMPRESA').AsInteger:=vempresa; qrecomendaciones.ParamByName('RECOMENDACION').AsInteger:=vrecomendacion; qrecomendaciones.Open; qrecomendacionesdetalle.Prepare; qrecomendacionesdetalle.ParamByName('EMPRESA').AsInteger:=vempresa; qrecomendacionesdetalle.ParamByName('RECOMENDACION').AsInteger:=vrecomendacion; qrecomendacionesdetalle.Open; qresponsables.Open; comboresponsables.KeyValue:=qresponsablesnif.AsString; end; end. ======================================== FICHERO: fgenericas.pas ======================================== unit fgenericas; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractDataset, ZDataset, ZAbstractRODataset, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls,datos; type Tgenericas = class(TForm) genericas: TZQuery; dsgenericas: TDataSource; Panel13: TPanel; Panel17: TPanel; gridgenericos: TDBGrid; Panel7: TPanel; btAcancelar: TButton; btAmodificar: TButton; btAborrar: TButton; btAnuevo: TButton; btAguardar: TButton; genericaside: TIntegerField; genericasid: TIntegerField; genericasdescripcion: TWideStringField; genericascodigo: TWideStringField; procedure btAnuevoClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormShow(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure btAmodificarClick(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); procedure dsgenericasStateChange(Sender: TObject); private { Private declarations } public { Public declarations } end; var genericas: Tgenericas; implementation {$R *.dfm} procedure Tgenericas.btAborrarClick(Sender: TObject); begin genericas.Delete; end; procedure Tgenericas.btAcancelarClick(Sender: TObject); begin genericas.cancel; end; procedure Tgenericas.btAguardarClick(Sender: TObject); begin genericas.post; end; procedure Tgenericas.btAmodificarClick(Sender: TObject); begin genericas.edit; end; procedure Tgenericas.btAnuevoClick(Sender: TObject); begin genericas.Append; gridgenericos.SelectedIndex:=1; end; procedure Tgenericas.dsgenericasStateChange(Sender: TObject); begin if genericas.State in [dsedit,dsinsert] then begin btanuevo.Enabled:=false; btamodificar.Enabled:=false; btaborrar.Enabled:=false; btacancelar.Enabled:=true; btaguardar.Enabled:=true; end else begin btanuevo.Enabled:=true; btamodificar.Enabled:=true; btaborrar.Enabled:=true; btacancelar.Enabled:=false; btaguardar.Enabled:=false; end; end; procedure Tgenericas.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tgenericas.FormKeyPress(Sender: TObject; var Key: Char); begin key:=upcase(key); if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tgenericas.FormShow(Sender: TObject); begin genericas.close; genericas.open; end; end. ======================================== FICHERO: fgrupos_trabajadores.pas ======================================== unit fgrupos_trabajadores; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset,datos; type Tgrupostrabajadores = class(TForm) Panel13: TPanel; Panel17: TPanel; DBGrid3: TDBGrid; Panel7: TPanel; btAcancelar: TButton; btAmodificar: TButton; btAborrar: TButton; btAnuevo: TButton; btAguardar: TButton; qgrupostrabajadores: TZQuery; dsqgrupostrabajadores: TDataSource; qgrupostrabajadoreside: TIntegerField; qgrupostrabajadoresid: TIntegerField; qgrupostrabajadoresdescripcion: TWideStringField; Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; Panel4: TPanel; Panel5: TPanel; Panel6: TPanel; Panel8: TPanel; Panel9: TPanel; Panel10: TPanel; Panel11: TPanel; Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; qtrabajosgrupo: TZQuery; dsqtrabajosgrupo: TDataSource; qhorasgrupo: TZQuery; dsqhorasgrupo: TDataSource; qtiposhora: TZReadOnlyQuery; dsqtiposhora: TDataSource; dsqtiposgrabajo: TDataSource; qtipostrabajo: TZReadOnlyQuery; DBGrid1: TDBGrid; DBGrid2: TDBGrid; DBGrid4: TDBGrid; DBGrid5: TDBGrid; qtipostrabajoid: TWideStringField; qtipostrabajonombre: TWideStringField; qtipostrabajoactivo: TIntegerField; qtipostrabajoempresa: TIntegerField; qtipostrabajocoste_elavoracion_campo: TIntegerField; qtipostrabajocoste_elavoracion_almacen: TIntegerField; qtipostrabajoelavoracion_produccion: TIntegerField; qtipostrabajoenvasado_produccion: TIntegerField; qtipostrabajologistica_produccion: TIntegerField; qtipostrabajoseleccionado: TIntegerField; qtipostrabajoalmacen_trabajo: TIntegerField; qhorasgrupoempresa: TIntegerField; qhorasgrupocodigo: TWideStringField; qhorasgrupogrupo: TIntegerField; qhorasgrupodescripcion: TWideStringField; qtrabajosgrupoempresa: TIntegerField; qtrabajosgrupocodigo: TWideStringField; qtrabajosgrupogrupo: TIntegerField; qtrabajosgrupodescripcion: TWideStringField; qtiposhoracodart: TWideStringField; qtiposhoradescrip: TWideStringField; qtiposhoraprecio: TFloatField; qtiposhoraequivalenciahoras: TFloatField; qtiposhoraactivo: TIntegerField; qtiposhoraempresa: TIntegerField; qtiposhorafacturar: TIntegerField; qtiposhoraseleccionado: TIntegerField; procedure btAnuevoClick(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure btAmodificarClick(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); procedure dsqgrupostrabajadoresStateChange(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); procedure qgrupostrabajadoresBeforePost(DataSet: TDataSet); procedure dsqgrupostrabajadoresDataChange(Sender: TObject; Field: TField); procedure Button2Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button3Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var grupostrabajadores: Tgrupostrabajadores; implementation {$R *.dfm} procedure Tgrupostrabajadores.btAborrarClick(Sender: TObject); begin qgrupostrabajadores.delete; end; procedure Tgrupostrabajadores.btAcancelarClick(Sender: TObject); begin qgrupostrabajadores.cancel; end; procedure Tgrupostrabajadores.btAguardarClick(Sender: TObject); begin qgrupostrabajadores.post; end; procedure Tgrupostrabajadores.btAmodificarClick(Sender: TObject); begin qgrupostrabajadores.edit; end; procedure Tgrupostrabajadores.btAnuevoClick(Sender: TObject); begin qgrupostrabajadores.append; dbgrid3.setfocus; end; procedure Tgrupostrabajadores.Button1Click(Sender: TObject); begin qtrabajosgrupo.Delete; qtipostrabajo.Refresh; end; procedure Tgrupostrabajadores.Button2Click(Sender: TObject); begin qtrabajosgrupo.Append; qtrabajosgrupoempresa.Value:=qtipostrabajoempresa.AsInteger; qtrabajosgrupocodigo.Value:=qtipostrabajoid.Asstring; qtrabajosgrupogrupo.Value:=qgrupostrabajadoresid.AsInteger; qtrabajosgrupodescripcion.Value:=qtipostrabajonombre.Asstring; qtrabajosgrupo.Post; qtipostrabajo.refresh; end; procedure Tgrupostrabajadores.Button3Click(Sender: TObject); begin qhorasgrupo.Delete; qtiposhora.Refresh; end; procedure Tgrupostrabajadores.Button4Click(Sender: TObject); begin qhorasgrupo.Append; qhorasgrupoempresa.Value:=qtiposhoraempresa.AsInteger; qhorasgrupocodigo.Value:=qtiposhoracodart.Asstring; qhorasgrupogrupo.Value:=qgrupostrabajadoresid.AsInteger; qhorasgrupodescripcion.Value:=qtiposhoradescrip.Asstring; qhorasgrupo.Post; qtiposhora.Refresh end; procedure Tgrupostrabajadores.dsqgrupostrabajadoresDataChange(Sender: TObject; Field: TField); begin qtrabajosgrupo.close; qtrabajosgrupo.Prepare; qtrabajosgrupo.ParamByName('GRUPO').AsInteger:=qgrupostrabajadoresid.asinteger; qtrabajosgrupo.ParamByName('EMPRESA').AsInteger:=qgrupostrabajadoreside.AsInteger; qtrabajosgrupo.Open; qhorasgrupo.close; qhorasgrupo.Prepare; qhorasgrupo.ParamByName('GRUPO').AsInteger:=qgrupostrabajadoresid.asinteger; qhorasgrupo.ParamByName('EMPRESA').AsInteger:=qgrupostrabajadoreside.AsInteger; qhorasgrupo.Open; qtipostrabajo.close; qtipostrabajo.Prepare; qtipostrabajo.ParamByName('GRUPO').AsInteger:=qgrupostrabajadoresid.asinteger; qtipostrabajo.ParamByName('EMPRESA').AsInteger:=qgrupostrabajadoreside.AsInteger; qtipostrabajo.Open; qtiposhora.close; qtiposhora.Prepare; qtiposhora.ParamByName('GRUPO').AsInteger:=qgrupostrabajadoresid.asinteger; qtiposhora.ParamByName('EMPRESA').AsInteger:=qgrupostrabajadoreside.AsInteger; qtiposhora.Open; end; procedure Tgrupostrabajadores.dsqgrupostrabajadoresStateChange(Sender: TObject); begin if qgrupostrabajadores.State in [dsedit,dsinsert] then begin btanuevo.Enabled:=false; btamodificar.Enabled:=false; btaborrar.Enabled:=false; btacancelar.Enabled:=true; btaguardar.Enabled:=true; end else begin btanuevo.Enabled:=true; btamodificar.Enabled:=true; btaborrar.Enabled:=true; btacancelar.Enabled:=false; btaguardar.Enabled:=false; end; end; procedure Tgrupostrabajadores.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tgrupostrabajadores.FormKeyPress(Sender: TObject; var Key: Char); begin key:=upcase(key); if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tgrupostrabajadores.FormShow(Sender: TObject); begin qgrupostrabajadores.Close; qgrupostrabajadores.Open; end; procedure Tgrupostrabajadores.qgrupostrabajadoresBeforePost(DataSet: TDataSet); begin qgrupostrabajadoreside.Value:=dm.tempresaid.AsInteger; end; end. ======================================== FICHERO: fidasociado.pas ======================================== unit fidasociado; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Data.DB, ZAbstractRODataset, ZDataset, Vcl.Grids, Vcl.DBGrids; type Tidasociado = class(TForm) DBGrid1: TDBGrid; qidasociado: TZReadOnlyQuery; qidasociadoid: TIntegerField; qidasociadoid_envase: TWideStringField; qidasociadonum_palets: TIntegerField; qidasociadonum_envases: TIntegerField; qidasociadomprima: TWideStringField; qidasociadocodssc: TWideStringField; dsqasociado: TDataSource; Panel1: TPanel; btok: TButton; Label1: TLabel; procedure DBGrid1DblClick(Sender: TObject); procedure btokClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } end; var idasociado: Tidasociado; implementation {$R *.dfm} uses fpedidos; procedure Tidasociado.btokClick(Sender: TObject); begin close; end; procedure Tidasociado.DBGrid1DblClick(Sender: TObject); begin btok.Click; end; procedure Tidasociado.FormClose(Sender: TObject; var Action: TCloseAction); begin pedidos.ssccasociado:=qidasociadocodssc.Asstring; end; end. ======================================== FICHERO: fImportarPresenciaPin.pas ======================================== unit fImportarPresenciaPin; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Bde.DBTables, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls, ZAbstractRODataset, ZAbstractDataset, ZDataset; type TImportardesdePresenciaPin = class(TForm) BDPRESENCIAPIN: TDatabase; qmarcajes: TQuery; DSPIN_MARCAJES: TDataSource; qmarcajesPersona: TIntegerField; qmarcajesFecha: TDateField; qmarcajesHora: TTimeField; qmarcajesTerminal: TIntegerField; qmarcajesModificado: TBooleanField; qmarcajesModoIdentificacion: TIntegerField; qmarcajesDNI: TStringField; qmarcajesnombre: TStringField; qtrabajadores: TZQuery; Panel1: TPanel; fdesde: TDateTimePicker; fhasta: TDateTimePicker; Label1: TLabel; Label2: TLabel; Panel2: TPanel; DBGrid3: TDBGrid; Label3: TLabel; Button1: TButton; qticados: TZQuery; qticadosid: TLargeintField; qticadoside: TSmallintField; qticadosfecha: TDateField; qticadosidt: TIntegerField; qticadosTRABAJADOR: TWideStringField; qticadosENTRADA_REAL: TTimeField; qticadosSALIDA_REAL: TTimeField; qtrabajadoreside: TIntegerField; qtrabajadoresid: TSmallintField; qtrabajadoresnif: TWideStringField; qtrabajadoresnombre: TWideStringField; procedure FormShow(Sender: TObject); procedure fdesdeChange(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var ImportardesdePresenciaPin: TImportardesdePresenciaPin; implementation {$R *.dfm} uses datos; procedure TImportardesdePresenciaPin.Button1Click(Sender: TObject); begin qmarcajes.First; while not qmarcajes.Eof do begin qtrabajadores.Close; qtrabajadores.Prepare; qtrabajadores.ParamByName('NIF').AsString:=qmarcajesdni.AsString; qtrabajadores.ParamByName('EMPRESA').Asinteger:=dm.tempresaid.asinteger; qtrabajadores.Open; if qtrabajadores.RecordCount>0 then begin qticados.Close; qticados.Prepare; qticados.ParamByName('EMPRESA').AsInteger:=dm.tempresaid.AsInteger; qticados.ParamByName('trabajador').AsInteger:=qtrabajadoresid.AsInteger; qticados.ParamByName('FECHA').AsDatetime:=qmarcajesfecha.AsDateTime; qticados.Open; if qticados.RecordCount=0 then begin qticados.Append; qticadoside.Value:=dm.tempresaid.AsInteger; qticadosfecha.Value:=qmarcajesfecha.AsDateTime; qticadosidt.Value:=qtrabajadoresid.AsInteger; qticadostrabajador.Value:=qtrabajadoresnombre.AsString; qticadosentrada_real.value:=qmarcajeshora.Asdatetime; qticados.Post; end else begin qticados.Edit; qticadossalida_real.Value:=qmarcajeshora.AsDateTime; qticados.Post; end; end; qmarcajes.Next; end; end; procedure TImportardesdePresenciaPin.fdesdeChange(Sender: TObject); begin qmarcajes.Close; qmarcajes.Prepare; qmarcajes.ParamByName('DESDE').AsDate:=fdesde.Date; qmarcajes.ParamByName('HASTA').AsDate:=fhasta.Date; qmarcajes.Open; end; procedure TImportardesdePresenciaPin.FormShow(Sender: TObject); begin fdesde.Date:=date; fhasta.Date:=date; try CopyFileEx('e:\db\marcajes.db','c:\agrigest\datos\presenciapin\marcajes.db', nil, nil, nil, 0); CopyFileEx('e:\db\marcajes.px','c:\agrigest\datos\presenciapin\marcajes.px', nil, nil, nil, 0); CopyFileEx('e:\db\personal.db','c:\agrigest\datos\presenciapin\personal.db', nil, nil, nil, 0); CopyFileEx('e:\db\personal.mb','c:\agrigest\datos\presenciapin\personal.mb', nil, nil, nil, 0); CopyFileEx('e:\db\personal.px','c:\agrigest\datos\presenciapin\personal.px', nil, nil, nil, 0); finally end; end; end. ======================================== FICHERO: fimpresionarticuloscomponentes.pas ======================================== unit fimpresionarticuloscomponentes; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZDataset, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, frxClass,frxDBSet,Excel2000, ComObj; type Tinfarticulos = class(TForm) Panel1: TPanel; todosarticulos: TCheckBox; DBGrid1: TDBGrid; qarticulos: TZReadOnlyQuery; dsqarticulos: TDataSource; DBGrid2: TDBGrid; qarticulosidempresa: TIntegerField; qarticulosid: TIntegerField; qarticuloscodigo: TWideStringField; qarticulosdescripcion: TWideStringField; qarticulosfamilia: TIntegerField; qarticulosprovhab: TIntegerField; qarticulostipoiva: TIntegerField; qarticulospreciocoste: TFloatField; qarticulosmargen: TFloatField; qarticulosbeneficio: TFloatField; qarticulospvp: TFloatField; qarticulosstock: TFloatField; qarticulosult_preciocompra: TFloatField; qarticulosfacturable: TIntegerField; qarticulosobservaciones: TWideStringField; qarticulosimagen: TBlobField; qarticulosactivo: TIntegerField; qarticulosvalor_almacen: TFloatField; qarticulosstock_minimo: TFloatField; qarticulosavisar_stock: TIntegerField; qarticuloscontrolar_traza: TIntegerField; qarticulospeso: TFloatField; qarticulosnomfamilia: TWideStringField; qarticulosnomproveedor: TWideStringField; btimprimir: TButton; btexcel: TButton; informes: TfrxReport; informedb: TfrxDBDataset; SaveDialog1: TSaveDialog; procedure todosarticulosClick(Sender: TObject); procedure btimprimirClick(Sender: TObject); procedure DBGrid1TitleClick(Column: TColumn); procedure FormShow(Sender: TObject); procedure btexcelClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar = nil); end; var infarticulos: Tinfarticulos; implementation {$R *.dfm} procedure Tinfarticulos.ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar); 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 // 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 Tinfarticulos.btexcelClick(Sender: TObject); var archivo:string; begin savedialog1.FileName:='ARTICULOS-COMPONENTES.xls'; savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'ARTICULOS-COMPONENTES',DBGRID1); finally showmessage('Los datos han sido exportados correctamente a '+archivo); end; end; procedure Tinfarticulos.btimprimirClick(Sender: TObject); begin informedb.Datasource:=dsqarticulos; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\listado-articulos.fr3'); // if rentradas.Checked then informes.Variables.Variables['TITULO']:=QUOTEDSTR('Listado de entradas desde el '+datetostr(fdesde.Date)+' hasta el '+datetostr(fhasta.Date) ); // if rsalidas.Checked then informes.Variables.Variables['TITULO']:=QUOTEDSTR('Listado de salidas desde el '+datetostr(fdesde.Date)+' hasta el '+datetostr(fhasta.Date) ); informes.ShowReport(); informes.Clear end; procedure Tinfarticulos.DBGrid1TitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=qarticulos.SortType; qarticulos.SortedFields:=Column.FieldName; If st = stAscending then qarticulos.SortType:=stDescending else qarticulos.SortType:=stAscending; dsqarticulos.DataSet.First; end; procedure Tinfarticulos.FormShow(Sender: TObject); begin qarticulos.Open; end; procedure Tinfarticulos.todosarticulosClick(Sender: TObject); begin if todosarticulos.Checked then begin qarticulos.Close; qarticulos.SQL.Clear; qarticulos.SQL.Add('select a.*,f.descripcion as nomfamilia,p.nombre_corto as nomproveedor from articulosf a,familias f,proveedores p where a.idempresa=f.idempresa and a.idempresa=p.idempresa and a.familia=f.id and a.provhab=p.id order by a.descripcion'); qarticulos.Open; end else begin qarticulos.Close; qarticulos.SQL.Clear; qarticulos.SQL.Add('select a.*,f.descripcion as nomfamilia,p.nombre_corto as nomproveedor from articulosf a,familias f,proveedores p where a.activo=1 and a.idempresa=f.idempresa and a.idempresa=p.idempresa and a.familia=f.id and a.provhab=p.id order by a.descripcion'); qarticulos.Open; end; end; end. ======================================== FICHERO: fimpresionconsumos.pas ======================================== unit fimpresionconsumos; 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.DBCtrls, Vcl.ComCtrls, frxClass, frxDBSet, Data.DB, ZAbstractRODataset, ZDataset, Vcl.Grids, Vcl.DBGrids,Excel2000, ComObj; type Tinsumos = class(TForm) Panel2: TPanel; DBGrid1: TDBGrid; SaveDialog1: TSaveDialog; dsqentradas: TDataSource; qentradas: TZReadOnlyQuery; informes: TfrxReport; informedb: TfrxDBDataset; dsproveedores: TDataSource; qproveedores: TZReadOnlyQuery; qproveedoresid: TIntegerField; qproveedoresidempresa: TIntegerField; qproveedoresnombre: TWideStringField; qproveedoresnombre_corto: TWideStringField; qarticulos: TZReadOnlyQuery; qarticulosidempresa: TIntegerField; qarticulosid: TIntegerField; qarticuloscodigo: TWideStringField; qarticulosdescripcion: TWideStringField; dsarticulos: TDataSource; dsfamilias: TDataSource; qfamilias: TZReadOnlyQuery; qfamiliasidempresa: TIntegerField; qfamiliasid: TIntegerField; qfamiliasdescripcion: TWideStringField; Panel1: TPanel; Panel4: TPanel; btimprimir: TButton; btexcel: TButton; Button1: TButton; Panel3: TPanel; Label1: TLabel; Label2: TLabel; Label3: TLabel; fdesde: TDateTimePicker; fhasta: TDateTimePicker; qentradasidempresa: TIntegerField; qentradasidarticulo: TIntegerField; qentradascodigo: TWideStringField; qentradasdescripcion: TWideStringField; qentradassumeamcantidad: TFloatField; procedure Button1Click(Sender: TObject); procedure btimprimirClick(Sender: TObject); procedure btexcelClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar = nil); end; var insumos: Tinsumos; implementation {$R *.dfm} procedure Tinsumos.ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar); 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 // 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 Tinsumos.btexcelClick(Sender: TObject); var archivo:string; begin savedialog1.FileName:='CONSUMOS DE MATERIALES.xls'; savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'MATERIALES',DBGRID1); finally showmessage('Los datos han sido exportados correctamente a '+archivo); end; end; procedure Tinsumos.btimprimirClick(Sender: TObject); begin informedb.Datasource:=dsqentradas; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\informeconsumos.fr3'); informes.ShowReport(); informes.Clear end; procedure Tinsumos.Button1Click(Sender: TObject); var dia,mes,anyo:word; tdia,tmes,tanyo,tfdesde,tfhasta:string; begin decodedate(fdesde.Date,anyo,mes,dia); tfdesde:=''''+inttostr(dia)+'/'+inttostr(mes)+'/'+inttostr(anyo-2000)+''''; decodedate(fhasta.Date,anyo,mes,dia); tfhasta:=''''+inttostr(dia)+'/'+inttostr(mes)+'/'+inttostr(anyo-2000)+''''; qentradas.Prepare; qentradas.Close; qentradas.ParamByName('DESDE').AsDate:=fdesde.date; qentradas.ParamByName('HASTA').AsDate:=fhasta.date; qentradas.open; end; end. ======================================== FICHERO: fimpresionentradas.pas ======================================== unit fimpresionentradas; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZDataset, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, frxClass,frxDBSet,Excel2000, ComObj, Vcl.DBCtrls; type Timpentradas = class(TForm) Panel1: TPanel; Panel4: TPanel; btimprimir: TButton; btexcel: TButton; Button1: TButton; Panel3: TPanel; Label1: TLabel; Label2: TLabel; Label3: TLabel; fdesde: TDateTimePicker; fhasta: TDateTimePicker; Panel2: TPanel; DBGrid1: TDBGrid; informes: TfrxReport; informedb: TfrxDBDataset; SaveDialog1: TSaveDialog; dsqentradas: TDataSource; qentradas: TZReadOnlyQuery; Label4: TLabel; dsproveedores: TDataSource; qproveedores: TZReadOnlyQuery; dsarticulos: TDataSource; qarticulos: TZReadOnlyQuery; dsfamilias: TDataSource; qfamilias: TZReadOnlyQuery; qproveedoresid: TIntegerField; qproveedoresidempresa: TIntegerField; qproveedoresnombre: TWideStringField; qproveedoresnombre_corto: TWideStringField; qarticulosidempresa: TIntegerField; qarticulosid: TIntegerField; qarticuloscodigo: TWideStringField; qarticulosdescripcion: TWideStringField; qfamiliasidempresa: TIntegerField; qfamiliasid: TIntegerField; qfamiliasdescripcion: TWideStringField; comboproveedor: TDBLookupComboBox; comboarticulos: TDBLookupComboBox; combofamilias: TDBLookupComboBox; RadioGroup1: TRadioGroup; chkproveedor: TRadioButton; chkarticulos: TRadioButton; chkfamilias: TRadioButton; chktodos: TRadioButton; qentradasidempresa: TIntegerField; qentradasidentrada: TIntegerField; qentradasidproveedor: TIntegerField; qentradasnomproveedor: TWideStringField; qentradasfecha: TDateField; qentradasdocumento: TWideStringField; qentradasiddetalle: TIntegerField; qentradascodproveedor: TWideStringField; qentradasdescripcion_proveedor: TWideStringField; qentradasid_propio: TWideStringField; qentradasdescripcion_propia: TWideStringField; qentradasidfamilia: TIntegerField; qentradasnomfamilia: TWideStringField; qentradascantidad: TFloatField; qentradasstock: TFloatField; qentradasprecio: TFloatField; qentradaslote: TWideStringField; procedure DBGrid1TitleClick(Column: TColumn); procedure chkproveedorClick(Sender: TObject); procedure chkarticulosClick(Sender: TObject); procedure chkfamiliasClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure chktodosClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure comboproveedorCloseUp(Sender: TObject); procedure comboarticulosCloseUp(Sender: TObject); procedure combofamiliasCloseUp(Sender: TObject); procedure btimprimirClick(Sender: TObject); procedure btexcelClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar = nil); end; var impentradas: Timpentradas; implementation {$R *.dfm} uses datos; procedure Timpentradas.ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar); 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 // 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 Timpentradas.btexcelClick(Sender: TObject); var archivo:string; begin savedialog1.FileName:='ENTRADAS DE MATERIALES.xls'; savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'ENTRADAS',DBGRID1); finally showmessage('Los datos han sido exportados correctamente a '+archivo); end; end; procedure Timpentradas.btimprimirClick(Sender: TObject); begin informedb.Datasource:=dsqentradas; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\informecompras.fr3'); informes.ShowReport(); informes.Clear end; procedure Timpentradas.Button1Click(Sender: TObject); var dia,mes,anyo:word; tdia,tmes,tanyo,tfdesde,tfhasta:string; begin decodedate(fdesde.Date,anyo,mes,dia); tfdesde:=''''+inttostr(dia)+'/'+inttostr(mes)+'/'+inttostr(anyo-2000)+''''; decodedate(fhasta.Date,anyo,mes,dia); tfhasta:=''''+inttostr(dia)+'/'+inttostr(mes)+'/'+inttostr(anyo-2000)+''''; qentradas.Close; qentradas.Filtered:=false; qentradas.Filter:='fecha>='+tfdesde+' and fecha<='+tfhasta; qentradas.filtered:=true; qentradas.open; end; procedure Timpentradas.chkarticulosClick(Sender: TObject); begin comboproveedor.Visible:=false; comboarticulos.Visible:=true; combofamilias.Visible:=false; qentradas.Close; qentradas.MasterSource:=nil; qentradas.LinkedFields:='idempresa;id_propio'; qentradas.MasterFields:='idempresa;codigo'; qentradas.MasterSource:=dsarticulos; end; procedure Timpentradas.chkfamiliasClick(Sender: TObject); begin comboproveedor.Visible:=false; comboarticulos.Visible:=false; combofamilias.Visible:=true; qentradas.Close; qentradas.MasterSource:=nil; qentradas.LinkedFields:='idempresa;idfamilia'; qentradas.MasterFields:='idempresa;id'; qentradas.MasterSource:=dsfamilias; end; procedure Timpentradas.chkproveedorClick(Sender: TObject); begin comboproveedor.Visible:=true; comboarticulos.Visible:=false; combofamilias.Visible:=false; qentradas.Close; qentradas.MasterSource:=nil; qentradas.LinkedFields:='idempresa;idproveedor'; qentradas.MasterFields:='idempresa;id'; qentradas.MasterSource:=dsproveedores; end; procedure Timpentradas.chktodosClick(Sender: TObject); begin comboproveedor.Visible:=false; comboarticulos.Visible:=false; combofamilias.Visible:=false; qentradas.Close; qentradas.MasterSource:=nil; qentradas.LinkedFields:=''; qentradas.MasterFields:=''; end; procedure Timpentradas.comboarticulosCloseUp(Sender: TObject); begin qentradas.Close; end; procedure Timpentradas.combofamiliasCloseUp(Sender: TObject); begin qentradas.Close; end; procedure Timpentradas.comboproveedorCloseUp(Sender: TObject); begin qentradas.Close; end; procedure Timpentradas.DBGrid1TitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=qentradas.SortType; qentradas.SortedFields:=Column.FieldName; If st = stAscending then qentradas.SortType:=stDescending else qentradas.SortType:=stAscending; dsqentradas.DataSet.First; end; procedure Timpentradas.FormShow(Sender: TObject); begin qentradas.Close; qproveedores.Close; qarticulos.Close; qfamilias.Close; dm.tempresa.open; qproveedores.open; qarticulos.open; qfamilias.open; chktodos.Checked:=true; fdesde.Date:=date(); fhasta.Date:=date(); end; end. ======================================== FICHERO: fimpresionmovimientos.pas ======================================== unit fimpresionmovimientos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZDataset, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, frxClass, frxDBSet,Excel2000, ComObj; type Tinfmovimientos = class(TForm) Panel1: TPanel; Panel2: TPanel; DBGrid1: TDBGrid; qmovimientos: TZReadOnlyQuery; dsqmovimientos: TDataSource; Panel4: TPanel; Panel3: TPanel; Label1: TLabel; Label2: TLabel; Label3: TLabel; fdesde: TDateTimePicker; fhasta: TDateTimePicker; btimprimir: TButton; btexcel: TButton; RadioGroup1: TRadioGroup; rentradas: TRadioButton; rsalidas: TRadioButton; qmovimientosid: TIntegerField; qmovimientosfecha: TDateField; qmovimientosfechatrabajo: TDateField; qmovimientosparcela: TWideStringField; qmovimientosmprima: TWideStringField; qmovimientosmprima_p: TWideStringField; qmovimientosid_envase: TWideStringField; qmovimientosnum_envases: TIntegerField; qmovimientoscliente: TWideStringField; qmovimientosciudad: TWideStringField; qmovimientospeso_neto: TFloatField; qmovimientospeso_neto_teorico: TFloatField; qmovimientospeso_medio: TFloatField; qmovimientostemperatura: TFloatField; qmovimientoslote: TIntegerField; Button1: TButton; informedb: TfrxDBDataset; informes: TfrxReport; SaveDialog1: TSaveDialog; qmovimientosidalbaran: TWideStringField; qmovimientospeso_bruto: TFloatField; qmovimientoscalibrecalidad: TIntegerField; procedure DBGrid1TitleClick(Column: TColumn); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); procedure Button1Click(Sender: TObject); procedure btimprimirClick(Sender: TObject); procedure rentradasClick(Sender: TObject); procedure rsalidasClick(Sender: TObject); procedure btexcelClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar = nil); end; var infmovimientos: Tinfmovimientos; implementation {$R *.dfm} uses principal; procedure Tinfmovimientos.ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar); 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 // 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 Tinfmovimientos.btexcelClick(Sender: TObject); var archivo:string; begin savedialog1.FileName:='ENTRADAS-SALIDAS.xlsx'; savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'ENTRADAS-SALIDAS',DBGRID1); finally showmessage('Los datos han sido exportados correctamente a '+archivo); end; end; procedure Tinfmovimientos.btimprimirClick(Sender: TObject); begin informedb.Datasource:=dsqmovimientos; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\entradas-salidas.fr3'); if rentradas.Checked then informes.Variables.Variables['TITULO']:=QUOTEDSTR('Listado de entradas desde el '+datetostr(fdesde.Date)+' hasta el '+datetostr(fhasta.Date) ); if rsalidas.Checked then informes.Variables.Variables['TITULO']:=QUOTEDSTR('Listado de salidas desde el '+datetostr(fdesde.Date)+' hasta el '+datetostr(fhasta.Date) ); informes.ShowReport(); informes.Clear end; procedure Tinfmovimientos.Button1Click(Sender: TObject); var comillas,espacio,desde,hasta:string; dia,mes,anyo:word; tdia,tmes,tanyo:string; begin comillas:=''''; espacio:=comillas+' '+comillas; decodedate(fdesde.date,anyo,mes,dia); tdia:=floattostr(dia); tmes:=floattostr(mes); tanyo:=floattostr(anyo); desde:=comillas+tanyo+'-'+tmes+'-'+tdia+comillas; decodedate(fhasta.date,anyo,mes,dia); tdia:=floattostr(dia); tmes:=floattostr(mes); tanyo:=floattostr(anyo); hasta:=comillas+tanyo+'-'+tmes+'-'+tdia+comillas; if rentradas.Checked then begin qmovimientos.Close; qmovimientos.SQL.Clear; qmovimientos.SQL.Add('(select v.id,v.fecha,v.fechatrabajo,v.parcela,v.mprima as mprima,v.mprima_p as mprima_p,v.id_envase,v.num_envases,v.destino as cliente,'); qmovimientos.SQL.Add(espacio+' as ciudad,v.peso_bruto,v.peso_neto,v.peso_neto_teorico,v.peso_medio,v.temperatura,v.lote,v.idalbaran,v.calibrecalidad '); qmovimientos.SQL.Add(' from v_ea_pesadaslotes v where v.idea>0 and '); qmovimientos.SQL.Add(' v.fecha>='+desde+' and fecha<='+hasta); qmovimientos.SQL.Add(' and v.pedidocliente is null)'); qmovimientos.SQL.Add(' UNION ALL'); qmovimientos.SQL.Add('(select v.id,v.fecha,v.fechatrabajo,v.parcela,v.mprima as mprima,v.mprima_p as mprima_p,v.id_envase,v.num_envases,c.nombre as cliente,'); qmovimientos.SQL.Add(' p.iddestino as ciudad,v.peso_bruto,v.peso_neto,v.peso_neto_teorico,v.peso_medio,v.temperatura,v.lote,v.idalbaran,v.calibrecalidad '); qmovimientos.SQL.Add(' from v_ea_pesadaslotes v, pedidos p,clientes c where v.idea>0 and '); qmovimientos.SQL.Add(' v.fecha>=+'+desde+' and fecha<='+hasta); qmovimientos.SQL.Add(' and v.pedidocliente is not null and v.pedidocliente=p.id and p.idcliente=c.id)'); qmovimientos.SQL.Add(' order by mprima,lote,id desc, fecha'); qmovimientos.Open; end; if rsalidas.Checked then begin qmovimientos.Close; qmovimientos.SQL.Clear; qmovimientos.SQL.Add('(select v.id,v.fecha,v.fechatrabajo,v.parcela,v.mprima as mprima,v.mprima_p as mprima_p,v.id_envase,v.num_envases,v.destino as cliente,'); qmovimientos.SQL.Add(espacio+' as ciudad,v.peso_bruto,v.peso_neto,v.peso_neto_teorico,v.peso_medio,v.temperatura,v.lote,v.idalbaran,v.calibrecalidad '); qmovimientos.SQL.Add(' from v_ea_pesadaslotes v where (v.idea=0 or v.iddestino in (select id from almacenes where final=1)) and v.iddestino<>0 and v.iddestino in (select id from almacenes where produccion=0) and '); qmovimientos.SQL.Add(' v.fecha>='+desde+' and fecha<='+hasta); qmovimientos.SQL.Add(' and v.pedidocliente is null) '); qmovimientos.SQL.Add(' UNION ALL'); qmovimientos.SQL.Add('((select v.id,v.fecha,v.fechatrabajo,v.parcela,v.mprima as mprima,v.mprima_p as mprima_p,v.id_envase,v.num_envases,c.nombre as cliente,p.iddestino as ciudad,'); qmovimientos.SQL.Add(' v.peso_bruto,v.peso_neto,v.peso_neto_teorico,v.peso_medio,v.temperatura,v.lote,v.idalbaran,v.calibrecalidad'); qmovimientos.SQL.Add(' from v_ea_pesadaslotes v, pedidos p,clientes c where (v.idea=0 or v.iddestino in (select id from almacenes where final=1)) and v.iddestino<>0 and v.iddestino in (select id from almacenes where produccion=0) and '); qmovimientos.SQL.Add(' v.fecha>='+desde+' and fecha<='+hasta); qmovimientos.SQL.Add(' and v.pedidocliente is not null and v.pedidocliente=p.id and p.idcliente=c.id))'); qmovimientos.SQL.Add(' order by mprima_p,lote,id desc, fecha'); qmovimientos.Open; end; end; procedure Tinfmovimientos.DBGrid1TitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=qmovimientos.SortType; qmovimientos.SortedFields:=Column.FieldName; If st = stAscending then qmovimientos.SortType:=stDescending else qmovimientos.SortType:=stAscending; dsqmovimientos.DataSet.First; end; procedure Tinfmovimientos.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; if (key='.') and (activecontrol is tedit) then begin if (activecontrol as tedit).Name='thoras' then key:=','; if (activecontrol as tedit).Name='edimporte' then key:=','; if (activecontrol as tedit).Name='edjhoras' then key:=','; if (activecontrol as tedit).Name='lprecio' then key:=','; if (activecontrol as tedit).Name='edjprecio' then key:=','; if (activecontrol as tedit).Name='limporteanticipos' then key:=','; end; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tinfmovimientos.FormShow(Sender: TObject); begin fdesde.Date:=date; fhasta.Date:=date; end; procedure Tinfmovimientos.rentradasClick(Sender: TObject); begin qmovimientos.Close; end; procedure Tinfmovimientos.rsalidasClick(Sender: TObject); begin qmovimientos.Close; end; end. ======================================== FICHERO: firma.pas ======================================== unit firma; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls; type TVFIRMA = class(TForm) Panel1: TPanel; Panel2: TPanel; Button1: TButton; Button2: TButton; Label2: TLabel; Label1: TLabel; Image1: TImage; procedure panelfirmaMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure panelfirmaMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure Image1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure Image1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure Image1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure Button2Click(Sender: TObject); procedure FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var VFIRMA: TVFIRMA; pintando:boolean; implementation {$R *.dfm} procedure TVFIRMA.Button1Click(Sender: TObject); begin image1.Picture.Bitmap.SaveToFile('c:\agrigest\informes\firmatemp.bmp'); end; procedure TVFIRMA.Button2Click(Sender: TObject); var W: Word; begin for W := 10 to 200 do Canvas.Pixels[W, 10] := clRed; end; procedure TVFIRMA.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin pintando:=true; end; procedure TVFIRMA.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var xpos,ypos:integer; begin xpos:=mouse.cursorpos.X; ypos:=mouse.cursorpos.y; label1.Caption:='x='+inttostr(xpos); label2.Caption:='y='+inttostr(ypos); if pintando then begin Canvas.Pixels[xpos,ypos]:=clRed; end; end; procedure TVFIRMA.FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin pintando:=false; end; procedure TVFIRMA.Image1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin pintando:=true; end; procedure TVFIRMA.Image1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var xpos,ypos:integer; begin xpos:=mouse.cursorpos.X-(left+7+image1.Left); ypos:=mouse.cursorpos.y-(top+30+image1.Top); if pintando then begin with image1.Canvas do begin pixels[xpos,ypos]:=clblack; pixels[xpos-1,ypos]:=clblack; pixels[xpos+1,ypos]:=clblack; pixels[xpos,ypos-1]:=clblack; pixels[xpos,ypos+1]:=clblack; pixels[xpos-1,ypos-1]:=clblack; pixels[xpos-1,ypos+1]:=clblack; pixels[xpos+1,ypos-1]:=clblack; pixels[xpos+1,ypos+1]:=clblack; end; end; end; procedure TVFIRMA.Image1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin pintando:=false; end; procedure TVFIRMA.panelfirmaMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin pintando:=true; end; procedure TVFIRMA.panelfirmaMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin pintando:=false; end; end. ======================================== FICHERO: fmaterialespesada.pas ======================================== unit fmaterialespesada; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZDataset, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.DBCtrls, ZAbstractDataset, Vcl.Mask, Vcl.ComCtrls, Vcl.ExtCtrls, ZAbstractTable,Excel2000, ComObj; type Tmaterialespesadas = class(TForm) DBGrid1: TDBGrid; qmateriales: TZReadOnlyQuery; dsqmateriales: TDataSource; gcrpagado: TDBCheckBox; qmateriales2: TZQuery; qmaterialesid: TIntegerField; qmaterialescodigo: TWideStringField; qmaterialesdescripcion: TWideStringField; qmaterialeside: TIntegerField; qmaterialesidea: TIntegerField; qmaterialesidea2: TIntegerField; qmaterialesidaf: TIntegerField; qmaterialescantidad: TFloatField; qmaterialespeso: TFloatField; qmaterialeslote: TWideStringField; qmaterialesprecio: TFloatField; qmaterialesrecuperado: TIntegerField; qmateriales2ide: TIntegerField; qmateriales2idea: TIntegerField; qmateriales2idea2: TIntegerField; qmateriales2idaf: TIntegerField; qmateriales2cantidad: TFloatField; qmateriales2peso: TFloatField; qmateriales2lote: TWideStringField; qmateriales2precio: TFloatField; qmateriales2recuperado: TIntegerField; procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBGrid1CellClick(Column: TColumn); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } procedure AppMessage(var Msg: Tmsg; var Handled:Boolean); end; var materialespesadas: Tmaterialespesadas; implementation {$R *.dfm} procedure Tmaterialespesadas.AppMessage(var Msg: TMSg; Var Handled:Boolean); var actual : TWincontrol; begin if Msg.message = WM_KEYDOWN then begin // esto es para controlar que con la flecha abajo se desplegen las // listas if Msg.wParam = VK_DOWN then begin Actual := Screen.ActiveControl; if Actual is TDBLookupComboBox then if not TDBLookupComboBox(Screen.ActiveForm.ActiveControl).listVisible then TDBLookupComboBox(Screen.ActiveForm.ActiveControl).DropDown; // si utilizas las RX { if Actual is TRxDBLookupCombo then if not TRxDBLookupCombo(Screen.ActiveForm.ActiveControl).listVisible then TRxDBLookupCombo(Screen.ActiveForm.ActiveControl).DropDown; } if Actual is TComboBox then SendMessage(TComboBox(Screen.ActiveForm.ActiveControl).Handle,CB_SHOWDROPDOWN,-1,0); if (Actual is TCustomEdit) then Msg.wParam := VK_TAB; // se pueden añadir mas controles.... end; // y aqui es el control del intro. if Msg.wParam = VK_RETURN THEN begin Actual := Screen.ActiveControl; // para los edit. if (Actual is TCustomEdit) and not (Actual is TCustomMemo) then Msg.wParam := VK_TAB; // para los memo. Con ctrl + enter se salta de linea dentro del // memo, si solo es intro salta al siguiente control if (Actual is TCustomMemo) and (HiWord(GetKeyState(VK_CONTROL)) = 0)then Msg.wParam := VK_TAB; // para los lookup if Actual is TDBLookupComboBox then if not TDBLookupComboBox(Actual).listVisible then Msg.wParam := VK_TAB; // Si utilizas las RX { if Actual is TRxDBLookupCombo then if not TRxDBLookupCombo(Actual).listVisible then Msg.wParam := VK_TAB; } // Los combobox if Actual is TCustomComboBox then if not TCustomComboBox(Actual).DroppedDown then Msg.wParam := VK_TAB; // el radiobutton if Actual is TRadioButton then Msg.wParam := VK_TAB; // en el grid if Actual is TDBGrid then if (TDBGrid(Actual).ReadOnly) or (HiWord(GetKeyState(VK_CONTROL)) = 1)then Msg.wParam := VK_TAB; // o esto otro Con Ctrl + intro siguiente celda con // ctrl + shift + intro celda anterior // es complicado pero es por no liar con el intro solo // que siempre pasa de un control a otro. if Actual is TDBGrid then begin if (TDBGrid(Actual).ReadOnly) or (HiWord(GetKeyState(VK_CONTROL)) = 0) then Msg.wParam := VK_TAB else if not(HiWord(GetKeyState(VK_SHIFT)) = 0) then begin if TDBGrid(Actual).selectedindex > 0 then { increment the field } TDBGrid(Actual).selectedindex := TDBGrid(Actual).selectedindex -1 else TDBGrid(Actual).selectedindex := TDBGrid(Actual).fieldcount -1; end else begin if TDBGrid(Actual).selectedindex < (TDBGrid(Actual).fieldcount -1) then { increment the field } TDBGrid(Actual).selectedindex := TDBGrid(Actual).selectedindex +1 else TDBGrid(Actual).selectedindex := 0; end; end; // ListBox if Actual is TCustomListBox then Msg.wParam := VK_TAB; // TabControl // if Actual is TCustomTabControl then Msg.wParam := VK_TAB; // Aqui se pondrían todos los controles que usamos en la // aplicación y necesitamos cambiar el tab por intro. // de esta forma te despreocupas de cuantos añades y es más // limpio el código end; end; end; procedure Tmaterialespesadas.DBGrid1CellClick(Column: TColumn); begin if column.Field.FieldName ='recuperado' then begin if qmateriales2recuperado.asinteger=-1 then begin qmateriales2.Edit; qmateriales2recuperado.Value:=0; qmateriales2.Post; dbgrid1.selectedIndex:=1; end else begin qmateriales2.Edit; qmateriales2recuperado.Value:=-1; qmateriales2.Post; qmateriales2.Refresh; dbgrid1.SelectedIndex:=1; end; end; qmateriales.Refresh; end; procedure Tmaterialespesadas.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); const IsChecked : array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED); var DrawState: Integer; DrawRect: TRect; begin if (gdFocused in State) then begin if (Column.Field.FieldName = 'recuperado') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'recuperado') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=-1 then DrawState := ischecked[true]; DBgrid1.Canvas.FillRect(Rect); DrawFrameControl(DBgrid1.Canvas.Handle, DrawRect, DFC_BUTTON, DrawState); end; end; end; procedure Tmaterialespesadas.FormCreate(Sender: TObject); var I: Integer; begin Application.OnMessage := AppMessage; gcrpagado.DataField := 'recuperado'; gcrpagado.Visible := False; gcrpagado.SendToBack; gcrpagado.Color := DBGrid1.Color; gcrpagado.Caption := ''; //explained later in the article gcrpagado.ValueChecked := '-1'; gcrpagado.ValueUnChecked := '0'; end; procedure Tmaterialespesadas.FormShow(Sender: TObject); begin qmateriales.open; qmateriales2.open; end; end. ======================================== FICHERO: fmeteorologia.pas ======================================== unit fmeteorologia; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.ExtCtrls; type Tmeteorologia = class(TForm) Panel2: TPanel; btAnuevo: TButton; btAborrar: TButton; btAmodificar: TButton; btAguardar: TButton; btAcancelar: TButton; DBGrid1: TDBGrid; qmeteorologia: TZQuery; dsqmeteorologia: TDataSource; qmeteorologiaid: TIntegerField; qmeteorologiaide: TIntegerField; qmeteorologiadescripcion: TWideStringField; procedure btAnuevoClick(Sender: TObject); procedure qmeteorologiaBeforeOpen(DataSet: TDataSet); procedure qmeteorologiaBeforePost(DataSet: TDataSet); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } var vempresa:integer; end; var meteorologia: Tmeteorologia; implementation {$R *.dfm} procedure Tmeteorologia.btAnuevoClick(Sender: TObject); begin qmeteorologia.Append; end; procedure Tmeteorologia.FormShow(Sender: TObject); begin qmeteorologia.Open; end; procedure Tmeteorologia.qmeteorologiaBeforeOpen(DataSet: TDataSet); begin qmeteorologia.Prepare; qmeteorologia.ParamByName('EMPRESA').AsInteger:=vempresa; end; procedure Tmeteorologia.qmeteorologiaBeforePost(DataSet: TDataSet); begin qmeteorologiaide.Value:=vempresa; end; end. ======================================== FICHERO: formaspago.pas ======================================== unit formaspago; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset,datos, ZAbstractDataset, ZDataset, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls; type Tfformaspago = class(TForm) Panel13: TPanel; Panel17: TPanel; DBGrid3: TDBGrid; Panel7: TPanel; btAcancelar: TButton; btAmodificar: TButton; btAborrar: TButton; btAnuevo: TButton; btAguardar: TButton; qaux: TZQuery; dsqformaspago: TDataSource; qformaspago: TZQuery; qformaspagoid: TIntegerField; qformaspagodescripcion: TWideStringField; qformaspagoide: TIntegerField; qformaspagocodigo: TWideStringField; qformaspagodias: TIntegerField; procedure btAnuevoClick(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure btAmodificarClick(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure dsqformaspagoStateChange(Sender: TObject); private { Private declarations } public { Public declarations } end; var fformaspago: Tfformaspago; implementation {$R *.dfm} procedure Tfformaspago.btAborrarClick(Sender: TObject); begin qformaspago.Delete; end; procedure Tfformaspago.btAcancelarClick(Sender: TObject); begin qformaspago.cancel end; procedure Tfformaspago.btAguardarClick(Sender: TObject); begin qformaspagoide.Value:=dm.tempresaid.AsInteger; qformaspago.post; end; procedure Tfformaspago.btAmodificarClick(Sender: TObject); begin qformaspago.edit; end; procedure Tfformaspago.btAnuevoClick(Sender: TObject); begin dm.tempresa.Open; qaux.sql.clear; qaux.SQL.Add('select max(id)+1 from formas_pago'); qaux.Open; qformaspago.append; qformaspagoide.Value:=dm.tempresaid.AsInteger; dbgrid3.setfocus; qformaspagoid.Value:=qaux.Fields[0].AsInteger; end; procedure Tfformaspago.dsqformaspagoStateChange(Sender: TObject); begin if qformaspago.State in [dsedit,dsinsert] then begin btanuevo.Enabled:=false; btamodificar.Enabled:=false; btaborrar.Enabled:=false; btacancelar.Enabled:=true; btaguardar.Enabled:=true; end else begin btanuevo.Enabled:=true; btamodificar.Enabled:=true; btaborrar.Enabled:=true; btacancelar.Enabled:=false; btaguardar.Enabled:=false; end; end; procedure Tfformaspago.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tfformaspago.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); // if (key='.') and (activecontrol is tdbedit) then // begin // if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' // end; if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tfformaspago.FormShow(Sender: TObject); begin qformaspago.close; qformaspago.open; end; end. ======================================== FICHERO: fpedidos.pas ======================================== unit fpedidos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,principal,datosclientes,datos, Vcl.StdCtrls, Vcl.DBCtrls, Vcl.Mask, Vcl.ComCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls,DATA.DB, ZAbstractRODataset, ZDataset, ZAbstractDataset, frxClass, frxDBSet; type Tpedidos = class(TForm) Panel1: TPanel; Panel2: TPanel; Panel5: TPanel; Label1: TLabel; DBGrid1: TDBGrid; pedidos: TPanel; ppedidos: TPanel; pdatospedidos: TPanel; Label2: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; DBEdit1: TDBEdit; DBEdit3: TDBEdit; DBEdit4: TDBEdit; Panel4: TPanel; Label36: TLabel; btPcancelar: TButton; btPmodificar: TButton; btPborrar: TButton; btPnuevo: TButton; btPguardar: TButton; qclientes: TZReadOnlyQuery; DBLookupComboBox1: TDBLookupComboBox; dsqclientes: TDataSource; DBMemo1: TDBMemo; Label3: TLabel; qdestinos: TZReadOnlyQuery; dsqdestinos: TDataSource; qaux: TZReadOnlyQuery; Panel3: TPanel; DBEdit6: TDBEdit; Label17: TLabel; DBEdit7: TDBEdit; Label18: TLabel; DBEdit13: TDBEdit; Label8: TLabel; DBGrid2: TDBGrid; qclientesid: TIntegerField; qclientesIdempresa: TIntegerField; qclientesnombre: TWideStringField; qclientesnombre_corto: TWideStringField; qdestinoscodigo: TWideStringField; qdestinosidcliente: TIntegerField; qdestinosidempresa: TIntegerField; qdestinosdescripcion: TWideStringField; qdestinosseleccionado: TIntegerField; qdestinosactivo: TIntegerField; qdestinosdireccion: TWideStringField; qdestinospoblacion: TWideStringField; qdestinoscodpost: TWideStringField; qdestinosprovincia: TWideStringField; DBLookupComboBox2: TDBLookupComboBox; Panel6: TPanel; Label10: TLabel; btpdmodificar: TButton; btpdborrar: TButton; btpdnuevo: TButton; qcajas: TZReadOnlyQuery; dsqcajas: TDataSource; qcajasid: TIntegerField; qcajaside: TIntegerField; qcajascodigo: TWideStringField; qcajascod_logi: TIntegerField; qcajasdescripcion: TWideStringField; qcajaslargo: TFloatField; qcajasalto: TFloatField; qcajasancho: TFloatField; qcajastara: TFloatField; qcajaspeso_venta: TFloatField; qcajastipo: TWideStringField; qcajaspalet: TIntegerField; qcajasenvase_trabajo: TIntegerField; qcajasenvase_venta: TIntegerField; qcajascosto: TFloatField; qcajasactivo: TIntegerField; qcajasobservaciones: TWideStringField; qcajasfacturar_pesofijo: TIntegerField; qcajaspreguntar_gen: TIntegerField; qcajasunidades_venta: TIntegerField; Panel7: TPanel; Detallesarticulos: TPageControl; Tasignar: TTabSheet; Panel8: TPanel; Label32: TLabel; Label9: TLabel; tbuscarenvasado: TEdit; DBGrid7: TDBGrid; DBGrid3: TDBGrid; Panel11: TPanel; btALnuevo: TButton; btALborrar: TButton; qenvasados: TZQuery; qenvasadosid: TIntegerField; qenvasadosid_envase: TWideStringField; qenvasadosnum_envases: TIntegerField; qenvasadosdestino: TWideStringField; qenvasadospeso_neto_teorico: TFloatField; qenvasadosmprima: TWideStringField; qenvasadosparcela: TWideStringField; qenvasados2: TZQuery; dsqenvasados2: TDataSource; dsqenvasados: TDataSource; qenvasadosidempresa: TIntegerField; qenvasadosidpedido: TIntegerField; qenvasados2id: TIntegerField; qenvasados2id_envase: TWideStringField; qenvasados2num_envases: TIntegerField; qenvasados2destino: TWideStringField; qenvasados2peso_neto_teorico: TFloatField; qenvasados2mprima: TWideStringField; qenvasados2parcela: TWideStringField; qenvasados2idpedido: TIntegerField; qenvasados2idempresa: TIntegerField; DBEdit9: TDBEdit; Label19: TLabel; qenvasados2lote: TIntegerField; qenvasadospedidocliente: TIntegerField; dspedidos: TDataSource; dtpedidos: TZQuery; dtpedidosid: TIntegerField; dtpedidoside: TIntegerField; dtpedidosidcliente: TIntegerField; dtpedidosiddestino: TWideStringField; dtpedidosfecha_pedido: TDateField; dtpedidosfecha_carga: TDateField; dtpedidosfecha_entrega: TDateField; dtpedidoshora_carga: TTimeField; dtpedidospedidocliente: TWideStringField; dtpedidosabierto: TIntegerField; dtpedidosobservaciones: TWideStringField; dtpedidosfecha_elavoracion: TDateField; dsqpedidos: TDataSource; qpedidos: TZReadOnlyQuery; qpedidosid: TIntegerField; qpedidoside: TIntegerField; qpedidosidcliente: TIntegerField; qpedidosiddestino: TWideStringField; qpedidosfecha_pedido: TDateField; qpedidosfecha_carga: TDateField; qpedidosfecha_entrega: TDateField; qpedidoshora_carga: TTimeField; qpedidospedidocliente: TWideStringField; qpedidosabierto: TIntegerField; qpedidosobservaciones: TWideStringField; qpedidosnombre: TWideStringField; qpedidosdescripcion: TWideStringField; dspedidosdetalle: TDataSource; dtlinpedidos: TZQuery; dtlinpedidosid: TIntegerField; dtlinpedidoside: TIntegerField; dtlinpedidosidpedido: TIntegerField; dtlinpedidosidcliente: TIntegerField; dtlinpedidosidproductocli: TWideStringField; dtlinpedidosidenvase: TWideStringField; dtlinpedidosdesc_envase: TWideStringField; dtlinpedidosdesc_producto: TWideStringField; dtlinpedidoscantidad: TFloatField; dtlinpedidoscantidadservida: TFloatField; dtlinpedidospalets: TIntegerField; dtlinpedidosref: TWideStringField; dtlinpedidosean: TWideStringField; dtlinpedidosmarca: TWideStringField; dtlinpedidosobservaciones: TWideStringField; dtlinpedidosidcajapropia: TWideStringField; dtlinpedidosidalbaran: TWideStringField; dtlinpedidosidexpedicion: TWideStringField; qenvasadosidalbaran: TWideStringField; qenvasados2idalbaran: TWideStringField; dtlinpedidosdesc_envpropio: TWideStringField; btimprimir: TButton; qlistado: TZReadOnlyQuery; infdbpendientes: TfrxDBDataset; infpendientes: TfrxReport; dsqlistado: TDataSource; qlistadoide: TIntegerField; qlistadoid: TIntegerField; qlistadoidcliente: TIntegerField; qlistadofecha_pedido: TDateField; qlistadofecha_carga: TDateField; qlistadoobservaciones: TWideStringField; qlistadodesc_envpropio: TWideStringField; qlistadoidcajapropia: TWideStringField; qlistadonombre: TWideStringField; qlistadocantidad: TFloatField; qlistadocantidadservida: TFloatField; Button1: TButton; dtlinpedidosidcalidad: TWideStringField; dtlinpedidosidacabado: TWideStringField; dtlinpedidosdesc_calidad: TWideStringField; dtlinpedidosdesc_acabado: TWideStringField; dtlinpedidosidformatopropio: TIntegerField; dtlinpedidosdesc_formatopropio: TWideStringField; qacabados: TZReadOnlyQuery; dsqacabados: TDataSource; dsarticulos: TDataSource; dtarticulos: TZQuery; qclientesacabados: TZQuery; dsqclientesacabados: TDataSource; qclientescalidad: TZQuery; dsqclientescalidad: TDataSource; dtarticulosformato: TZQuery; dsarticulosformato: TDataSource; dtarticulosidempresa: TIntegerField; dtarticulosidcliente: TIntegerField; dtarticulosid: TWideStringField; dtarticulosdesc_cliente: TWideStringField; dtarticulosactivo: TIntegerField; qclientesacabadosid: TWideStringField; qclientesacabadosidempresa: TIntegerField; qclientesacabadosidcliente: TIntegerField; qclientesacabadosdescripcion: TWideStringField; qclientesacabadosactivo: TIntegerField; qclientesacabadosean: TWideStringField; qclientesacabadosmarca: TWideStringField; qclientesacabadosobservaciones: TWideStringField; qclientescalidadid: TWideStringField; qclientescalidadidempresa: TIntegerField; qclientescalidadidcliente: TIntegerField; qclientescalidaddescripcion: TWideStringField; qclientescalidadactivo: TIntegerField; dtarticulosformatoidformato: TIntegerField; dtarticulosformatoidempresa: TIntegerField; dtarticulosformatoidcliente: TIntegerField; dtarticulosformatoid: TWideStringField; dtarticulosformatodes_envase: TWideStringField; dtarticulosformatodesc_cliente: TWideStringField; dtarticulosformatoactivo: TIntegerField; dtarticulosformatoean: TWideStringField; dtarticulosformatomarca: TWideStringField; dtarticulosformatoobservaciones: TWideStringField; dtarticulosformatoprecio_venta: TFloatField; dtarticulosformatounidades: TFloatField; Button7: TButton; dtarticulosean: TWideStringField; qacabadosid: TIntegerField; qacabadoside: TIntegerField; qacabadosdescripcion: TWideStringField; qacabadosactivo: TIntegerField; qacabadosdescripcion2: TWideStringField; qacabadoscoste: TFloatField; qacabadospeso: TFloatField; dtlinpedidosunidadescaja: TIntegerField; dtpedidosfecha_caducidad: TDateField; qenvasadoscodean: TWideStringField; qenvasadoscodssc: TWideStringField; dtlinpedidosfecha_caducidad: TDateField; Button2: TButton; dtarticulosformatoiddestino: TWideStringField; dtarticulosiddestino: TWideStringField; qclientescalidadiddestino: TWideStringField; qclientesacabadosiddestino: TWideStringField; Label11: TLabel; combocliente: TDBLookupComboBox; Label12: TLabel; combodestino: TDBLookupComboBox; fdesde: TDateTimePicker; fhasta: TDateTimePicker; Label13: TLabel; btfiltrar: TButton; Button4: TButton; Button3: TButton; qresumenpedidos: TZReadOnlyQuery; dsqresumenpedido: TDataSource; gridresumen: TDBGrid; SaveDialog1: TSaveDialog; qresumenpedidospedido: TIntegerField; qresumenpedidoslinpedido: TIntegerField; qresumenpedidospedidocliente: TWideStringField; qresumenpedidosdestino: TWideStringField; qresumenpedidosfecha_pedido: TDateField; qresumenpedidoslote: TIntegerField; qresumenpedidospartida: TFloatField; qresumenpedidoskg: TFloatField; qresumenpedidosproducto: TWideStringField; qresumenpedidosenvase: TWideStringField; qresumenpedidosformato: TWideStringField; qresumenpedidosvariedad: TWideStringField; qresumenpedidosorigen: TWideStringField; qresumenpedidosobservaciones: TWideStringField; qresumenpedidosenvases_linea: TFloatField; qenvasadosnum_palets: TIntegerField; qcontadores: TZQuery; qcontadoressscc: TIntegerField; qenvasados2num_palets: TIntegerField; qidasociado: TZReadOnlyQuery; qidasociadoid: TIntegerField; qidasociadoid_envase: TWideStringField; qidasociadonum_palets: TIntegerField; qidasociadonum_envases: TIntegerField; qidasociadomprima: TWideStringField; qidasociadocodssc: TWideStringField; qresumenpedidoscajas: TLargeintField; Label14: TLabel; DBEdit2: TDBEdit; dtpedidosalbarancliente: TWideStringField; dtlinpedidosidvariedad: TWideStringField; dtlinpedidosidpais: TWideStringField; dtlinpedidosdesc_pais: TWideStringField; dtlinpedidosdesc_variedad: TWideStringField; dsqpaises: TDataSource; dsqvariedades: TDataSource; dtarticulosformatodun14: TWideStringField; qpaises: TZQuery; qpaisesid: TWideStringField; qpaisesidempresa: TIntegerField; qpaisesidcliente: TIntegerField; qpaisesdescripcion: TWideStringField; qvariedades: TZQuery; qvariedadesid: TIntegerField; qvariedadesidempresa: TIntegerField; qvariedadesidcliente: TIntegerField; qvariedadesdescripcion: TWideStringField; dtlinpedidosdun14: TWideStringField; dtlinpedidosprecio: TFloatField; qresumenpedidosalbaran: TWideStringField; qresumenpedidosfactura: TWideStringField; qresumenpedidosprecio: TFloatField; dtlinpedidospesocaja: TFloatField; dtlinpedidospesopalet: TFloatField; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); procedure btPnuevoClick(Sender: TObject); procedure btPborrarClick(Sender: TObject); procedure btPmodificarClick(Sender: TObject); procedure btPguardarClick(Sender: TObject); procedure btPcancelarClick(Sender: TObject); procedure btpdmodificarClick(Sender: TObject); procedure btpdguardarClick(Sender: TObject); procedure btpdcancelarClick(Sender: TObject); procedure btpdborrarClick(Sender: TObject); procedure btALnuevoClick(Sender: TObject); procedure tbuscarenvasadoChange(Sender: TObject); procedure tbuscarenvasadoEnter(Sender: TObject); procedure btALborrarClick(Sender: TObject); procedure DBGrid2DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure tbuscarenvasadoExit(Sender: TObject); procedure btALnuevoExit(Sender: TObject); procedure DBGrid7DblClick(Sender: TObject); procedure DBEdit6Exit(Sender: TObject); procedure dspedidosStateChange(Sender: TObject); procedure dspedidosdetalleStateChange(Sender: TObject); procedure dspedidosdetalleDataChange(Sender: TObject; Field: TField); procedure dspedidosdestalle2StateChange(Sender: TObject); procedure qpedidosBeforeOpen(DataSet: TDataSet); procedure DBGrid1TitleClick(Column: TColumn); procedure btimprimirClick(Sender: TObject); procedure dsqclientesDataChange(Sender: TObject; Field: TField); procedure btpdnuevoClick(Sender: TObject); procedure Button7Click(Sender: TObject); procedure dsqcajasDataChange(Sender: TObject; Field: TField); procedure Button2Click(Sender: TObject); procedure btfiltrarClick(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure DBGrid2DblClick(Sender: TObject); procedure dtpedidosBeforeDelete(DataSet: TDataSet); procedure dtlinpedidosBeforeDelete(DataSet: TDataSet); private { Private declarations } public { Public declarations } var filtro,ssccasociado:string; vertodos:integer; end; var pedidos: Tpedidos; implementation {$R *.dfm} uses datosproduccion, pesadas, fdlglineaspedido, ftraza_materiales2, dlgduplicar, fidasociado, fcrearalbaran; procedure Tpedidos.btPcancelarClick(Sender: TObject); begin dtpedidos.cancel; pdatospedidos.Enabled:=false; end; procedure Tpedidos.btPmodificarClick(Sender: TObject); begin pdatospedidos.Enabled:=true; dtpedidos.edit; dbedit3.SetFocus; end; procedure Tpedidos.btALborrarClick(Sender: TObject); var pedido:integer; begin qaux.sql.Clear; qaux.sql.add('update ea_pesadas set id_palet2='+''''+'FACTURANDO'+''''+',idpedido=null,pedidocliente=null,idalbaran=null where id='+qenvasados2id.AsString); qaux.ExecSQL; dtlinpedidos.Edit; dtlinpedidoscantidadservida.value:=dtlinpedidoscantidadservida.AsInteger-qenvasados2num_envases.AsInteger; dtlinpedidos.Post; qenvasados2.Refresh; qenvasados.Refresh; pedido:=dtlinpedidosid.AsInteger; dtlinpedidos.Refresh; dtlinpedidos.Locate('Id',pedido,[locaseinsensitive,lopartialkey]); end; procedure Tpedidos.btALnuevoClick(Sender: TObject); var pedido,sscc:integer; begin qenvasados.Edit; qenvasadosidpedido.value:=dtlinpedidosid.AsInteger; qenvasadospedidocliente.value:=dtlinpedidosidpedido.AsInteger; if qenvasadosnum_palets.AsInteger>0 then begin qcontadores.open; sscc:=qcontadoressscc.AsInteger; qcontadores.Edit; qcontadoressscc.Value:=sscc+1; qcontadores.Post; qenvasadoscodssc.Value:=dm.tempresaean.asstring+inttostr(sscc); end else begin idasociado := Tidasociado.Create(nil); try idasociado.qidasociado.prepare; idasociado.qidasociado.ParamByName('LINEAPEDIDO').AsInteger:=dtlinpedidosid.AsInteger; idasociado.qidasociado.Open; idasociado.ShowModal(); finally idasociado.Free; qenvasadoscodssc.Value:=ssccasociado; end; end; qenvasados.Post; dtlinpedidos.Edit; dtlinpedidoscantidadservida.value:=dtlinpedidoscantidadservida.AsInteger+qenvasadosnum_envases.AsInteger; dtlinpedidos.Post; qenvasados.Refresh; qenvasados2.Close; qenvasados2.SQL.Clear; qenvasados2.SQL.Add('select * from ea_pesadas where iddestino in (select id from almacenes where final=1) and idpedido='+dtlinpedidosid.asstring+' ORDER BY `id` DESC'); qenvasados2.open; pedido:=dtlinpedidosid.AsInteger; dtlinpedidos.Refresh; dtlinpedidos.Locate('Id',pedido,[locaseinsensitive,lopartialkey]); tbuscarenvasado.SetFocus; end; procedure Tpedidos.btALnuevoExit(Sender: TObject); begin // tbuscarenvasado.setfocus; end; procedure Tpedidos.btimprimirClick(Sender: TObject); begin qlistado.Close; qlistado.Open; infdbpendientes.Datasource:=dsqlistado; infpendientes.Report.Clear; infpendientes.LoadFromFile('c:\agrigest\informes\pedidospendientes.fr3'); infpendientes.ShowReport(); infpendientes.Clear end; procedure Tpedidos.btPborrarClick(Sender: TObject); begin dtpedidos.delete; qpedidos.Refresh; dtpedidos.Refresh; end; procedure Tpedidos.btPnuevoClick(Sender: TObject); begin pdatospedidos.Enabled:=true; dtpedidos.append; dbedit3.SetFocus; end; procedure Tpedidos.Button2Click(Sender: TObject); begin crearalbaran := Tcrearalbaran.Create(nil); try crearalbaran.vidempresa:=dtpedidoside.AsInteger; crearalbaran.vidcliente:=dtpedidosidcliente.AsInteger; crearalbaran.vpedido:=dtpedidosid.AsInteger; crearalbaran.viddestino:=dtpedidosiddestino.Asstring; crearalbaran.ShowModal(); finally crearalbaran.Free; dtlinpedidos.Refresh; end; end; procedure Tpedidos.Button3Click(Sender: TObject); var archivo,vidcliente,viddestino:string; begin if combocliente.KeyValue=null then vidcliente:='%' else vidcliente:=combocliente.KeyValue; if combodestino.KeyValue=null then viddestino:='%' else viddestino:=combodestino.KeyValue; qresumenpedidos.Prepare; qresumenpedidos.ParamByName('IDCLIENTE').AsString:=vidcliente; qresumenpedidos.ParamByName('IDDESTINO').AsString:=viddestino; qresumenpedidos.ParamByName('FECHAINICIO').Asdate:=fdesde.Date; qresumenpedidos.ParamByName('FECHAFIN').Asdate:=fhasta.Date; qresumenpedidos.open; SaveDialog1.FileName := 'RESUMEN DE PEDIDOS.xlsx'; SaveDialog1.Execute(); archivo := SaveDialog1.FileName; try base.ExportaraExcel(archivo, 'Pedidos', gridresumen) finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure Tpedidos.btfiltrarClick(Sender: TObject); var vidcliente,viddestino:string; begin if combocliente.KeyValue=null then vidcliente:='%' else vidcliente:=combocliente.KeyValue; if combodestino.KeyValue=null then viddestino:='%' else viddestino:=combodestino.KeyValue; qpedidos.Prepare; qpedidos.ParamByName('IDCLIENTE').AsString:=vidcliente; qpedidos.ParamByName('IDDESTINO').AsString:=viddestino; qpedidos.ParamByName('FECHAINICIO').Asdate:=fdesde.Date; qpedidos.ParamByName('FECHAFIN').Asdate:=fhasta.Date; qpedidos.refresh; end; procedure Tpedidos.Button4Click(Sender: TObject); begin combocliente.KeyValue:=null; combodestino.KeyValue:=null; btfiltrar.click; end; procedure Tpedidos.Button7Click(Sender: TObject); begin traza_materiales2 := Ttraza_materiales2.Create(nil); try traza_materiales2.qpesadas.close; traza_materiales2.qpesadas.SQL.Clear; traza_materiales2.qpesadas.SQL.Add('select mat.idea,mat.idea2,mat.idaf,af.descripcion,mat.cantidad,mat.lote,e.documento as doc_compra,p.nombre as proveedor,:documento as documento from ea_materiales mat ,articulosf af,entradas_detalle ed,entradas e,proveedores p where'); traza_materiales2.qpesadas.SQL.Add('mat.idaf=af.id and mat.ide=af.idempresa and mat.idaf=ed.id_propio and mat.lote=ed.lote and ed.identrada=e.id and mat.ide=e.idempresa and e.idproveedor=p.id and'); traza_materiales2.qpesadas.SQL.Add(' (ide,idea,idea2) in (select idempresa,id,idea from ea_pesadas where pedidocliente=:documento) order by idaf,idea,idea2'); traza_materiales2.qpesadas.ParamByName('documento').AsString:=dtpedidosid.AsString; traza_materiales2.qpesadas.prepare; traza_materiales2.qpesadas.open; traza_materiales2.DBGrid2.Columns[0].Title.caption:='Pedido Cli'; traza_materiales2.showmodal(); finally traza_materiales2.Free; end; end; procedure Tpedidos.btpdcancelarClick(Sender: TObject); begin //panel10.Visible:=false; dtlinpedidos.cancel; //dtlinpedidos2.cancel; end; procedure Tpedidos.btpdmodificarClick(Sender: TObject); begin qvariedades.Close; qvariedades.Prepare; qvariedades.ParamByName('IDCLIENTE').AsInteger:=qclientesid.AsInteger; qvariedades.ParamByName('IDEMPRESA').AsInteger:=qclientesidempresa.AsInteger; qvariedades.Open; qpaises.Close; qpaises.Prepare; qpaises.ParamByName('IDCLIENTE').Asinteger:=qclientesid.AsInteger; qpaises.ParamByName('IDEMPRESA').AsInteger:=qclientesidempresa.AsInteger; qpaises.Open; dtlinpedidos.Edit; dlglineaspedido := Tdlglineaspedido.Create(nil); try dlglineaspedido.showmodal(); finally dlglineaspedido.Free; end; end; procedure Tpedidos.btpdnuevoClick(Sender: TObject); begin qvariedades.Close; qvariedades.Prepare; qvariedades.ParamByName('IDCLIENTE').AsInteger:=qclientesid.AsInteger; qvariedades.ParamByName('IDEMPRESA').AsInteger:=qclientesidempresa.AsInteger; qvariedades.Open; qpaises.Close; qpaises.Prepare; qpaises.ParamByName('IDCLIENTE').Asinteger:=qclientesid.AsInteger; qpaises.ParamByName('IDEMPRESA').AsInteger:=qclientesidempresa.AsInteger; qpaises.Open; dtlinpedidos.append; dlglineaspedido := Tdlglineaspedido.Create(nil); try dlglineaspedido.showmodal(); finally dlglineaspedido.Free; end; end; procedure Tpedidos.btpdborrarClick(Sender: TObject); begin case dm.PedirConfirmacion('¿Confirma que desea borrar esta línea de pedido?',true,true,false) of mrno:Abort; end; qaux.sql.clear; qaux.sql.add('update ea_pesadas set id_palet2='+''''+'TRIGGUER_OFF'+''''+',idpedido=null where idpedido='+dtlinpedidosid.asstring); qaux.ExecSQL; qaux.sql.clear; qaux.sql.add('delete from pedidosdetalle where id='+dtlinpedidosid.asstring); qaux.ExecSQL; dtlinpedidos.refresh; qenvasados.Refresh; qenvasados2.refresh; end; procedure Tpedidos.btpdguardarClick(Sender: TObject); begin { } dtlinpedidos.Close; dtlinpedidos.MasterSource:=dspedidos; dtlinpedidos.open;; //panel10.Visible:=false; end; procedure Tpedidos.DBEdit6Exit(Sender: TObject); begin dtpedidosfecha_elavoracion.Value:=strtodate(dbedit6.Text); end; procedure Tpedidos.DBGrid1TitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=qpedidos.SortType; qpedidos.SortedFields:=Column.FieldName; If st = stAscending then qpedidos.SortType:=stDescending else qpedidos.SortType:=stAscending; dsqpedidos.DataSet.First; end; procedure Tpedidos.DBGrid2DblClick(Sender: TObject); begin btpdmodificar.Click; end; procedure Tpedidos.DBGrid2DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if dtlinpedidoscantidadservida.Asinteger>dtlinpedidoscantidad.Asinteger then begin dbgrid2.Canvas.brush.Color := rojo; end; if dtlinpedidoscantidadservida.Asinteger=dtlinpedidoscantidad.Asinteger then begin dbgrid2.Canvas.brush.Color := verde; end; dbgrid2.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure Tpedidos.DBGrid7DblClick(Sender: TObject); begin base.mostrarpesadas(qenvasados2id.AsString);{ fpesadas := Tfpesadas.Create(nil); try if fpesadas.qpesadas.active=false then fpesadas.qpesadas.open; fpesadas.Edit1.Text:=; fpesadas.btbuscar.Click; fpesadas.ShowModal; finally fpesadas.Free; end; } end; procedure Tpedidos.dspedidosdestalle2StateChange(Sender: TObject); begin { if dtlinpedidos2.State in [dsedit,dsinsert] then begin btPdnuevo.enabled:=false; btPdborrar.enabled:=false; btPdmodificar.enabled:=false; //btPdguardar.enabled:=true; //btPdcancelar.enabled:=true; end; if dtlinpedidos2.State in [dsbrowse] then begin btPdnuevo.enabled:=true; btPdborrar.enabled:=true; btPdmodificar.enabled:=true; //btPdguardar.enabled:=false; //btPdcancelar.enabled:=false; end;} end; procedure Tpedidos.dspedidosdetalleDataChange(Sender: TObject; Field: TField); begin if dtlinpedidos.State in [dsbrowse] then begin if dtlinpedidosid.AsString<>'' then begin qenvasados2.Close; qenvasados2.SQL.Clear; qenvasados2.SQL.Add('select * from ea_pesadas where iddestino in (select id from almacenes where final=1) and idpedido='+dtlinpedidosid.asstring+' ORDER BY `id` DESC'); qenvasados2.open; end else begin qenvasados2.SQL.Clear; qenvasados2.SQL.Add('select * from ea_pesadas where iddestino in (select id from almacenes where final=1) and idpedido is not null ORDER BY `id` DESC'); qenvasados2.open; end; end; end; procedure Tpedidos.dspedidosdetalleStateChange(Sender: TObject); begin if dtlinpedidos.State in [dsedit,dsinsert] then begin btPdnuevo.enabled:=false; btPdborrar.enabled:=false; btPdmodificar.enabled:=false; //btPdguardar.enabled:=true; //btPdcancelar.enabled:=true; end; if dtlinpedidos.State in [dsbrowse] then begin btPdnuevo.enabled:=true; btPdborrar.enabled:=true; btPdmodificar.enabled:=true; //btPdguardar.enabled:=false; //btPdcancelar.enabled:=false; end; end; procedure Tpedidos.dspedidosStateChange(Sender: TObject); begin if dtpedidos.State in [dsedit,dsinsert] then begin Pdatospedidos.Enabled:=true; btPnuevo.enabled:=false; btPborrar.enabled:=false; btPmodificar.enabled:=false; btPguardar.enabled:=true; btPcancelar.enabled:=true; end; if dtpedidos.State in [dsbrowse] then begin Pdatospedidos.Enabled:=false; btPnuevo.enabled:=true; btPborrar.enabled:=true; btPmodificar.enabled:=true; btPguardar.enabled:=false; btPcancelar.enabled:=false; end; end; procedure Tpedidos.dsqcajasDataChange(Sender: TObject; Field: TField); begin qacabados.Close; qacabados.Prepare; qacabados.ParamByName('ENVASE').AsInteger:=qcajasid.AsInteger; qacabados.Open; end; procedure Tpedidos.dsqclientesDataChange(Sender: TObject; Field: TField); begin qdestinos.Close; qdestinos.Prepare; qdestinos.ParamByName('IDCLIENTE').AsInteger:=qclientesid.AsInteger; qdestinos.ParamByName('IDEMPRESA').AsInteger:=qclientesidempresa.AsInteger; qdestinos.Open; { qdestinos.SQL.Clear; qdestinos.SQL.Add('select * from clientes_destinos where activo=1 and idcliente='+qclientesid.AsString+' and idempresa='+qclientesidempresa.AsString+' order by descripcion'); qdestinos.Open;} end; procedure Tpedidos.dtlinpedidosBeforeDelete(DataSet: TDataSet); begin case dm.PedirConfirmacion('¿Confirma que desea borrar esta línea de pedido?',true,true,false) of mrno:Abort; end; end; procedure Tpedidos.dtpedidosBeforeDelete(DataSet: TDataSet); begin case dm.PedirConfirmacion('¿Confirma que desea borrar este pedido?',true,true,false) of mrno:Abort; end; end; procedure Tpedidos.btPguardarClick(Sender: TObject); var anyo,mes,dia:word; fecha:string; id:integer; begin decodedate(dtpedidosfecha_pedido.AsDateTime,anyo,mes,dia); fecha:=''''+inttostr(anyo)+'-'+inttostr(mes)+'-'+inttostr(dia)+''''; qaux.SQL.Clear; qaux.SQL.Add('select count(*) from pedidos'); qaux.Open; if qaux.Fields[0].AsInteger>0 then begin qaux.SQL.Clear; qaux.SQL.Add('select max(id)+1 from pedidos'); qaux.Open; id:=qaux.Fields[0].AsInteger; end; if dtpedidos.State in [dsinsert] then begin dtpedidoside.value:=dm.tempresaid.asinteger; dtpedidosid.Value:=id; dtpedidos.Post; qpedidos.Refresh; qpedidos.Locate('id',id,[locaseinsensitive]); qpedidos.Refresh; end; if dtpedidos.State in [dsedit] then begin id:=dtpedidosid.AsInteger; dtpedidos.Post; qpedidos.Refresh; qpedidos.Locate('id',id,[locaseinsensitive]); qpedidos.Refresh; end; pdatospedidos.Enabled:=false; end; procedure Tpedidos.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tpedidos.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is tdbgrid) then begin key:=','; end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tpedidos.FormShow(Sender: TObject); var vidcliente,viddestino:string; begin fdesde.Date:=date()-30; fhasta.Date:=date()+60; if combocliente.KeyValue=null then vidcliente:='%' else vidcliente:=combocliente.KeyValue; if combodestino.KeyValue=null then viddestino:='%' else viddestino:=combodestino.KeyValue; dm.tempresa.Open; qpedidos.Prepare; qpedidos.ParamByName('IDCLIENTE').AsString:=vidcliente; qpedidos.ParamByName('IDDESTINO').AsString:=viddestino; qpedidos.ParamByName('FECHAINICIO').Asdate:=fdesde.Date; qpedidos.ParamByName('FECHAFIN').Asdate:=fhasta.Date; qpedidos.Open; dtpedidos.Open; dtlinpedidos.Open; qclientes.Open; qdestinos.Open; qenvasados.Open; qenvasados2.Open; qcajas.Open; qacabados.Open; dtarticulosformato.Open; qclientescalidad.Open; dtarticulos.Open; qclientesacabados.Open; end; procedure Tpedidos.qpedidosBeforeOpen(DataSet: TDataSet); var filtrolocal:string; begin { if filtro<>'' then begin begin filtrolocal:=' and (c.nombre like('+filtro+') or d.descripcion like('+filtro+'))'; end; end; if filtro='' then begin filtrolocal:=''; end; qpedidos.SQL.Clear; qpedidos.SQL.Add('select p.*,c.nombre,d.descripcion from pedidos p,clientes c,clientes_destinos d where p.idcliente=c.id and p.iddestino=d.codigo and c.id=d.idcliente ' + filtrolocal +' order by fecha_pedido desc, id desc') } end; procedure Tpedidos.tbuscarenvasadoChange(Sender: TObject); begin if tbuscarenvasado.Text<>'' then begin qenvasados.Close; qenvasados.SQL.Clear; qenvasados.SQL.Add('select * from ea_pesadas where (idea=0 or iddestino in (select id from almacenes where final=1)) and id='+tbuscarenvasado.text+' and idpedido is null ORDER BY id,idea'); qenvasados.open; end else begin qenvasados.Close; qenvasados.SQL.Clear; qenvasados.SQL.Add('select * from ea_pesadas where (idea=0 or iddestino in (select id from almacenes where final=1)) and idpedido is null ORDER BY id,idea'); qenvasados.open; end; end; procedure Tpedidos.tbuscarenvasadoEnter(Sender: TObject); begin tbuscarenvasado.Text:=''; end; procedure Tpedidos.tbuscarenvasadoExit(Sender: TObject); begin if tbuscarenvasado.Text<>'' then btalnuevo.SetFocus; end; end. ======================================== FICHERO: fpresentaciones.pas ======================================== unit fpresentaciones; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ZDataset, Data.DB, ZAbstractRODataset, ZAbstractDataset, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.DBCtrls, Vcl.Mask,ShellApi; type Tpresentaciones = class(TForm) Panel2: TPanel; Panel5: TPanel; Label1: TLabel; todosarticulos: TCheckBox; tbuscar: TEdit; DBGrid1: TDBGrid; presentaciones: TZQuery; qpresentaciones: TZReadOnlyQuery; qpresentacionesid: TIntegerField; qpresentacioneside: TIntegerField; qpresentacionesdescripcion: TWideStringField; qpresentacionesactivo: TIntegerField; Panel1: TPanel; Panel6: TPanel; btfcancelar: TButton; btFmodificar: TButton; btFborrar: TButton; btFnuevo: TButton; btFguardar: TButton; btfduplicar: TButton; Panel4: TPanel; Panel8: TPanel; Panel9: TPanel; Panel10: TPanel; Button1: TButton; Button2: TButton; Panel11: TPanel; DBGrid2: TDBGrid; DBGrid3: TDBGrid; qarticulosfinal: TZReadOnlyQuery; dsqarticulosfinal: TDataSource; dsqpresentaciones: TDataSource; dspresentaciones: TDataSource; presentaciones_componentes: TZQuery; dspresentacionescomponentes: TDataSource; presentaciones_componenteside: TIntegerField; presentaciones_componentesidaf: TIntegerField; presentaciones_componentesidcfg: TIntegerField; presentaciones_componentescantidad: TFloatField; Panel3: TPanel; Panel12: TPanel; Panel13: TPanel; DBGrid4: TDBGrid; Panel14: TPanel; Button3: TButton; Button4: TButton; Panel15: TPanel; DBGrid5: TDBGrid; Panel16: TPanel; Label7: TLabel; tbuscarcomponentes: TEdit; qaux: TZReadOnlyQuery; Label2: TLabel; Label5: TLabel; DBEdit4: TDBEdit; presentacionesid: TIntegerField; presentacioneside: TIntegerField; presentacionesdescripcion: TWideStringField; presentacionesactivo: TIntegerField; DBCheckBox1: TDBCheckBox; qenvases: TZReadOnlyQuery; dsqenvases: TDataSource; qarticulosfinalidempresa: TIntegerField; qarticulosfinalid: TIntegerField; qarticulosfinalcodigo: TWideStringField; qarticulosfinaldescripcion: TWideStringField; dspresentaciones_envases: TDataSource; presentaciones_envases: TZQuery; OpenDialog1: TOpenDialog; SaveDialog1: TSaveDialog; qenvaseside: TIntegerField; qenvasesid: TIntegerField; qenvasescodigo: TWideStringField; qenvasesdescripcion: TWideStringField; DBText1: TDBText; presentaciones_componentescodigo: TWideStringField; presentaciones_componentesdescripcion: TWideStringField; presentaciones_envaseside: TIntegerField; presentaciones_envasesidcfg: TIntegerField; presentaciones_envasesidenv: TIntegerField; presentaciones_envasescodigo: TWideStringField; presentaciones_envasesdescripcion: TWideStringField; presentaciones_envasesimagen: TBlobField; presentaciones_envasesnomimagen: TWideStringField; presentaciones_envasesextension: TWideStringField; Label3: TLabel; DBEdit1: TDBEdit; qpresentacionesdescripcion2: TWideStringField; presentacionesdescripcion2: TWideStringField; Label4: TLabel; DBEdit2: TDBEdit; Label6: TLabel; DBEdit3: TDBEdit; presentacionescoste: TFloatField; presentacionespeso: TFloatField; presentaciones_componentescoste: TFloatField; presentaciones_componentespeso: TFloatField; Panel7: TPanel; Label8: TLabel; tbuscarenvases: TEdit; Label9: TLabel; Label10: TLabel; Label11: TLabel; Label12: TLabel; qarticulosfinalult_preciocompra: TFloatField; qarticulosfinalpeso: TFloatField; procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormShow(Sender: TObject); procedure Button2Click(Sender: TObject); procedure dspresentaciones_envasesDataChange(Sender: TObject; Field: TField); procedure btddescargarClick(Sender: TObject); procedure btdverClick(Sender: TObject); procedure imgfotoClick(Sender: TObject); procedure dspresentacionesStateChange(Sender: TObject); procedure btFnuevoClick(Sender: TObject); procedure btFborrarClick(Sender: TObject); procedure btFmodificarClick(Sender: TObject); procedure btFguardarClick(Sender: TObject); procedure tbuscarChange(Sender: TObject); procedure qpresentacionesBeforeOpen(DataSet: TDataSet); procedure tbuscarcomponentesChange(Sender: TObject); procedure qarticulosfinalBeforeOpen(DataSet: TDataSet); procedure Button1Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure btfcancelarClick(Sender: TObject); procedure dsqpresentacionesDataChange(Sender: TObject; Field: TField); procedure Button3Click(Sender: TObject); procedure presentaciones_componentesBeforePost(DataSet: TDataSet); procedure presentaciones_componentesAfterPost(DataSet: TDataSet); procedure DBEdit4Exit(Sender: TObject); procedure tbuscarenvasesChange(Sender: TObject); procedure qenvasesBeforeOpen(DataSet: TDataSet); procedure todosarticulosClick(Sender: TObject); private { Private declarations } public { Public declarations } var filtro:string; vertodos,vertodosmateriales,vertodosenvases,vertodaspresentaciones:integer; end; var presentaciones: Tpresentaciones; implementation {$R *.dfm} uses datos; procedure Tpresentaciones.btddescargarClick(Sender: TObject); var archivo:string; begin archivo:=presentaciones_envasesnomimagen.AsString; savedialog1.FileName:=archivo; savedialog1.Execute(); archivo:=savedialog1.FileName; presentaciones_envasesimagen.SaveToFile(archivo); end; procedure Tpresentaciones.btdverClick(Sender: TObject); var nomarchivo:string; begin nomarchivo:=presentaciones_envasesimagen.asstring; ShellExecute(Handle,nil,PChar('c:\agrigest\tmp\'+nomarchivo),'','',SW_SHOWNORMAL); end; procedure Tpresentaciones.btFborrarClick(Sender: TObject); begin presentaciones.delete; qpresentaciones.Close; qpresentaciones.open; end; procedure Tpresentaciones.btfcancelarClick(Sender: TObject); begin presentaciones.Cancel; end; procedure Tpresentaciones.btFguardarClick(Sender: TObject); var id:integer; begin filtro:='%'+tbuscar.Text+'%'; vertodos:=0; id:=presentacionesid.AsInteger; presentacioneside.value:=dm.tempresaid.AsInteger; presentaciones.Post; presentaciones.Close; presentaciones.MasterSource:=dsqpresentaciones; presentaciones.Open; qpresentaciones.Close; qpresentaciones.Open; qpresentaciones.Locate('id',id,[locaseinsensitive,lopartialkey]); end; procedure Tpresentaciones.btFmodificarClick(Sender: TObject); begin presentaciones.Edit; dbedit4.SetFocus; end; procedure Tpresentaciones.btFnuevoClick(Sender: TObject); begin presentaciones.MasterSource:=nil; presentaciones.Append; dbedit4.SetFocus; end; procedure Tpresentaciones.Button1Click(Sender: TObject); begin presentaciones_componentes.Delete; presentaciones_componentes.Refresh; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('select sum(peso),sum(coste) from configuraciones_detalle where ide='+presentacioneside.Asstring+' and idcfg='+presentacionesid.Asstring); qaux.open; presentaciones.Edit; presentacionespeso.Value:=qaux.Fields[0].AsFloat; presentacionescoste.Value:=qaux.Fields[1].AsFloat; presentaciones.post; presentaciones_componentes.Close; presentaciones_componentes.open; end; procedure Tpresentaciones.Button2Click(Sender: TObject); var cantidad,ide,idcfg,idaf:integer; begin qaux.SQL.Clear; qaux.SQL.Add('select ide,idaf,idcfg,cantidad from configuraciones_detalle where ide='+qpresentacioneside.Asstring+' and idcfg='+qpresentacionesid.Asstring+' and idaf='+qarticulosfinalid.Asstring); qaux.Open; if qaux.RecordCount>0 then begin cantidad:=qaux.Fields[3].AsInteger; ide:=qaux.Fields[0].AsInteger; idaf:=qaux.Fields[1].AsInteger; idcfg:=qaux.Fields[2].AsInteger; presentaciones_componentes.Locate('ide;idcfg;idaf',vararrayof([ide,idcfg,idaf]),[locaseinsensitive]); presentaciones_componentes.edit; presentaciones_componentescantidad.Value:=cantidad+1; presentaciones_componentespeso.Value:=qarticulosfinalpeso.Asfloat; presentaciones_componentescoste.Value:=qarticulosfinalult_preciocompra.Asfloat; presentaciones_componentes.Post; end else begin presentaciones_componentes.Append; presentaciones_componenteside.Value:=presentacioneside.AsInteger; presentaciones_componentesidaf.Value:=qarticulosfinalid.asinteger; presentaciones_componentescodigo.Value:=qarticulosfinalcodigo.AsString; presentaciones_componentescoste.Value:=qarticulosfinalult_preciocompra.Asfloat; presentaciones_componentespeso.Value:=qarticulosfinalpeso.Asfloat; presentaciones_componentesdescripcion.Value:=qarticulosfinaldescripcion.AsString; presentaciones_componentesidcfg.Value:=presentacionesid.AsInteger; presentaciones_componentescantidad.Value:=1; presentaciones_componentes.Post; end; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('select sum(peso),sum(coste) from configuraciones_detalle where ide='+presentacioneside.Asstring+' and idcfg='+presentacionesid.Asstring); qaux.open; presentaciones.Edit; presentacionespeso.Value:=qaux.Fields[0].AsFloat; presentacionescoste.Value:=qaux.Fields[1].AsFloat; presentaciones.post; presentaciones_componentes.Close; presentaciones_componentes.open; end; procedure Tpresentaciones.Button3Click(Sender: TObject); begin presentaciones_envases.Delete; qenvases.Close; qenvases.sql.clear; qenvases.SQL.Add('select ide,id,codigo,descripcion from articulos_almacen where activo=1 and envase_venta=1 and (ide,id) not in (select ide,idenv from configuraciones_envases where idcfg='+qpresentacionesid.asstring+') order by descripcion asc'); qenvases.Open; end; procedure Tpresentaciones.Button4Click(Sender: TObject); begin presentaciones_envases.append; presentaciones_envaseside.Value:=qpresentacioneside.asinteger; presentaciones_envasesidcfg.Value:=qpresentacionesid.asinteger; presentaciones_envasesidenv.Value:=qenvasesid.asinteger; presentaciones_envasescodigo.Value:=qenvasescodigo.asstring; presentaciones_envasesdescripcion.Value:=qenvasesdescripcion.asstring; presentaciones_envases.Post; qenvases.Close; qenvases.sql.clear; qenvases.SQL.Add('select ide,id,codigo,descripcion from articulos_almacen where activo=1 and palet=0 and (ide,id) not in (select ide,idenv from configuraciones_envases where idcfg='+qpresentacionesid.asstring+') order by descripcion asc'); qenvases.Open; end; procedure Tpresentaciones.DBEdit4Exit(Sender: TObject); begin presentacionesdescripcion.Value:=presentacionesdescripcion2.AsString; end; procedure Tpresentaciones.dspresentacionesStateChange(Sender: TObject); begin if presentaciones.State in [dsedit,dsinsert] then begin Panel3.Enabled:=true; panel12.Visible:=false; panel8.Visible:=false; btfnuevo.enabled:=false; btfmodificar.enabled:=false; btfguardar.enabled:=true; btfcancelar.enabled:=true; end; if presentaciones.State in [dsbrowse] then begin Panel3.Enabled:=false; panel12.Visible:=true; panel8.Visible:=true; btfnuevo.enabled:=true; btfmodificar.enabled:=true; btfguardar.enabled:=false; btfcancelar.enabled:=false; end; end; procedure Tpresentaciones.dspresentaciones_envasesDataChange(Sender: TObject; Field: TField); var img:TPicture; ext,nomarchivo:string; SearchRec: TSearchRec; begin {If not DirectoryExists('c:\agrigest\tmp') then CreateDir('c:\agrigest\tmp'); if presentaciones_envases.State in [dsbrowse] then begin if FindFirst('c:\agrigest\tmp\*.*', faAnyFile, SearchRec) = 0 then repeat Deletefile('c:\agrigest\tmp\'+SearchRec.name); until (FindNext(SearchRec) <> 0); FindClose(SearchRec); if presentaciones_envases.RecordCount>0 then begin imgfoto.Picture:=nil; ext:=presentaciones_envasesextension.AsString; nomarchivo:=presentaciones_envasesnomimagen.asstring; if nomarchivo<>'' then presentaciones_envasesimagen.savetofile('c:\agrigest\tmp\'+nomarchivo); if (ext='.jpg') or (ext='.jpeg') or (ext='.bmp') or (ext='.png') then begin imgfoto.Picture:=nil; if nomarchivo<>'' then imgfoto.Picture.LoadFromFile('c:\agrigest\tmp\'+nomarchivo); imgfoto.Visible:=true; btdver.Visible:=false; end else begin imgfoto.Visible:=false; btdver.Visible:=true; end; end; if presentaciones_envases.RecordCount=0 then begin imgfoto.Visible:=false; btdver.Visible:=false; imgfoto.Picture:=nil; end; end; } end; procedure Tpresentaciones.dsqpresentacionesDataChange(Sender: TObject; Field: TField); begin if qpresentaciones.RecordCount>0 then begin panel12.Visible:=true; panel8.Visible:=true; qenvases.Close; qenvases.sql.clear; qenvases.SQL.Add('select ide,id,codigo,descripcion from articulos_almacen where activo=1 and palet=0 and (ide,id) not in (select ide,idenv from configuraciones_envases where idcfg='+qpresentacionesid.asstring+') order by descripcion asc'); qenvases.Open; end else begin panel12.Visible:=false; panel8.Visible:=false; end; end; procedure Tpresentaciones.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tpresentaciones.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is tdbgrid) then begin key:=','; end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tpresentaciones.FormShow(Sender: TObject); begin vertodaspresentaciones:=0; qpresentaciones.Open; presentaciones.Open; qarticulosfinal.Open; presentaciones_componentes.Open; qenvases.Open; presentaciones_envases.open; end; procedure Tpresentaciones.imgfotoClick(Sender: TObject); var ext,nomarchivo:string; begin if opendialog1.Execute then begin try finally presentaciones_envases.edit; ext:= ExtractFileExt(opendialog1.FileName); nomarchivo:= extractfilename(opendialog1.FileName); presentaciones_envasesnomimagen.Value:=nomarchivo; presentaciones_envasesextension.Value:=ext; presentaciones_envasesimagen.LoadFromFile(opendialog1.FileName); presentaciones_envases.Post; end; end; end; procedure Tpresentaciones.presentaciones_componentesAfterPost( DataSet: TDataSet); begin qaux.close; qaux.SQL.Clear; qaux.SQL.Add('select sum(peso),sum(coste) from configuraciones_detalle where ide='+presentacioneside.Asstring+' and idcfg='+presentacionesid.Asstring); qaux.open; presentaciones.Edit; presentacionespeso.Value:=qaux.Fields[0].AsFloat; presentacionescoste.Value:=qaux.Fields[1].AsFloat; presentaciones.post; end; procedure Tpresentaciones.presentaciones_componentesBeforePost( DataSet: TDataSet); begin qarticulosfinal.Locate('id',presentaciones_componentesidaf.AsInteger,[locaseinsensitive]); presentaciones_componentespeso.Value:=qarticulosfinalpeso.Asfloat*presentaciones_componentescantidad.Asinteger; presentaciones_componentescoste.Value:=qarticulosfinalult_preciocompra.Asfloat*presentaciones_componentescantidad.Asinteger; end; procedure Tpresentaciones.qarticulosfinalBeforeOpen(DataSet: TDataSet); var filtrolocal:string; begin if filtro<>'' then begin begin filtrolocal:=' where descripcion like('+''''+filtro+''''+') or codigo like('+''''+filtro+''''+') or id like('+''''+filtro+''''+')'; end; if vertodosmateriales=0 then begin begin filtrolocal:=' where (descripcion like('+''''+filtro+''''+') or codigo like('+''''+filtro+''''+') or id like('+''''+filtro+''''+')'; filtrolocal:=filtrolocal+') and activo=1 '; end; end; end; if filtro='' then begin filtrolocal:=''; if vertodosmateriales=0 then begin filtrolocal:=' where activo=1 '; end; end; qarticulosfinal.SQL.Clear; qarticulosfinal.SQL.Add('select * from articulosf ' + filtrolocal +' order by descripcion') end; procedure Tpresentaciones.qenvasesBeforeOpen(DataSet: TDataSet); var filtrolocal:string; begin if filtro<>'' then begin begin filtrolocal:=' where descripcion like('+''''+filtro+''''+') or codigo like('+''''+filtro+''''+') or id like('+''''+filtro+''''+')'; end; if vertodosenvases=0 then begin begin filtrolocal:=' where (descripcion like('+''''+filtro+''''+') or codigo like('+''''+filtro+''''+') or id like('+''''+filtro+''''+')'; filtrolocal:=filtrolocal+') and activo=1 '; end; end; end; if filtro='' then begin filtrolocal:=''; if vertodosenvases=0 then begin filtrolocal:=' where activo=1 '; end; end; qenvases.SQL.Clear; qenvases.SQL.Add('select ide,id,codigo,descripcion from articulos_almacen ' + filtrolocal +' order by descripcion'); end; procedure Tpresentaciones.qpresentacionesBeforeOpen(DataSet: TDataSet); var filtrolocal:string; begin if filtro<>'' then begin begin filtrolocal:=' where descripcion like('+''''+filtro+''''+') or id like('+''''+filtro+''''+')'; end; if vertodaspresentaciones=0 then begin filtrolocal:=' where (descripcion like('+''''+filtro+''''+') or id like('+''''+filtro+''''+')'; filtrolocal:=filtrolocal+') and activo=1 '; end else begin filtrolocal:=' where (descripcion like('+''''+filtro+''''+') or id like('+''''+filtro+''''+')'; filtrolocal:=filtrolocal+')'; end end; if filtro='' then begin filtrolocal:=''; if vertodaspresentaciones=0 then begin filtrolocal:=' where activo=1 '; end else begin filtrolocal:=''; end end; qpresentaciones.SQL.Clear; qpresentaciones.SQL.Add('select * from configuraciones ' + filtrolocal +' order by descripcion') end; procedure Tpresentaciones.tbuscarChange(Sender: TObject); begin filtro:='%'+tbuscar.Text+'%'; vertodaspresentaciones:=0; qpresentaciones.Close; qpresentaciones.open; end; procedure Tpresentaciones.tbuscarcomponentesChange(Sender: TObject); begin filtro:='%'+tbuscarcomponentes.Text+'%'; vertodosmateriales:=0; qarticulosfinal.Close; qarticulosfinal.open; end; procedure Tpresentaciones.tbuscarenvasesChange(Sender: TObject); begin filtro:='%'+tbuscarenvases.Text+'%'; vertodosenvases:=0; qenvases.Close; qenvases.open; end; procedure Tpresentaciones.todosarticulosClick(Sender: TObject); begin if todosarticulos.Checked=true then begin vertodaspresentaciones:=1; qpresentaciones.Close; qpresentaciones.Open; end else begin vertodaspresentaciones:=0; qpresentaciones.Close; qpresentaciones.Open; end; end; end. ======================================== FICHERO: fproductores.pas ======================================== unit fproductores; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.DBCtrls, Vcl.Mask, Vcl.ComCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, ZDataset, Data.DB, ZAbstractRODataset, ZAbstractDataset,Excel2000,ComObj,ShellApi, frxClass, frxExportBaseDialog, frxExportPDF, frxDBSet, frxCross; type TSociosProductores = class(TForm) Panel1: TPanel; Panel2: TPanel; Panel5: TPanel; Label1: TLabel; todosclientes: TCheckBox; tbuscar: TEdit; DBGrid1: TDBGrid; Panel3: TPanel; Panel4: TPanel; DatosProductores: TPageControl; TDatosClientes: TTabSheet; Panel14: TPanel; Label10: TLabel; Label11: TLabel; Label12: TLabel; Label13: TLabel; Label14: TLabel; Label15: TLabel; Label2: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; Label22: TLabel; Label23: TLabel; DBCheckBox2: TDBCheckBox; DBEdit1: TDBEdit; DBEdit10: TDBEdit; DBEdit11: TDBEdit; DBEdit12: TDBEdit; DBEdit13: TDBEdit; DBEdit3: TDBEdit; DBEdit4: TDBEdit; DBEdit5: TDBEdit; DBEdit6: TDBEdit; DBEdit7: TDBEdit; DBEdit8: TDBEdit; DBEdit9: TDBEdit; DBMemo1: TDBMemo; DBEdit21: TDBEdit; DBEdit22: TDBEdit; Panel6: TPanel; Label37: TLabel; BtScancelar: TButton; btSmodificar: TButton; BtSborrar: TButton; BtSNuevo: TButton; BtSguardar: TButton; TDatosDestinos: TTabSheet; Panel12: TPanel; Label36: TLabel; btPcancelar: TButton; btPmodificar: TButton; btPborrar: TButton; btPnuevo: TButton; btPguardar: TButton; Panel15: TPanel; Panel19: TPanel; Detallesproductores: TPageControl; TPedidos: TTabSheet; Panel8: TPanel; Label34: TLabel; TAlbaranes: TTabSheet; Panel10: TPanel; dsqsocios: TDataSource; socios: TZQuery; qsocios: TZReadOnlyQuery; dssocios: TDataSource; qsociosid: TIntegerField; qsocioside: TIntegerField; parcelas: TZQuery; dsparcelas: TDataSource; dsqenvasados: TDataSource; dsqparcelas: TDataSource; qparcelas: TZReadOnlyQuery; Panel147: TPanel; DBGrid20: TDBGrid; Panel148: TPanel; Label298: TLabel; todasparcelas: TCheckBox; tbuscarparcelas: TEdit; dsqcampanyas: TDataSource; qcampanyas: TZReadOnlyQuery; qcampanyasid: TIntegerField; qcampanyasdescripcion: TWideStringField; qcampanyasfechainicio: TDateField; qcampanyasfechafin: TDateField; qaux: TZReadOnlyQuery; Button16: TButton; Button15: TButton; sociosid: TIntegerField; socioside: TIntegerField; sociosnif: TWideStringField; sociosnombre: TWideStringField; sociosnombre_corto: TWideStringField; sociosdireccion: TWideStringField; sociospoblacion: TWideStringField; socioscp: TWideStringField; sociosprovincia: TWideStringField; sociostelefono: TWideStringField; sociosmovil: TWideStringField; sociosfax: TWideStringField; sociosemail: TWideStringField; sociospersonacontacto: TWideStringField; sociosccontable: TWideStringField; sociosobservaciones: TWideStringField; sociosactivo: TIntegerField; qsociosnombre_corto: TWideStringField; dsqsocios2: TDataSource; qsocios2: TZReadOnlyQuery; qsocios2id: TIntegerField; qsocios2ide: TIntegerField; qsocios2nombre_corto: TWideStringField; parcelascodpar: TWideStringField; parcelasempresa: TIntegerField; parcelasnombre: TWideStringField; parcelasvariedad: TWideStringField; parcelasnum_plantas: TIntegerField; parcelasfecha_plantacion: TDateField; parcelasmarco_plantacion: TWideStringField; parcelasnum_goteros: TFloatField; parcelasgastosgenerales: TIntegerField; parcelasref_catastro: TWideStringField; parcelassigpac_prov: TIntegerField; parcelassigpac_muni: TIntegerField; parcelassigpac_agre: TIntegerField; parcelassigpac_zona: TIntegerField; parcelassigpac_poli: TIntegerField; parcelassigpac_pacr: TIntegerField; parcelasx: TWideStringField; parcelasy: TWideStringField; parcelasdatum: TWideStringField; parcelashuso: TIntegerField; parcelaspropiedad: TWideStringField; parcelasactivo: TIntegerField; parcelasseleccionado: TIntegerField; parcelassuperficie: TFloatField; parcelasest_meteo: TWideStringField; parcelascoste_kg_ref: TFloatField; parcelasactivo_almacen: TIntegerField; parcelasporc_desperdicio: TFloatField; parcelasporc_merma: TFloatField; parcelases_centrotrabajo: TIntegerField; parcelassigpac_recinto: TIntegerField; parcelaspie_planta: TWideStringField; parcelasnumero: TWideStringField; parcelastiene_gg: TIntegerField; parcelastiene_dop: TIntegerField; parcelasc_calidad: TIntegerField; parcelasc_espcliente: TIntegerField; parcelasc_etiquetado: TIntegerField; parcelassello_gg: TWideStringField; parcelassello_dop: TWideStringField; parcelassello_igp: TWideStringField; parcelastiene_igp: TIntegerField; parcelastiene_ifs: TIntegerField; parcelassello_ifs: TWideStringField; parcelaspropietario: TIntegerField; qparcelasempresa: TIntegerField; qparcelascodpar: TWideStringField; qparcelasnombre: TWideStringField; qparcelasvariedad: TWideStringField; qparcelaspropietario: TIntegerField; qcultivos: TZReadOnlyQuery; dsqcultivos: TDataSource; qcultivosidempresa: TIntegerField; qcultivosid: TWideStringField; qcultivosvariedad: TWideStringField; qcultivosdescripcion: TWideStringField; qcultivosobservaciones: TWideStringField; qcultivosimagen: TBlobField; qcultivosEAN: TWideStringField; qcultivosbasculas: TIntegerField; qcultivosmesas: TIntegerField; qcultivosactivo: TIntegerField; qcultivosusar_precio_parcela: TIntegerField; qcultivosdesechos: TIntegerField; qcultivosgenerico: TWideStringField; qcultivoscompuesto: TIntegerField; DBGrid46: TDBGrid; DBGrid69: TDBGrid; dsqinfsalidas: TDataSource; qinfenvasados: TZQuery; qinfenvasadosid: TIntegerField; qinfenvasadosfecha: TDateField; qinfenvasadosfechatrabajo: TDateField; qinfenvasadosparcela: TWideStringField; qinfenvasadosmprima: TWideStringField; qinfenvasadosmprima_p: TWideStringField; qinfenvasadosid_envase: TWideStringField; qinfenvasadosnum_envases: TIntegerField; qinfenvasadoscliente: TWideStringField; qinfenvasadosciudad: TWideStringField; qinfenvasadospeso_neto: TFloatField; qinfenvasadospeso_neto_teorico: TFloatField; qinfenvasadospeso_medio: TFloatField; qinfenvasadostemperatura: TFloatField; qinfenvasadoslote: TIntegerField; qinfenvasadosidalbaran: TIntegerField; dsqinfentradas: TDataSource; qinfentradas: TZQuery; qinfentradasid: TIntegerField; qinfentradasfecha: TDateField; qinfentradasfechatrabajo: TDateField; qinfentradasparcela: TWideStringField; qinfentradasmprima: TWideStringField; qinfentradasid_envase: TWideStringField; qinfentradasnum_envases: TIntegerField; qinfentradascliente: TWideStringField; qinfentradasciudad: TWideStringField; qinfentradaspeso_neto: TFloatField; qinfentradaspeso_neto_teorico: TFloatField; qinfentradaspeso_medio: TFloatField; qinfentradastemperatura: TFloatField; qinfentradaslote: TIntegerField; qinfentradasidalbaran: TIntegerField; qinfentradasmprima_p: TWideStringField; Label17: TLabel; DBEdit2: TDBEdit; socioscodproductor: TWideStringField; sociospais: TWideStringField; parcelas_recintos: TZQuery; parcelas_recintosid: TIntegerField; parcelas_recintoscodpar: TWideStringField; parcelas_recintosempresa: TIntegerField; parcelas_recintosref_catastro: TWideStringField; parcelas_recintossigpac_prov: TIntegerField; parcelas_recintossigpac_muni: TIntegerField; parcelas_recintossigpac_agre: TIntegerField; parcelas_recintossigpac_zona: TIntegerField; parcelas_recintossigpac_poli: TIntegerField; parcelas_recintossigpac_pacr: TIntegerField; parcelas_recintosx: TWideStringField; parcelas_recintosy: TWideStringField; parcelas_recintosdatum: TWideStringField; parcelas_recintoshuso: TIntegerField; parcelas_recintossuperficie: TFloatField; parcelas_recintossigpac_recinto: TIntegerField; DBGrid2: TDBGrid; dsparcelasrecintos: TDataSource; Panel7: TPanel; Label139: TLabel; Label140: TLabel; Label141: TLabel; Label142: TLabel; Label143: TLabel; Label144: TLabel; Label145: TLabel; Label159: TLabel; Label197: TLabel; Label198: TLabel; Label201: TLabel; Label208: TLabel; Label299: TLabel; Label16: TLabel; DBEdit79: TDBEdit; DBEdit80: TDBEdit; DBEdit82: TDBEdit; DBEdit83: TDBEdit; DBEdit84: TDBEdit; DBEdit85: TDBEdit; DBComboBox1: TDBComboBox; DBCheckBox19: TDBCheckBox; DBEdit104: TDBEdit; DBEdit105: TDBEdit; DBEdit108: TDBEdit; DBEdit115: TDBEdit; DBCheckBox27: TDBCheckBox; DBCheckBox28: TDBCheckBox; DBCheckBox29: TDBCheckBox; DBCheckBox32: TDBCheckBox; DBCheckBox39: TDBCheckBox; DBEdit117: TDBEdit; DBEdit118: TDBEdit; DBEdit119: TDBEdit; DBCheckBox41: TDBCheckBox; DBLookupComboBox15: TDBLookupComboBox; DBCheckBox42: TDBCheckBox; DBEdit81: TDBEdit; DBCheckBox17: TDBCheckBox; DBLookupComboBox1: TDBLookupComboBox; Button3: TButton; SaveDialog1: TSaveDialog; TabSheet1: TTabSheet; DBGrid4: TDBGrid; Panel11: TPanel; Label20: TLabel; dsqestadisticas: TDataSource; DBCheckBox1: TDBCheckBox; DBEdit14: TDBEdit; parcelastiene_brc: TIntegerField; parcelassello_brc: TWideStringField; Panel13: TPanel; Label21: TLabel; combocampanyas: TDBLookupComboBox; btactualizar: TButton; Button9: TButton; RadioGroup1: TRadioGroup; tkparcela: TRadioButton; tkmprima: TRadioButton; dbaestadisticas: TfrxDBDataset; dbaenvasados: TfrxDBDataset; dbaentradas: TfrxDBDataset; frxPDFExport1: TfrxPDFExport; infproductores: TfrxReport; frxCrossObject1: TfrxCrossObject; dbdesechos: TfrxDBDataset; dbpropietarios: TfrxDBDataset; tkmprimaenv: TRadioButton; qestadisticas_mpe: TZReadOnlyQuery; Edit1: TEdit; Label18: TLabel; qentradasdetalle: TZReadOnlyQuery; qenvasadosdetalle: TZReadOnlyQuery; qdesechosdetalle: TZReadOnlyQuery; Label19: TLabel; tdesechos: TTabSheet; DBGrid3: TDBGrid; Panel9: TPanel; Label3: TLabel; qestadisticas_mpeMateriaPrima: TWideStringField; qestadisticas_mpeEnvase: TWideStringField; qestadisticas_mpeKgRecolectados: TFloatField; qestadisticas_mpeKgEnvasados: TFloatField; qestadisticas_mpeKgFacturables: TFloatField; qestadisticas_mpeKgFacturados: TFloatField; qestadisticas_mpeDesechos: TFloatField; qestadisticas_mpeIniciorecolección: TDateField; qestadisticas_mpeFinrecolección: TDateField; qestadisticas_mpeMermaVenta: TFloatField; qentradasdetalleId: TIntegerField; qentradasdetalleLote: TIntegerField; qentradasdetalleFecha: TDateField; qentradasdetalleParcela: TWideStringField; qentradasdetalleMatériaPrima: TWideStringField; qentradasdetalleEnvase: TWideStringField; qentradasdetalleNºEnvases: TIntegerField; qentradasdetalleUbicaciónactual: TWideStringField; qentradasdetallePesoneto: TFloatField; qentradasdetallePesoFacturable: TFloatField; qenvasadosdetalleId: TIntegerField; qenvasadosdetalleLote: TIntegerField; qenvasadosdetalleFecha: TDateField; qenvasadosdetalleParcela: TWideStringField; qenvasadosdetalleMatériaPrima: TWideStringField; qenvasadosdetalleEnvase: TWideStringField; qenvasadosdetalleNºEnvases: TIntegerField; qenvasadosdetalleUbicaciónactual: TWideStringField; qenvasadosdetallePesoneto: TFloatField; qenvasadosdetallePesoFacturable: TFloatField; qdesechosdetalleId: TIntegerField; qdesechosdetalleLote: TIntegerField; qdesechosdetalleFecha: TDateField; qdesechosdetalleParcela: TWideStringField; qdesechosdetalleMatériaPrima: TWideStringField; qdesechosdetalleEnvase: TWideStringField; qdesechosdetalleNºEnvases: TIntegerField; qdesechosdetalleUbicaciónactual: TWideStringField; qdesechosdetallePesoneto: TFloatField; qdesechosdetallePesoFacturable: TFloatField; dsqdesechos: TDataSource; dsqentradas: TDataSource; qestadisticas_p: TZReadOnlyQuery; qestadisticas_mp: TZReadOnlyQuery; qestadisticas_mpMateriaPrima: TWideStringField; qestadisticas_mpKgRecolectados: TFloatField; qestadisticas_mpKgEnvasados: TFloatField; qestadisticas_mpKgFacturables: TFloatField; qestadisticas_mpKgFacturados: TFloatField; qestadisticas_mpDesechos: TFloatField; qestadisticas_mpIniciorecolección: TDateField; qestadisticas_mpFinrecolección: TDateField; qestadisticas_mpMermaVenta: TFloatField; qestadisticas_mpMermaRecoleccion: TFloatField; qestadisticas_pParcela: TWideStringField; qestadisticas_pKgRecolectados: TFloatField; qestadisticas_pKgEnvasados: TFloatField; qestadisticas_pKgFacturables: TFloatField; qestadisticas_pKgFacturados: TFloatField; qestadisticas_pDesechos: TFloatField; qestadisticas_pIniciorecolección: TDateField; qestadisticas_pFinrecolección: TDateField; qestadisticas_pmermaVenta: TFloatField; qestadisticas_pMermaRecoleccion: TFloatField; Button7: TButton; tdesde: TDateTimePicker; thasta: TDateTimePicker; Label24: TLabel; Label25: TLabel; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); procedure BtSNuevoClick(Sender: TObject); procedure BtSborrarClick(Sender: TObject); procedure btSmodificarClick(Sender: TObject); procedure BtSguardarClick(Sender: TObject); procedure BtScancelarClick(Sender: TObject); procedure dssociosStateChange(Sender: TObject); procedure Button15Click(Sender: TObject); procedure Button16Click(Sender: TObject); procedure tbuscarChange(Sender: TObject); procedure qsociosBeforeOpen(DataSet: TDataSet); procedure todosclientesClick(Sender: TObject); procedure btPnuevoClick(Sender: TObject); procedure btPmodificarClick(Sender: TObject); procedure btPborrarClick(Sender: TObject); procedure btPcancelarClick(Sender: TObject); procedure btPguardarClick(Sender: TObject); procedure dsparcelasStateChange(Sender: TObject); procedure tbuscarparcelasChange(Sender: TObject); procedure qparcelasBeforeOpen(DataSet: TDataSet); procedure Button3Click(Sender: TObject); procedure btJexcelClick(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure btactualizarClick(Sender: TObject); procedure tkparcelaClick(Sender: TObject); procedure dsqsociosDataChange(Sender: TObject; Field: TField); procedure Button9Click(Sender: TObject); procedure qestadisticas_mpCalcFields(DataSet: TDataSet); procedure qestadisticas_pCalcFields(DataSet: TDataSet); procedure Button7Click(Sender: TObject); procedure qestadisticas_mpeCalcFields(DataSet: TDataSet); procedure Button6Click(Sender: TObject); procedure dsqcampanyasDataChange(Sender: TObject; Field: TField); private { Private declarations } public { Public declarations } procedure AppMessage(var Msg: Tmsg; var Handled:Boolean); procedure ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar = nil); var filtro,tparcelascodigo:string; tsociosid,tsocioside,vertodos:integer; end; var SociosProductores: TSociosProductores; implementation {$R *.dfm} uses datos, pesadas; procedure TSociosProductores.btJexcelClick(Sender: TObject); var archivo:string; begin savedialog1.FileName:='ENTRADAS CAMPO.xls'; savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'ENTRADAS CAMPO',DBGRID46); finally showmessage('Los datos han sido exportados correctamente a '+archivo); end; end; procedure TSociosProductores.btPborrarClick(Sender: TObject); begin parcelas.Delete; qparcelas.Refresh; qparcelas.First end; procedure TSociosProductores.btPcancelarClick(Sender: TObject); begin parcelas.cancel; parcelas.refresh; end; procedure TSociosProductores.btPguardarClick(Sender: TObject); begin tparcelascodigo:=parcelascodpar.asstring; tsociosid:=parcelaspropietario.AsInteger; parcelas.post; qsocios.close; qsocios.open; qsocios.Locate('id',tsociosid,[locaseinsensitive]); qparcelas.Close; qparcelas.Open; qparcelas.Locate('codpar',tparcelascodigo,[locaseinsensitive]); qsocios2.close; qsocios2.open; end; procedure TSociosProductores.btPmodificarClick(Sender: TObject); begin parcelas.edit; dbedit79.SetFocus; end; procedure TSociosProductores.btPnuevoClick(Sender: TObject); begin parcelas.append; parcelaspropietario.Value:=qsociosid.AsInteger; dbedit79.SetFocus; end; procedure TSociosProductores.BtSborrarClick(Sender: TObject); begin socios.Delete; end; procedure TSociosProductores.BtScancelarClick(Sender: TObject); begin socios.cancel; qsocios.Refresh; socios.MasterSource:=dsqsocios; end; procedure TSociosProductores.BtSguardarClick(Sender: TObject); begin socioside.Value:=tsocioside; if socios.state in [dsedit,dsinsert] then socios.Post; qsocios.close; qsocios.open; qsocios.Locate('id',tsociosid,[locaseinsensitive,lopartialkey]); qsocios2.close; qsocios2.open; qparcelas.Close; qparcelas.Open; socios.MasterSource:=dsqsocios; end; procedure TSociosProductores.btSmodificarClick(Sender: TObject); begin tsociosid:=qsociosid.asinteger; socios.MasterSource:=nil; socios.edit; dbedit1.SetFocus; end; procedure TSociosProductores.BtSNuevoClick(Sender: TObject); begin qaux.SQL.Clear; qaux.SQL.Add('select max(id)+1 from propietarios'); qaux.Open; socios.MasterSource:=nil; socios.append; dbedit1.SetFocus; if qaux.Fields[0].Asinteger>0 then begin dbedit1.Text:=qaux.Fields[0].AsString; end else begin dbedit1.Text:='0'; end; end; procedure TSociosProductores.Button15Click(Sender: TObject); var url:array[0..255] of WideChar; cadena,x,y:string; begin x:=parcelasx.Asstring; y:=parcelasy.Asstring; stringreplace(x,'.',',',[rfReplaceAll]); stringreplace(y,',','.',[rfReplaceAll]); cadena:='https://www.google.es/maps/place/'+x+','+y; stringtowidechar(cadena,url,256); ShellExecute(Handle,'open','iexplore.exe',URL,nil,SW_NORMAL); end; procedure TSociosProductores.Button16Click(Sender: TObject); var url:array[0..255] of WideChar; cadena:string; begin cadena:='http://sigpac.mapa.es/fega/visor/?provincia='+parcelas_recintossigpac_prov.AsString+'&municipio='+parcelas_recintossigpac_muni.AsString+'&AGREGADO='+parcelas_recintossigpac_agre.AsString+'&zona='+parcelas_recintossigpac_zona.AsString+'&poligono='+parcelas_recintossigpac_poli.AsString+'&parcela='+parcelas_recintossigpac_pacr.AsString+'&recinto='+parcelas_recintossigpac_recinto.AsString; stringtowidechar(cadena,url,256); ShellExecute(Handle,'open','iexplore.exe',URL,nil,SW_NORMAL); end; procedure TSociosProductores.Button2Click(Sender: TObject); var archivo:string; begin savedialog1.FileName:='ENVASADOS.xls'; savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'ENVASADOS',DBGRID69); finally showmessage('Los datos han sido exportados correctamente a '+archivo); end; end; procedure TSociosProductores.Button3Click(Sender: TObject); begin parcelas_recintos.Delete; end; procedure TSociosProductores.Button5Click(Sender: TObject); var archivo:string; begin savedialog1.FileName:='ESTADISTICAS DE '+sociosnombre.AsString+'.xlsx'; savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'ESTADISTICAS',DBGRID4); finally showmessage('Los datos han sido exportados correctamente a '+archivo); end; end; procedure TSociosProductores.Button6Click(Sender: TObject); begin { infproductoresran.Datasource:=dsalbaranes; infdetallealbaran.Datasource:=dsalbaranesdetalle; infalbaranivas.Datasource:=dsqalbaranesiva; informe.Report.Clear; informe.LoadFromFile('c:\agrigest\informes\'+documento+'.fr3'); informe.Variables.Variables['FORMAPAGO']:=QUOTEDSTR(formapago); informe.Variables.Variables['PEDIDOS']:=QUOTEDSTR(pedidos); informe.Variables.Variables['FECHACARGA']:=QUOTEDSTR(fechacarga); informe.ShowReport(); informe.Clear; } end; procedure TSociosProductores.Button7Click(Sender: TObject); var archivo:string; begin savedialog1.FileName:='ESTADISTICAS DE '+sociosnombre.AsString+'.xlsx'; savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'ESTADISTICAS',DBGRID4); finally showmessage('Los datos han sido exportados correctamente a '+archivo); end; savedialog1.FileName:='DETALLE DE ENTRADAS DE '+sociosnombre.AsString+'.xlsx'; savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'DETALLE',DBGRID46); finally showmessage('Los datos han sido exportados correctamente a '+archivo); end; savedialog1.FileName:='DETALLE DE ENVASADOS DE '+sociosnombre.AsString+'.xlsx'; savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'DETALLE',DBGRID69); finally showmessage('Los datos han sido exportados correctamente a '+archivo); end; savedialog1.FileName:='DETALLE DE DESECHOS DE '+sociosnombre.AsString+'.xlsx'; savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'DETALLE',DBGRID3); finally showmessage('Los datos han sido exportados correctamente a '+archivo); end; end; procedure TSociosProductores.Button9Click(Sender: TObject); begin { if dbgrid4.SelectedRows.Count>0 then for i := 0 to dbgrid4.Selectedrows.Count - 1 do begin qacuentradas.GotoBookmark ((dbgrid4.selectedrows[i])); qaux.ParamByName('ID').AsInteger:=qlistaempleadosid.asinteger; qaux.Execsql; end else begin qlistaemplea.First; while not qlistaempleados.Eof do begin qaux.ParamByName('ID').AsInteger:=qlistaempleadosid.asinteger; qaux.Execsql; qlistaempleados.Next; end end; 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.seleccionado=1 order by nombre'); qinftrabajadores.Open; informedb.Datasource:=dsqinftrabajadores; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\infproductor.fr3'); informes.ShowReport(); } end; procedure TSociosProductores.btactualizarClick(Sender: TObject); var vdesde,vhasta:tdate; vpropietario:integer; vgenerico:string; begin vdesde:=tdesde.Date;// qcampanyasfechainicio.AsDatetime; vhasta:=thasta.date;// qcampanyasfechafin.AsDatetime; vpropietario:=qsociosid.AsInteger; vgenerico:='%'+edit1.Text+'%'; dsqentradas.DataSet:=qentradasdetalle; dsqenvasados.DataSet:=qenvasadosdetalle; dsqdesechos.DataSet:=qdesechosdetalle; qentradasdetalle.Close; qentradasdetalle.Prepare; qentradasdetalle.ParamByName('PDESDE').AsDate:=vdesde; qentradasdetalle.ParamByName('PHASTA').AsDate:=vhasta; qentradasdetalle.ParamByName('PPROPIETARIO').Asinteger:=vpropietario; qentradasdetalle.paramByname('PGENERICO').ASSTRING:=vgenerico; qentradasdetalle.Open; qenvasadosdetalle.Close; qenvasadosdetalle.Prepare; qenvasadosdetalle.ParamByName('PDESDE').AsDate:=vdesde; qenvasadosdetalle.ParamByName('PHASTA').AsDate:=vhasta; qenvasadosdetalle.ParamByName('PPROPIETARIO').Asinteger:=vpropietario; qenvasadosdetalle.paramByname('PGENERICO').ASSTRING:=vgenerico; qenvasadosdetalle.Open; qdesechosdetalle.Close; qdesechosdetalle.Prepare; qdesechosdetalle.ParamByName('PDESDE').AsDate:=vdesde; qdesechosdetalle.ParamByName('PHASTA').AsDate:=vhasta; qdesechosdetalle.ParamByName('PPROPIETARIO').Asinteger:=vpropietario; qdesechosdetalle.paramByname('PGENERICO').ASSTRING:=vgenerico; qdesechosdetalle.Open; if tkparcela.Checked then begin dsqestadisticas.DataSet:=qestadisticas_p; qestadisticas_p.close; qestadisticas_p.Prepare; qestadisticas_p.ParamByName('PDESDE').AsDate:=vdesde; qestadisticas_p.ParamByName('PHASTA').AsDate:=vhasta; qestadisticas_p.ParamByName('PPROPIETARIO').AsInteger:=vpropietario; qestadisticas_p.paramByname('PGENERICO').ASSTRING:=vgenerico; qestadisticas_p.Open; end; if tkmprima.Checked then begin dsqestadisticas.DataSet:=qestadisticas_mp; qestadisticas_mp.close; qestadisticas_mp.Prepare; qestadisticas_mp.ParamByName('PDESDE').AsDate:=vdesde; qestadisticas_mp.ParamByName('PHASTA').AsDate:=vhasta; qestadisticas_mp.ParamByName('PPROPIETARIO').AsInteger:=vpropietario; qestadisticas_mp.paramByname('PGENERICO').ASSTRING:=vgenerico; qestadisticas_mp.Open; end; if tkmprimaenv.Checked then begin dsqestadisticas.DataSet:=qestadisticas_mpe; qestadisticas_mpe.close; qestadisticas_mpe.Prepare; qestadisticas_mpe.ParamByName('PDESDE').AsDate:=vdesde; qestadisticas_mpe.ParamByName('PHASTA').AsDate:=vhasta; qestadisticas_mpe.ParamByName('PPROPIETARIO').AsInteger:=vpropietario; qestadisticas_mpe.paramByname('PGENERICO').ASSTRING:=vgenerico; qestadisticas_mpe.Open; end; { qenvasados.Close; qenvasados.prepare; qenvasados.ParamByName('PDESDE').AsDate:=pdesde; qenvasados.ParamByName('PHASTA').AsDate:=phasta; qenvasados.ParamByName('PAGRUPACION').Asstring:=pagrupacion; qenvasados.Open; qenvasadosdetalle.Close; qenvasadosdetalle.prepare; qenvasadosdetalle.ParamByName('PDESDE').AsDate:=pdesde; qenvasadosdetalle.ParamByName('PHASTA').AsDate:=phasta; qenvasadosdetalle.Open; qinfenvasados.Close; qinfenvasados.Prepare; qinfenvasados.ParamByName('PDESDE').AsDate:=pdesde; qinfenvasados.ParamByName('PHASTA').AsDate:=phasta;} end; procedure TSociosProductores.dsparcelasStateChange(Sender: TObject); begin if parcelas.State in [dsedit,dsinsert] then begin Panel7.Enabled:=true; btpnuevo.enabled:=false; btpborrar.enabled:=false; btpmodificar.enabled:=false; btpguardar.enabled:=true; btpcancelar.enabled:=true; end; if parcelas.State in [dsbrowse] then begin Panel7.Enabled:=false; btpnuevo.enabled:=true; btpborrar.enabled:=true; btpmodificar.enabled:=true; btpguardar.enabled:=false; btpcancelar.enabled:=false; end; end; procedure TSociosProductores.dsqcampanyasDataChange(Sender: TObject; Field: TField); begin tdesde.Date:=qcampanyasfechainicio.asdatetime; thasta.Date:=qcampanyasfechafin.asdatetime; end; procedure TSociosProductores.dsqsociosDataChange(Sender: TObject; Field: TField); begin btactualizar.Click; end; procedure TSociosProductores.dssociosStateChange(Sender: TObject); begin if socios.State in [dsedit,dsinsert] then begin Panel14.Enabled:=true; btsnuevo.enabled:=false; btsborrar.enabled:=false; btsmodificar.enabled:=false; btsguardar.enabled:=true; btscancelar.enabled:=true; end; if socios.State in [dsbrowse] then begin Panel14.Enabled:=false; btsnuevo.enabled:=true; btsborrar.enabled:=true; btsmodificar.enabled:=true; btsguardar.enabled:=false; btscancelar.enabled:=false; end; end; procedure Tsociosproductores.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 Tsociosproductores.AppMessage(var Msg: TMSg; Var Handled:Boolean); var actual : TWincontrol; begin if Msg.message = WM_KEYDOWN then begin // esto es para controlar que con la flecha abajo se desplegen las // listas if Msg.wParam = VK_DOWN then begin Actual := Screen.ActiveControl; if Actual is TDBLookupComboBox then if not TDBLookupComboBox(Screen.ActiveForm.ActiveControl).listVisible then TDBLookupComboBox(Screen.ActiveForm.ActiveControl).DropDown; // si utilizas las RX { if Actual is TRxDBLookupCombo then if not TRxDBLookupCombo(Screen.ActiveForm.ActiveControl).listVisible then TRxDBLookupCombo(Screen.ActiveForm.ActiveControl).DropDown; } if Actual is TComboBox then SendMessage(TComboBox(Screen.ActiveForm.ActiveControl).Handle,CB_SHOWDROPDOWN,-1,0); if (Actual is TCustomEdit) then Msg.wParam := VK_TAB; // se pueden añadir mas controles.... end; // y aqui es el control del intro. if Msg.wParam = VK_RETURN THEN begin Actual := Screen.ActiveControl; // para los edit. if (Actual is TCustomEdit) and not (Actual is TCustomMemo) then Msg.wParam := VK_TAB; // para los memo. Con ctrl + enter se salta de linea dentro del // memo, si solo es intro salta al siguiente control if (Actual is TCustomMemo) and (HiWord(GetKeyState(VK_CONTROL)) = 0)then Msg.wParam := VK_TAB; // para los lookup if Actual is TDBLookupComboBox then if not TDBLookupComboBox(Actual).listVisible then Msg.wParam := VK_TAB; // Si utilizas las RX { if Actual is TRxDBLookupCombo then if not TRxDBLookupCombo(Actual).listVisible then Msg.wParam := VK_TAB; } // Los combobox if Actual is TCustomComboBox then if not TCustomComboBox(Actual).DroppedDown then Msg.wParam := VK_TAB; // el radiobutton if Actual is TRadioButton then Msg.wParam := VK_TAB; // en el grid if Actual is TDBGrid then if (TDBGrid(Actual).ReadOnly) or (HiWord(GetKeyState(VK_CONTROL)) = 1)then Msg.wParam := VK_TAB; // o esto otro Con Ctrl + intro siguiente celda con // ctrl + shift + intro celda anterior // es complicado pero es por no liar con el intro solo // que siempre pasa de un control a otro. if Actual is TDBGrid then begin if (TDBGrid(Actual).ReadOnly) or (HiWord(GetKeyState(VK_CONTROL)) = 0) then Msg.wParam := VK_TAB else if not(HiWord(GetKeyState(VK_SHIFT)) = 0) then begin if TDBGrid(Actual).selectedindex > 0 then { increment the field } TDBGrid(Actual).selectedindex := TDBGrid(Actual).selectedindex -1 else TDBGrid(Actual).selectedindex := TDBGrid(Actual).fieldcount -1; end else begin if TDBGrid(Actual).selectedindex < (TDBGrid(Actual).fieldcount -1) then { increment the field } TDBGrid(Actual).selectedindex := TDBGrid(Actual).selectedindex +1 else TDBGrid(Actual).selectedindex := 0; end; end; // ListBox if Actual is TCustomListBox then Msg.wParam := VK_TAB; // TabControl if Actual is TCustomTabControl then Msg.wParam := VK_TAB; // Aqui se pondrían todos los controles que usamos en la // aplicación y necesitamos cambiar el tab por intro. // de esta forma te despreocupas de cuantos añades y es más // limpio el código end; end; end; procedure TSociosProductores.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure TSociosProductores.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is tdbgrid) then begin key:=','; end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure TSociosProductores.FormShow(Sender: TObject); begin qsocios.Close; qsocios.Open; qsocios2.Close; qsocios2.Open; socios.Close; socios.Open; qparcelas.Close; qparcelas.Open; parcelas.Close; parcelas.Open; parcelas_recintos.Close; parcelas_recintos.Open; qcampanyas.Close; qcampanyas.Open; qcultivos.Close; qcultivos.Open; datosproductores.ActivePageIndex:=0; detallesproductores.ActivePageIndex:=0; tsocioside:=dm.tempresaid.asinteger; combocampanyas.KeyValue:=qcampanyasdescripcion.Asstring; end; procedure TSociosProductores.qestadisticas_mpCalcFields(DataSet: TDataSet); var venvasados,vfacturables,vrecolectados,vdesechos:real; begin if qestadisticas_mpkgenvasados.AsString='' then venvasados:=0 else venvasados:=qestadisticas_mpkgenvasados.asfloat; if qestadisticas_mpkgfacturables.AsString='' then vfacturables:=0 else vfacturables:=qestadisticas_mpkgfacturables.asfloat;; if qestadisticas_mpkgrecolectados.AsString='' then vrecolectados:=0 else vrecolectados:=qestadisticas_mpkgrecolectados.asfloat; if qestadisticas_mpdesechos.AsString='' then vdesechos:=0 else vdesechos:=qestadisticas_mpdesechos.asfloat;; if vrecolectados=0 then vrecolectados:=1; if venvasados=0 then venvasados:=1; qestadisticas_mpmermaventa.value:=((venvasados-vfacturables)*100)/venvasados; qestadisticas_mpmermarecoleccion.value:=(vrecolectados-venvasados-vdesechos)*100/vrecolectados; end; procedure TSociosProductores.qestadisticas_mpeCalcFields(DataSet: TDataSet); var venvasados,vfacturables,vrecolectados,vdesechos:real; begin if qestadisticas_mpekgenvasados.AsString='' then venvasados:=0 else venvasados:=qestadisticas_mpekgenvasados.asfloat; if qestadisticas_mpekgfacturables.AsString='' then vfacturables:=0 else vfacturables:=qestadisticas_mpekgfacturables.asfloat;; if qestadisticas_mpekgrecolectados.AsString='' then vrecolectados:=0 else vrecolectados:=qestadisticas_mpekgrecolectados.asfloat; if qestadisticas_mpedesechos.AsString='' then vdesechos:=0 else vdesechos:=qestadisticas_mpedesechos.asfloat;; if vrecolectados=0 then vrecolectados:=1; if venvasados=0 then venvasados:=1; qestadisticas_mpemermaventa.value:=((venvasados-vfacturables)*100)/venvasados; end; procedure TSociosProductores.qestadisticas_pCalcFields(DataSet: TDataSet); var venvasados,vfacturables,vrecolectados,vdesechos:real; begin if qestadisticas_pkgenvasados.AsString='' then venvasados:=0 else venvasados:=qestadisticas_pkgenvasados.asfloat; if qestadisticas_pkgfacturables.AsString='' then vfacturables:=0 else vfacturables:=qestadisticas_pkgfacturables.asfloat;; if qestadisticas_pkgrecolectados.AsString='' then vrecolectados:=0 else vrecolectados:=qestadisticas_pkgrecolectados.asfloat; if qestadisticas_pdesechos.AsString='' then vdesechos:=0 else vdesechos:=qestadisticas_pdesechos.asfloat;; if vrecolectados=0 then vrecolectados:=1; if venvasados=0 then venvasados:=1; qestadisticas_pmermaventa.value:=((venvasados-vfacturables)*100)/venvasados; qestadisticas_pmermarecoleccion.value:=(vrecolectados-venvasados-vdesechos)*100/vrecolectados; end; procedure TSociosProductores.qparcelasBeforeOpen(DataSet: TDataSet); var filtrolocal:string; begin if filtro<>'' then begin begin filtrolocal:=' where nombre like('+''''+filtro+''''+') or codpar like('+''''+filtro+''''+')'; end; if vertodos=0 then begin filtrolocal:=' where (nombre like('+''''+filtro+''''+') or codpar like('+''''+filtro+''''+')'; filtrolocal:=filtrolocal+') and activo=1 '; end; if vertodos=1 then begin filtrolocal:=' where (nombre like('+''''+filtro+''''+') or codpar like('+''''+filtro+''''+')'; filtrolocal:=filtrolocal+')'; end; end; if filtro='' then begin filtrolocal:=''; if vertodos=0 then begin filtrolocal:=' where activo=1 '; end; if vertodos=1 then begin filtrolocal:=''; end; end; qparcelas.SQL.Clear; qparcelas.SQL.Add('select empresa,codpar,nombre,variedad,propietario from parcelas ' + filtrolocal +' order by codpar,nombre') end; procedure TSociosProductores.qsociosBeforeOpen(DataSet: TDataSet); var filtrolocal:string; begin if filtro<>'' then begin begin filtrolocal:=' where nombre like('+''''+filtro+''''+') or nombre_corto like('+''''+filtro+''''+') or id like('+''''+filtro+''''+')'; end; if vertodos=0 then begin begin filtrolocal:=' where (nombre like('+''''+filtro+''''+') or nombre_corto like('+''''+filtro+''''+') or id like('+''''+filtro+''''+')'; filtrolocal:=filtrolocal+') and activo=1 '; end; end; end; if filtro='' then begin filtrolocal:=''; if vertodos=0 then begin filtrolocal:=' where activo=1 '; end; end; qsocios.SQL.Clear; qsocios.SQL.Add('select id,nombre_corto,ide from propietarios ' + filtrolocal +' order by nombre_corto') end; procedure TSociosProductores.tbuscarChange(Sender: TObject); begin filtro:='%'+tbuscar.Text+'%'; if todosclientes.Checked then vertodos:=1 else vertodos:=0; qsocios.Close; qsocios.open; end; procedure TSociosProductores.tbuscarparcelasChange(Sender: TObject); begin filtro:='%'+tbuscarparcelas.Text+'%'; if todasparcelas.Checked then vertodos:=1 else vertodos:=0; qparcelas.Close; qparcelas.open; end; procedure TSociosProductores.tkparcelaClick(Sender: TObject); begin btactualizar.Click; end; procedure TSociosProductores.todosclientesClick(Sender: TObject); begin if todosclientes.Checked=true then begin vertodos:=1; qsocios.Close; qsocios.SQL.Clear; qsocios.SQL.add('select * from propietarios order by nombre asc'); qsocios.Open; end else begin vertodos:=0; qsocios.Close; qsocios.SQL.Clear; qsocios.SQL.add('select * from propietarios where activo=1 order by nombre asc'); qsocios.Open; end; end; end. ======================================== FICHERO: fproductosfitosanitarios.pas ======================================== unit fproductosfitosanitarios; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Data.Win.ADODB, Vcl.Grids, Vcl.DBGrids, ZAbstractRODataset, ZAbstractDataset, ZDataset, Vcl.StdCtrls,shellapi, Vcl.ExtCtrls,URLMon, Vcl.DBCtrls; type Tproductosfitosanitarios = class(TForm) Panel7: TPanel; btAreutilizar: TButton; qfitosanitarios: TZQuery; DBGrid1: TDBGrid; dsqfitosanitarios: TDataSource; qfitosanitariosregistro: TWideStringField; qfitosanitariosnombre_comercial: TWideStringField; qfitosanitariostitular: TWideStringField; qfitosanitariosmateria_activa: TWideStringField; qfitosanitariosautorizado: TIntegerField; qfitosanitariosfecha_actualizacion: TDateField; qfitosanitariostemp: TZQuery; listado: TADOQuery; clistado: TADOConnection; qaux: TZQuery; qfitosanitariostempregistro: TWideStringField; qfitosanitariostempnombre_comercial: TWideStringField; qfitosanitariostemptitular: TWideStringField; qfitosanitariostempmateria_activa: TWideStringField; gcrpagado: TDBCheckBox; Label1: TLabel; Edit1: TEdit; Button1: TButton; procedure btAreutilizarClick(Sender: TObject); procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBGrid1TitleClick(Column: TColumn); procedure FormShow(Sender: TObject); procedure Edit1Change(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var productosfitosanitarios: Tproductosfitosanitarios; const rojo=$00AAAAFF; amarillo=$00B9FFFF; verde=$00C7FBAA; azul=$00FFFFBB; implementation {$R *.dfm} function borrarespacios(Const Search: String): String; Const BlackSpace = [#33..#126]; Var Index: Byte; Begin Index := 1; While (Index <= Length(Search)) and Not (Search[Index] in BlackSpace) Do Index := Index + 1; result := copy(Search,Index,255); Index := Length(Result); While (Index >0) and not (Result[Index] in BlackSpace) Do Index := Index -1; result := copy(Result,1,Index); End; procedure Tproductosfitosanitarios.btAreutilizarClick(Sender: TObject); begin qfitosanitarios.Close; qaux.sql.clear; qaux.SQL.Add('delete from productos_fitosanitarios'); qaux.ExecSQL; qaux.Close; qaux.sql.Clear; qaux.SQL.Add('insert into productos_fitosanitarios (registro,nombre_comercial,titular,materia_activa) (select * from productos_fitosanitariostemp pft where pft.registro not in (select registro from productos_fitosanitarios))'); qaux.ExecSQL; qaux.Close; qaux.sql.Clear; qaux.SQL.Add('update productos_fitosanitarios set autorizado=0 where registro not in (select registro from productos_fitosanitariostemp)'); qaux.ExecSQL; qaux.Close; qaux.sql.Clear; qaux.SQL.Add('update productos_fitosanitarios set fecha_actualizacion=:FECHA'); qaux.prepare; qaux.parambyname('FECHA').asdate:=date; qaux.ExecSQL; qfitosanitarios.Open; end; procedure Tproductosfitosanitarios.Button1Click(Sender: TObject); var direccion:pwidechar; registro,cadena:string; begin registro:= qfitosanitariosregistro.AsString; registro:=borrarespacios(registro); cadena:='https://www.mapa.gob.es/agricultura/pags/fitos/registro/productos/pdf/'+registro+'.pdf'; direccion:=pwidechar(widestring(cadena)); URLDownloadToFile(nil, direccion, 'C:\agrigest\tmp\ficha.pdf', 0, nil); ShellExecute(Handle,nil,PChar('c:\agrigest\tmp\ficha.pdf'),'','',SW_SHOWNORMAL); end; procedure Tproductosfitosanitarios.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); const IsChecked : array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED); var DrawState: Integer; DrawRect: TRect; begin if qfitosanitariosautorizado.Asinteger=1 then begin dbgrid1.Canvas.brush.Color := verde; end; if qfitosanitariosautorizado.Asinteger=0 then begin dbgrid1.Canvas.brush.Color := rojo; end; dbgrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State); if (gdFocused in State) then begin if (Column.Field.FieldName = 'autorizado') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'autorizado') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; // DrawState := ISChecked[Column.Field.Asboolean]; DBgrid1.Canvas.FillRect(Rect); DrawFrameControl(DBgrid1.Canvas.Handle, DrawRect, DFC_BUTTON, DrawState); end; end; gcrpagado.visible:=false; end; procedure Tproductosfitosanitarios.DBGrid1TitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=qfitosanitarios.SortType; qfitosanitarios.SortedFields:=Column.FieldName; If st = stAscending then qfitosanitarios.SortType:=stDescending else qfitosanitarios.SortType:=stAscending; dsqfitosanitarios.DataSet.First; end; procedure Tproductosfitosanitarios.Edit1Change(Sender: TObject); begin if edit1.Text<>'' then begin qfitosanitarios.Close; qfitosanitarios.Prepare; qfitosanitarios.ParamByName('FILTRO').AsString:='%'+edit1.Text+'%'; qfitosanitarios.Open; end else begin qfitosanitarios.Close; qfitosanitarios.Prepare; qfitosanitarios.ParamByName('FILTRO').AsString:='%'; qfitosanitarios.Open; end; end; procedure Tproductosfitosanitarios.FormKeyPress(Sender: TObject; var Key: Char); begin key:=upcase(key); end; procedure Tproductosfitosanitarios.FormShow(Sender: TObject); begin qfitosanitarios.Close; qfitosanitarios.Prepare; qfitosanitarios.ParamByName('FILTRO').AsString:='%'; qfitosanitarios.Open; end; end. ======================================== FICHERO: fproveedores.pas ======================================== unit fproveedores; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.DBCtrls, Vcl.Mask, Vcl.ComCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, datos, ZAbstractDataset, ZDataset, Data.DB, ZAbstractRODataset, ZAbstractTable; type Tproveedores = class(TForm) Panel1: TPanel; Panel2: TPanel; Panel5: TPanel; Label1: TLabel; todosproveedores: TCheckBox; tbuscar: TEdit; DBGrid1: TDBGrid; Panel3: TPanel; Panel4: TPanel; DatosProveedores: TPageControl; TDatosClientes: TTabSheet; Panel14: TPanel; Label10: TLabel; Label11: TLabel; Label12: TLabel; Label13: TLabel; Label14: TLabel; Label15: TLabel; Label2: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; Label22: TLabel; Label23: TLabel; DBCheckBox2: TDBCheckBox; DBEdit1: TDBEdit; DBEdit10: TDBEdit; DBEdit11: TDBEdit; DBEdit12: TDBEdit; DBEdit13: TDBEdit; DBEdit3: TDBEdit; DBEdit4: TDBEdit; DBEdit5: TDBEdit; DBEdit6: TDBEdit; DBEdit7: TDBEdit; DBEdit8: TDBEdit; DBEdit9: TDBEdit; DBMemo1: TDBMemo; DBEdit21: TDBEdit; DBEdit22: TDBEdit; Panel6: TPanel; Label37: TLabel; BtPcancelar: TButton; btPmodificar: TButton; BtPborrar: TButton; BtPNuevo: TButton; BtPguardar: TButton; TDatosArticulos: TTabSheet; Panel7: TPanel; Label35: TLabel; btAcancelar: TButton; btAmodificar: TButton; btAborrar: TButton; btAnuevo: TButton; btAguardar: TButton; Panel13: TPanel; Panel17: TPanel; Detallesproveedores: TPageControl; TAlbaranes: TTabSheet; Panel10: TPanel; Label32: TLabel; btALmodificar: TButton; btALnuevo: TButton; qproveedores: TZReadOnlyQuery; artproveedor: TZQuery; proveedores: TZQuery; qproveedoresnombre: TWideStringField; dsqproveedores: TDataSource; qproveedoresidempresa: TIntegerField; qproveedoresid: TIntegerField; dsproveedores: TDataSource; proveedoresid: TIntegerField; proveedoresIdempresa: TIntegerField; proveedoresnif: TWideStringField; proveedoresnombre: TWideStringField; proveedoresnombre_corto: TWideStringField; proveedoresdireccion: TWideStringField; proveedorespoblacion: TWideStringField; proveedorescodpost: TWideStringField; proveedoresprovincia: TWideStringField; proveedorestelefono: TWideStringField; proveedorestelefono2: TWideStringField; proveedoresmovil: TWideStringField; proveedoresemail: TWideStringField; proveedorespersonacontacto: TWideStringField; proveedorescodigomercado: TIntegerField; proveedoresactivo: TIntegerField; proveedoresobservaciones: TWideStringField; proveedoresccontable: TIntegerField; proveedoresdescuento: TFloatField; dsq_articulospropios: TDataSource; dsartproveedor: TDataSource; qarticulos_propios: TZReadOnlyQuery; qarticulos_propiosidempresa: TIntegerField; qarticulos_propiosid: TIntegerField; qarticulos_propioscodigo: TWideStringField; qarticulos_propiosdescripcion: TWideStringField; qarticulos_propiosult_preciocompra: TFloatField; artproveedoridempresa: TIntegerField; artproveedoridproveedor: TIntegerField; artproveedorid: TWideStringField; artproveedorid_propio: TWideStringField; artproveedordescripcion: TWideStringField; artproveedorult_precio: TFloatField; artproveedoractivo: TIntegerField; DBGrid3: TDBGrid; DBLookupComboBox2: TDBLookupComboBox; DBGrid2: TDBGrid; dsqcompras: TDataSource; qcompras: TZReadOnlyQuery; qcomprasidempresa: TIntegerField; qcomprasidproveedor: TIntegerField; qcomprasnombre: TWideStringField; qcomprasdocumento: TWideStringField; qcomprasfecha: TDateField; qcomprascodigo: TWideStringField; qcomprasdescripcion: TWideStringField; qcomprasid_propio: TWideStringField; qcomprasdesc_propia: TWideStringField; qcomprascantidad: TFloatField; qcomprasstock: TFloatField; qcomprasprecio: TFloatField; qaux: TZQuery; procedure BtPNuevoClick(Sender: TObject); procedure BtPborrarClick(Sender: TObject); procedure btPmodificarClick(Sender: TObject); procedure BtPguardarClick(Sender: TObject); procedure BtPcancelarClick(Sender: TObject); procedure dsproveedoresStateChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure btAnuevoClick(Sender: TObject); procedure btAmodificarClick(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); procedure dsartproveedorStateChange(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure tbuscarChange(Sender: TObject); procedure qproveedoresBeforeOpen(DataSet: TDataSet); procedure FormCreate(Sender: TObject); procedure DBGrid3DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBGrid3ColExit(Sender: TObject); procedure DBGrid3KeyPress(Sender: TObject; var Key: Char); procedure btALnuevoClick(Sender: TObject); procedure btALmodificarClick(Sender: TObject); procedure DBGrid2TitleClick(Column: TColumn); private { Private declarations } public { Public declarations } var filtro:string; vertodos:integer; end; var proveedores: Tproveedores; implementation {$R *.dfm} uses fentradas; procedure Tproveedores.btAborrarClick(Sender: TObject); begin artproveedor.Delete; end; procedure Tproveedores.btAcancelarClick(Sender: TObject); begin artproveedor.Cancel; end; procedure Tproveedores.btAguardarClick(Sender: TObject); begin artproveedor.Post; end; procedure Tproveedores.btALmodificarClick(Sender: TObject); begin entradas.ShowModal; end; procedure Tproveedores.btALnuevoClick(Sender: TObject); begin entradas.ShowModal(); end; procedure Tproveedores.btAmodificarClick(Sender: TObject); begin artproveedor.edit; end; procedure Tproveedores.btAnuevoClick(Sender: TObject); begin //artproveedor.MasterSource:=nil; artproveedor.append; end; procedure Tproveedores.BtPborrarClick(Sender: TObject); begin proveedores.Delete; end; procedure Tproveedores.BtPcancelarClick(Sender: TObject); begin proveedores.Cancel; end; procedure Tproveedores.BtPguardarClick(Sender: TObject); begin proveedores.Post; qproveedores.Refresh; proveedores.MasterSource:=dsqproveedores; end; procedure Tproveedores.btPmodificarClick(Sender: TObject); begin proveedores.MasterSource:=nil; proveedores.edit; dbedit1.SetFocus; end; procedure Tproveedores.BtPNuevoClick(Sender: TObject); var id:integer; begin qaux.sql.clear; qaux.sql.add('select max(id) from proveedores'); qaux.Open; if qaux.Fields[0].AsInteger>0 then id:=qaux.Fields[0].AsInteger+1 else id:=0; proveedores.MasterSource:=nil; proveedores.append; proveedoresid.Value:=id; dbedit1.SetFocus; end; procedure Tproveedores.DBGrid2TitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=qcompras.SortType; qcompras.SortedFields:=Column.FieldName; If st = stAscending then qcompras.SortType:=stDescending else qcompras.SortType:=stAscending; dsqcompras.DataSet.First; end; procedure Tproveedores.DBGrid3ColExit(Sender: TObject); begin if DBGrid3.SelectedField.FieldName = DBLookupComboBox2.DataField then DBLookupComboBox2.Visible := False; end; procedure Tproveedores.DBGrid3DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if (gdFocused in State) then begin if (Column.Field.FieldName = DBLookupComboBox2.DataField) then with DBLookupComboBox2 do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; end; end end; procedure Tproveedores.DBGrid3KeyPress(Sender: TObject; var Key: Char); begin //if (key = Chr(9)) then Exit; if (DBGrid3.SelectedField.FieldName = DBLookupComboBox2.DataField) then begin DBLookupComboBox2.SetFocus; SendMessage(DBLookupComboBox2.Handle, WM_Char, word(Key), 0); end end; procedure Tproveedores.dsartproveedorStateChange(Sender: TObject); begin if artproveedor.State in [dsedit,dsinsert] then begin btAnuevo.enabled:=false; btAborrar.enabled:=false; btAmodificar.enabled:=false; btAguardar.enabled:=true; btAcancelar.enabled:=true; end; if artproveedor.State in [dsbrowse] then begin btAnuevo.enabled:=true; btAborrar.enabled:=true; btAmodificar.enabled:=true; btAguardar.enabled:=false; btAcancelar.enabled:=false; end; end; procedure Tproveedores.dsproveedoresStateChange(Sender: TObject); begin if proveedores.State in [dsedit,dsinsert] then begin Panel14.Enabled:=true; btPnuevo.enabled:=false; btPborrar.enabled:=false; btPmodificar.enabled:=false; btPguardar.enabled:=true; btPcancelar.enabled:=true; end; if proveedores.State in [dsbrowse] then begin Panel14.Enabled:=false; btPnuevo.enabled:=true; btPborrar.enabled:=true; btPmodificar.enabled:=true; btPguardar.enabled:=false; btPcancelar.enabled:=false; end; end; procedure Tproveedores.FormCreate(Sender: TObject); begin with DBLookupComboBox2 do begin DataSource := dsartproveedor; // -> AdoTable1 -> DBGrid1 ListSource := dsq_articulospropios; DataField := 'id_propio'; // from AdoTable1 - displayed in the DBGrid KeyField := 'codigo'; ListField := 'descripcion;codigo'; Visible := False; end; end; procedure Tproveedores.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tproveedores.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tproveedores.FormShow(Sender: TObject); begin qproveedores.Close; qproveedores.Open; proveedores.Close; proveedores.Open; qarticulos_propios.Close; qarticulos_propios.Open; artproveedor.close; artproveedor.Open; qcompras.Close; qcompras.Open; datosproveedores.ActivePageIndex:=0; detallesproveedores.ActivePageIndex:=0; end; procedure Tproveedores.qproveedoresBeforeOpen(DataSet: TDataSet); var filtrolocal:string; begin if filtro<>'' then begin begin filtrolocal:=' where nombre like('+''''+filtro+''''+') or nombre_corto like('+''''+filtro+''''+') or id like('+''''+filtro+''''+')'; end; if vertodos=0 then begin begin filtrolocal:=' where (nombre like('+''''+filtro+''''+') or nombre_corto like('+''''+filtro+''''+') or id like('+''''+filtro+''''+')'; filtrolocal:=filtrolocal+') and activo=1 '; end; end; end; if filtro='' then begin filtrolocal:=''; if vertodos=0 then begin filtrolocal:=' where activo=1 '; end; end; qproveedores.SQL.Clear; qproveedores.SQL.Add('select idempresa,id,nombre_corto as nombre from proveedores ' + filtrolocal +' order by nombre_corto') end; procedure Tproveedores.tbuscarChange(Sender: TObject); begin filtro:='%'+tbuscar.Text+'%'; if todosproveedores.Checked then vertodos:=1 else vertodos:=0; qproveedores.Close; qproveedores.open; end; end. ======================================== FICHERO: frecalculostock.pas ======================================== unit frecalculostock; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZDataset, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.DBCtrls, ZAbstractDataset; type Trecalculostock = class(TForm) Panel1: TPanel; Panel4: TPanel; Button1: TButton; Panel3: TPanel; Label1: TLabel; Label3: TLabel; qaux: TZReadOnlyQuery; qpesadaslotes: TZReadOnlyQuery; qpesadaslotesid: TIntegerField; qpesadasloteside: TIntegerField; qpesadaslotesidea: TIntegerField; qpesadaslotesidea2: TIntegerField; qpesadaslotescajas: TLargeintField; qpesadaslotesid_envase: TIntegerField; qpesadaslotesid_formato: TIntegerField; qmateriales: TZReadOnlyQuery; qmaterialesidaf: TIntegerField; qpesadaslotesmprima: TWideStringField; PBar: TProgressBar; fdesde: TDBLookupComboBox; qinventarios: TZReadOnlyQuery; qinventarioside: TIntegerField; qinventariosfecha: TDateField; qinventariosregularizado: TIntegerField; dsqinventarios: TDataSource; qstockdetalle: TZReadOnlyQuery; qstockdetalleide: TIntegerField; qstockdetallefecha: TDateField; qstockdetallecodigo: TWideStringField; qstockdetalledescripcion: TWideStringField; qstockdetallestock: TFloatField; qstockdetallestock_real: TFloatField; qauxentradas: TZQuery; qauxentradasid: TIntegerField; qauxentradasidempresa: TIntegerField; qauxentradasidproveedor: TIntegerField; qauxentradasfecha: TDateField; qauxentradasdocumento: TWideStringField; qauxentradasbase: TFloatField; qauxentradastotaliva: TFloatField; qauxentradastotalentrada: TFloatField; qauxentradasdetalle: TZQuery; qauxentradasdetalleid: TIntegerField; qauxentradasdetalleidempresa: TIntegerField; qauxentradasdetalleidentrada: TIntegerField; qauxentradasdetalleidproveedor: TIntegerField; qauxentradasdetallecodigo: TWideStringField; qauxentradasdetalleid_propio: TWideStringField; qauxentradasdetalledescripcion: TWideStringField; qauxentradasdetallelote: TWideStringField; qauxentradasdetallecantidad: TFloatField; qauxentradasdetallestock: TFloatField; qauxentradasdetalleprecio: TFloatField; qauxentradasdetalletipo_iva: TIntegerField; qauxentradasdetallebase: TFloatField; qauxentradasdetalletotal: TFloatField; qlotes: TZReadOnlyQuery; qpesadas: TZQuery; qpesadasid: TIntegerField; qpesadasidempresa: TIntegerField; qpesadasidea: TIntegerField; qpesadasid_palet: TWideStringField; qpesadasnum_palets: TIntegerField; qpesadasid_envase: TWideStringField; qpesadasnum_envases: TIntegerField; qpesadasmprima: TWideStringField; qpesadastara: TFloatField; qpesadascosto_materiales: TFloatField; qaux2: TZQuery; lid: TLabel; qpesadasrecuperar_envases: TIntegerField; qborrarmateriales: TZReadOnlyQuery; qactualizarentradasdetalle: TZReadOnlyQuery; qactualizarentradasdetalle2: TZReadOnlyQuery; qactualizarentradasdetalle3: TZReadOnlyQuery; Label2: TLabel; Label4: TLabel; qinsertarmateriales: TZReadOnlyQuery; qactualizarfitos: TZReadOnlyQuery; qactualizar_pesada: TZReadOnlyQuery; borrar_trigger: TZReadOnlyQuery; crear_trigger: TZReadOnlyQuery; procedure Button1Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure dsqinventariosDataChange(Sender: TObject; Field: TField); private { Private declarations } public { Public declarations } end; var recalculostock: Trecalculostock; implementation {$R *.dfm} procedure Trecalculostock.Button1Click(Sender: TObject); var dia,mes,anyo:word; tdia,tmes,tanyo,tdesde,fecha,tdesde2,thasta2,tmultiplicador:string; vide,videa,videa2,vnum_palets,vnum_envases,vidpalet,videnvase,vidformato,vidaf:string; vcantidad,vpeso,vcoste,id:string; vmultiplicador,resto:real; vescompuesta:integer; begin decodedate(qinventariosfecha.AsDateTime,anyo,mes,dia); tdesde:=''''+floattostr(anyo)+'-'+floattostr(mes)+'-'+floattostr(dia)+''''; qpesadas.close; qpesadas.prepare; qpesadas.ParamByName('FECHA').AsDateTime:=qinventariosfecha.AsDateTime;//('select idempresa,id,idea,id_palet,num_palets,id_envase,num_envases,mprima,tara,costo_materiales,recuperar_envases from ea_pesadas where fecha>'+tdesde+' order by fecha,id'); qpesadas.Open; pbar.Visible:=true; pbar.Min:=0; pbar.Max:=qpesadas.RecordCount; LABEL2.Caption:='Nº DE REGISTROS: '+INTTOSTR(QPESADAS.RecordCount); label4.Caption:='BORRANDO MATERIALES'; panel3.Repaint; borrar_trigger.ExecSQL; while not qpesadas.eof do begin qborrarmateriales.Prepare; qborrarmateriales.ParamByName('EMPRESA').Asinteger:=qpesadasidempresa.asinteger; qborrarmateriales.ParamByName('ID').Asinteger:=qpesadasid.asinteger; qborrarmateriales.ParamByName('IDEA').Asinteger:=qpesadasidea.asinteger; qborrarmateriales.ExecSQL; pbar.marqueeInterval:=round(qpesadas.RecordCount/100); pbar.StepIt; qpesadas.Next; end; crear_trigger.ExecSQL; { qactualizarentradasdetalle.Prepare; qactualizarentradasdetalle.ParamByName('FECHA').AsDateTime:=qinventariosfecha.AsDateTime; qactualizarentradasdetalle.ParamByName('EMPRESA').asINTEGER:=qinventarioside.AsInteger; qactualizarentradasdetalle.ExecSQL; } { qaux.Close; qaux.sql.Clear; qaux.SQL.Create.Add('delete from ea_materiales where (ide,idea,idea2) in (select idempresa,id,idea from ea_pesadas where fecha>'+tdesde+')'); qaux.ExecSQL; qaux.Close; qaux.sql.Clear; qaux.sql.Add('update entradas_detalle set stock=cantidad where id_propio not in (select codigo from control_stock_detalle where fecha='+tdesde+' and ide='+qinventarioside.asstring+' ) and identrada in (select id from entradas where fecha>='+tdesde+')'); qaux.ExecSQL;} { try while not qstockdetalle.eof do begin qactualizarentradasdetalle2.Prepare; qactualizarentradasdetalle2.ParamByName('FECHA').AsDateTime:=qstockdetallefecha.AsDateTime; qactualizarentradasdetalle2.ParamByName('EMPRESA').asINTEGER:=qstockdetalleide.asinteger; qactualizarentradasdetalle2.ParamByName('CODIGO').AsString:=qstockdetallecodigo.asstring; qactualizarentradasdetalle2.ExecSQL; qactualizarentradasdetalle3.Prepare; qactualizarentradasdetalle3.ParamByName('FECHA').AsDateTime:=qstockdetallefecha.AsDateTime; qactualizarentradasdetalle3.ParamByName('EMPRESA').asINTEGER:=qstockdetalleide.asinteger; qactualizarentradasdetalle3.ParamByName('CODIGO').AsString:=qstockdetallecodigo.asstring; qactualizarentradasdetalle3.ExecSQL; decodedate(qstockdetallefecha.AsDateTime,anyo,mes,dia); fecha:=''''+floattostr(anyo)+'-'+floattostr(mes)+'-'+floattostr(dia)+''''; resto:=qstockdetallestock_real.AsFloat; qaux.Close; qaux.sql.Clear; qaux.sql.Add('select * from entradas_detalle where id_propio='+''''+qstockdetallecodigo.asstring+''''+' and idempresa='+qstockdetalleide.asstring+' order by id desc'); qaux.open; if qaux.RecordCount>0 then // if 1 begin qaux2.Close; qaux2.sql.Clear; qaux2.sql.Add('select * from entradas_detalle where id_propio='+''''+qstockdetallecodigo.asstring+''''+' and idempresa='+qstockdetalleide.asstring+' and identrada in (select id from entradas where fecha>'+fecha+') order by id desc'); qaux2.open; if qaux2.RecordCount>0 then begin qaux.Close; qaux.sql.Clear; qaux.sql.Add('update entradas_detalle set stock=cantidad where id_propio='+''''+qstockdetallecodigo.asstring+''''+' and idempresa='+qstockdetalleide.asstring+' and identrada in (select id from entradas where fecha>'+fecha+')'); qaux.ExecSQL; end; qaux.Close; qaux.sql.Clear; qaux.sql.Add('update entradas_detalle set stock=0 where id_propio='+''''+qstockdetallecodigo.asstring+''''+' and idempresa='+qstockdetalleide.asstring+' and identrada in (select id from entradas where fecha<='+fecha+')'); qaux.ExecSQL; qaux.Close; qaux.sql.Clear; qaux.sql.Add('select id,idempresa,fecha from entradas where fecha<'+fecha+' and (id,idempresa) in (select identrada,idempresa from entradas_detalle where cantidad>=0 and id_propio='+''''+qstockdetallecodigo.asstring+''''+' and idempresa='+qstockdetalleide.asstring+') order by fecha desc,id desc'); qaux.open; if qaux.recordcount=0 then begin qaux.sql.Clear; qaux.sql.Add('select id,idempresa,fecha from entradas where fecha>='+fecha+' and (id,idempresa) in (select identrada,idempresa from entradas_detalle where cantidad>=0 and id_propio='+''''+qstockdetallecodigo.asstring+''''+' and idempresa='+qstockdetalleide.asstring+') order by fecha desc'); qaux.open; end; while resto>0 do // while 1 begin qaux2.Close; qaux2.sql.Clear; qaux2.sql.Add('select * from entradas_detalle where idempresa='+qaux.fields[1].AsString+' and identrada='+qaux.fields[0].AsString+' and id_propio='+''''+qstockdetallecodigo.asstring+''''+' order by id desc'); qaux2.open; if qaux2.fields[8].asfloat>=resto then begin if not qaux.Eof then begin qaux2.edit; qaux2.Fields[9].Value:=resto; qaux2.post; resto:=0; end else begin qaux2.edit; qaux2.Fields[9].Value:=qaux2.Fields[9].asfloat+resto; qaux2.post; resto:=0; end; end; if qaux2.fields[8].asfloat<=resto then begin if not qaux.Eof then begin qaux2.edit; resto:=resto-qaux2.fields[8].asfloat; qaux2.Fields[9].Value:=qaux2.fields[8].asfloat; qaux2.post; end else begin qaux2.edit; qaux2.Fields[9].Value:=qaux2.Fields[9].asfloat+resto; qaux2.post; resto:=0; end; end; qaux.Next; end; // end while 1 end; if qaux.RecordCount=0 then begin decodedate(qstockdetallefecha.AsDateTime,anyo,mes,dia); fecha:=''''+floattostr(anyo)+'/'+floattostr(mes)+'/'+floattostr(dia)+''''; qaux2.close; qaux2.SQL.Clear; qaux2.SQL.Add('select * from entradas where idproveedor=0 and fecha='+fecha+' and idempresa='+qstockdetalleide.asstring); qaux2.Open; if qaux2.RecordCount=0 then begin qauxentradas.Open; qauxentradas.Append; qauxentradasidempresa.Value:=qstockdetalleide.asinteger; qauxentradasidproveedor.Value:=0; qauxentradasfecha.Value:=qstockdetallefecha.AsDateTime; qauxentradasdocumento.Value:='INV.'+qstockdetallefecha.AsSTRING; qauxentradas.Post; end else begin qauxentradas.Open; qauxentradas.Locate('documento','INV.'+qstockdetallefecha.AsSTRING,[locaseinsensitive]); end; qauxentradasdetalle.Open; qauxentradasdetalle.Append; qauxentradasdetalleidempresa.Value:=qauxentradasidempresa.AsInteger; qauxentradasdetalleidentrada.Value:=qauxentradasid.AsInteger; qauxentradasdetalleidproveedor.Value:=qauxentradasidproveedor.AsInteger; qauxentradasdetallecodigo.Value:=qstockdetallecodigo.asstring; qauxentradasdetalleid_propio.Value:=qstockdetallecodigo.asstring; qauxentradasdetalledescripcion.Value:=qstockdetalledescripcion.asstring; qauxentradasdetallelote.Value:=qauxentradasdocumento.asstring; qauxentradasdetallecantidad.Value:=qstockdetallestock_real.asfloat; qauxentradasdetallestock.Value:=qstockdetallestock_real.asfloat; qauxentradasdetalleprecio.Value:=0; qauxentradasdetalletipo_iva.Value:=0; qauxentradasdetalle.Post; end; qstockdetalle.next; end; except showmessage('error en el codigo '+qstockdetallecodigo.AsString); end; } { qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('update articulosf af set stock=(select sum(stock) as stock from entradas_detalle where id_propio=af.codigo and idempresa=af.idempresa group by id_propio )'); qaux.ExecSQL; qaux.SQL.Clear; qaux.SQL.Add('update articulosf af set preciocoste=(SELECT SUM((SELECT PRECIO*STOCK FROM entradas_detalle WHERE ID=ed.id))/sum(stock) FROM `entradas_detalle` ed where id_propio=af.codigo) where idempresa=af.idempresa and codigo=af.codigo'); qaux.ExecSQL; qaux.SQL.Clear; qaux.SQL.Add('select * from articulosf where stock_minimo>stock and avisar_stock=1'); qaux.Open; } ///// /// qpesadas.First; pbar.Visible:=true; pbar.Min:=0; pbar.Max:=qpesadas.RecordCount; label4.Caption:='INSERTANDO MATERIALES'; panel3.Repaint; while not qpesadas.Eof do begin qaux.SQL.Clear; qaux.SQL.Add('select compuesto from materias_primas where idempresa='+qpesadasidempresa.asstring+' and id='+''''+qpesadasmprima.asstring+''''); qaux.Open; if qaux.Fields[0].AsInteger=0 then vmultiplicador:=1 else vmultiplicador:=0.5; tmultiplicador:=floattostr(vmultiplicador); tmultiplicador:=StringReplace(tmultiplicador, ',', '.',[rfReplaceAll, rfIgnoreCase]); pbar.StepIt; id:=qpesadasid.AsString; { if id='6939' then begin showmessage('6939'); end; } lid.Caption:='ID: '+id; lid.Repaint; qlotes.Close; qlotes.Prepare; qlotes.ParamByName('EMPRESA').Asinteger:=qpesadasidempresa.asinteger; qlotes.ParamByName('ID').Asinteger:=qpesadasid.asinteger; qlotes.ParamByName('IDEA').Asinteger:=qpesadasidea.asinteger; qlotes.open; if qlotes.RecordCount>0 then begin qinsertarmateriales.prepare; qinsertarmateriales.ParamByName('EMPRESA').AsInteger:=qpesadasidempresa.AsInteger; qinsertarmateriales.ParamByName('IDEA').AsInteger:=qpesadasid.AsInteger; qinsertarmateriales.ParamByName('IDEA2').AsInteger:=qpesadasidea.AsInteger; qinsertarmateriales.ParamByName('NUMPALETS').AsInteger:=qpesadasnum_palets.AsInteger; qinsertarmateriales.ParamByName('MULTIPLICADOR').AsFLOAT:=vmultiplicador; qinsertarmateriales.ParamByName('IDPALET').AsString:=qpesadasid_palet.AsString; qinsertarmateriales.ExecSQL; { qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('insert into ea_materiales '); qaux.SQL.Add('select idempresa,'+qpesadasid.AsString+' as idea,'+qpesadasidea.AsString+' as idea2,idarticulof,sum(cantidadtotal) as cantidadtotal,sum(pesototal) as pesototal,null,sum(preciototal) as preciototal,0 as recuperado,null as identrada from '); //// materiales de los envases qaux.SQL.Add('(SELECT ac.idempresa,ac.idarticuloalmacen,ac.idarticulof,(ac.cantidad*lp.cajas*'+tmultiplicador+') as cantidadtotal,(ac.peso*lp.cajas*'+tmultiplicador+') as pesototal,(ac.preciocoste*lp.cajas*'+tmultiplicador+') as preciototal '); qaux.SQL.Add(' FROM articulos_componentes ac,(SELECT lp.ide,lp.idea,lp.idea2,sum(cajas) as cajas,aa.id as id_envase FROM lotes_pesadas lp,articulos_almacen aa where aa.ide=lp.ide and aa.codigo=lp.id_envase '); qaux.SQL.Add(' and lp.ide='+qpesadasidempresa.AsString+' and lp.idea='+qpesadasid.AsString+' and lp.idea2='+qpesadasidea.AsString+' group by lp.id_envase ) as lp '); qaux.SQL.Add(' where ac.idempresa=lp.ide and ac.idarticuloalmacen=lp.id_envase '); qaux.SQL.Add(' union ALL'); // materiales de los formatos qaux.SQL.Add(' SELECT ac.ide,ac.idcfg,ac.idaf,(ac.cantidad*lp.cajas*'+tmultiplicador+') as cantidadtotal,(ac.peso*lp.cajas*'+tmultiplicador+') as pesototal,(ac.coste*lp.cajas*'+tmultiplicador+') as preciototal FROM '); qaux.SQL.Add(' configuraciones_detalle ac,(SELECT lp.ide,lp.idea,lp.idea2,sum(cajas) as cajas,aa.id as id_envase FROM lotes_pesadas lp, '); qaux.SQL.Add(' configuraciones aa where aa.ide=lp.ide and aa.id=lp.id_formato and lp.ide='+qpesadasidempresa.AsString+' and lp.idea='+qpesadasid.AsString+' and lp.idea2='+qpesadasidea.AsString+' group by lp.id_envase ) as lp '); qaux.SQL.Add(' where ac.ide=lp.ide and ac.idcfg=lp.id_envase '); qaux.SQL.Add(' union ALL'); //// materiales de los palets qaux.SQL.Add(' SELECT ac.idempresa,ac.idarticuloalmacen,ac.idarticulof,(ac.cantidad*'+qpesadasnum_palets.AsString+') as cantidadtotal,(ac.peso*'+qpesadasnum_palets.AsString+') as pesototal,(ac.coste*'+qpesadasnum_palets.AsString+') as preciototal'); qaux.SQL.Add(' FROM articulos_componentes ac where ac.idempresa='+qpesadasidempresa.AsString+' and ac.idarticuloalmacen=(select id from articulos_almacen where codigo='+''''+qpesadasid_palet.AsString+''''+' )'); qaux.SQL.Add(' ) as ea_materiales_tmp group by idarticulof'); qaux.execsql; } end; if qpesadasrecuperar_envases.AsInteger=1 then begin qaux.SQL.Clear; qaux.SQL.Add('update ea_materiales ea set recuperado=-1 where ea.ide='+qpesadasidempresa.asstring+' and ea.idea='+qpesadasid.AsString+' and ea.idea2='+qpesadasidea.AsString); qaux.execsql; end else begin qaux.SQL.Clear; qaux.SQL.Add('update ea_materiales ea set recuperado=0 where ea.ide='+qpesadasidempresa.asstring+' and ea.idea='+qpesadasid.AsString+' and ea.idea2='+qpesadasidea.AsString); qaux.execsql; end; qaux.sql.clear; qaux.sql.Add('select sum(peso),sum(precio) from ea_materiales where ide='+qpesadasidempresa.AsString+' and idea='+qpesadasid.AsString+' and idea2='+qpesadasidea.AsString); qaux.open; qactualizar_pesada.close; qactualizar_pesada.prepare; qactualizar_pesada.ParamByName('EMPRESA').AsInteger:=qpesadasidempresa.Asinteger; qactualizar_pesada.ParamByName('IDEA').AsInteger:=qpesadasid.Asinteger; qactualizar_pesada.ParamByName('IDEA2').AsInteger:=qpesadasidea.Asinteger; qactualizar_pesada.ParamByName('COSTO').Asfloat:=qaux.Fields[1].AsFloat;; qactualizar_pesada.ExecSQL; { qpesadas.Edit; qpesadastara.Value:=qaux.Fields[0].AsFloat; qpesadascosto_materiales.Value:=qaux.Fields[1].AsFloat; qpesadas.Post;} qpesadas.next end; pbar.Visible:=false; showmessage('¡¡¡Actualización realizada¡¡¡¡¡'); { qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('update articulosf af set stock=(select sum(stock) as stock from entradas_detalle where id_propio=af.codigo and idempresa=af.idempresa group by id_propio )'); qaux.ExecSQL; qaux.SQL.Clear; qaux.SQL.Add('update articulosf af set preciocoste=(SELECT SUM((SELECT PRECIO*STOCK FROM entradas_detalle WHERE ID=ed.id))/sum(stock) FROM `entradas_detalle` ed where id_propio=af.codigo) where idempresa=af.idempresa and codigo=af.codigo'); qaux.ExecSQL; qaux.SQL.Clear; qaux.SQL.Add('select * from articulosf where stock_minimo>stock and avisar_stock=1'); qaux.Open; } // qactualizarfitos.execsql; end; procedure Trecalculostock.dsqinventariosDataChange(Sender: TObject; Field: TField); begin qstockdetalle.Close; qstockdetalle.ParamByName('FECHA').AsDateTime:=qinventariosfecha.AsDateTime; qstockdetalle.ParamByName('EMPRESA').AsInteger:=qinventarioside.AsInteger; qstockdetalle.Open; end; procedure Trecalculostock.FormKeyPress(Sender: TObject; var Key: Char); begin if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Trecalculostock.FormShow(Sender: TObject); begin qinventarios.Open; // qstockdetalle.Open; end; end. ======================================== FICHERO: frecalculostock_PORTATIL_sep.-23-170321-2020_Conflict.pas ======================================== unit frecalculostock; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZDataset, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.DBCtrls, ZAbstractDataset; type Trecalculostock = class(TForm) Panel1: TPanel; Panel4: TPanel; Button1: TButton; Panel3: TPanel; Label1: TLabel; Label3: TLabel; qaux: TZReadOnlyQuery; qpesadaslotes: TZReadOnlyQuery; qpesadaslotesid: TIntegerField; qpesadasloteside: TIntegerField; qpesadaslotesidea: TIntegerField; qpesadaslotesidea2: TIntegerField; qpesadaslotescajas: TLargeintField; qpesadaslotesid_envase: TIntegerField; qpesadaslotesid_formato: TIntegerField; qmateriales: TZReadOnlyQuery; qmaterialesidaf: TIntegerField; qpesadaslotesmprima: TWideStringField; PBar: TProgressBar; fdesde: TDBLookupComboBox; qinventarios: TZReadOnlyQuery; qinventarioside: TIntegerField; qinventariosfecha: TDateField; qinventariosregularizado: TIntegerField; dsqinventarios: TDataSource; qstockdetalle: TZReadOnlyQuery; qstockdetalleide: TIntegerField; qstockdetallefecha: TDateField; qstockdetallecodigo: TWideStringField; qstockdetalledescripcion: TWideStringField; qstockdetallestock: TFloatField; qstockdetallestock_real: TFloatField; qauxentradas: TZQuery; qauxentradasid: TIntegerField; qauxentradasidempresa: TIntegerField; qauxentradasidproveedor: TIntegerField; qauxentradasfecha: TDateField; qauxentradasdocumento: TWideStringField; qauxentradasbase: TFloatField; qauxentradastotaliva: TFloatField; qauxentradastotalentrada: TFloatField; qauxentradasdetalle: TZQuery; qauxentradasdetalleid: TIntegerField; qauxentradasdetalleidempresa: TIntegerField; qauxentradasdetalleidentrada: TIntegerField; qauxentradasdetalleidproveedor: TIntegerField; qauxentradasdetallecodigo: TWideStringField; qauxentradasdetalleid_propio: TWideStringField; qauxentradasdetalledescripcion: TWideStringField; qauxentradasdetallelote: TWideStringField; qauxentradasdetallecantidad: TFloatField; qauxentradasdetallestock: TFloatField; qauxentradasdetalleprecio: TFloatField; qauxentradasdetalletipo_iva: TIntegerField; qauxentradasdetallebase: TFloatField; qauxentradasdetalletotal: TFloatField; qlotes: TZReadOnlyQuery; qpesadas: TZQuery; qpesadasid: TIntegerField; qpesadasidempresa: TIntegerField; qpesadasidea: TIntegerField; qpesadasid_palet: TWideStringField; qpesadasnum_palets: TIntegerField; qpesadasid_envase: TWideStringField; qpesadasnum_envases: TIntegerField; qpesadasmprima: TWideStringField; qpesadastara: TFloatField; qpesadascosto_materiales: TFloatField; qaux2: TZQuery; lid: TLabel; procedure Button1Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } end; var recalculostock: Trecalculostock; implementation {$R *.dfm} procedure Trecalculostock.Button1Click(Sender: TObject); var dia,mes,anyo:word; tdia,tmes,tanyo,tdesde,fecha,tdesde2,thasta2:string; vide,videa,videa2,vnum_palets,vnum_envases,vidpalet,videnvase,vidformato,vidaf:string; vcantidad,vpeso,vcoste,id:string; vmultiplicador,resto:real; vescompuesta:integer; begin decodedate(qinventariosfecha.AsDateTime,anyo,mes,dia); tdesde:=''''+floattostr(anyo)+'-'+floattostr(mes)+'-'+floattostr(dia)+''''; qpesadas.close; qpesadas.sql.clear; qpesadas.sql.add('select idempresa,id,idea,id_palet,num_palets,id_envase,num_envases,mprima,tara,costo_materiales from ea_pesadas where fecha>'+tdesde+' order by fecha,id'); qpesadas.Open; pbar.Visible:=true; pbar.Min:=0; pbar.Max:=qpesadas.RecordCount; pbar.marqueeInterval:=round(qpesadas.RecordCount/100); qaux.Close; qaux.sql.Clear; qaux.SQL.Create.Add('delete from ea_materiales where (ide,idea,idea2) in (select idempresa,id,idea from ea_pesadas where fecha>'+tdesde+')'); qaux.ExecSQL; ///// try while not qstockdetalle.eof do begin decodedate(qstockdetallefecha.AsDateTime,anyo,mes,dia); fecha:=''''+floattostr(anyo)+'-'+floattostr(mes)+'-'+floattostr(dia)+''''; resto:=qstockdetallestock_real.AsFloat; qaux.Close; qaux.sql.Clear; qaux.sql.Add('select * from entradas_detalle where id_propio='+''''+qstockdetallecodigo.asstring+''''+' and idempresa='+qstockdetalleide.asstring+' order by id desc'); qaux.open; if qaux.RecordCount>0 then // if 1 begin qaux2.Close; qaux2.sql.Clear; qaux2.sql.Add('select * from entradas_detalle where id_propio='+''''+qstockdetallecodigo.asstring+''''+' and idempresa='+qstockdetalleide.asstring+' and identrada in (select id from entradas where fecha>'+fecha+') order by id desc'); qaux2.open; if qaux2.RecordCount>0 then begin qaux.Close; qaux.sql.Clear; qaux.sql.Add('update entradas_detalle set stock=cantidad where id_propio='+''''+qstockdetallecodigo.asstring+''''+' and idempresa='+qstockdetalleide.asstring+' and identrada in (select id from entradas where fecha>'+fecha+')'); qaux.ExecSQL; end; qaux.Close; qaux.sql.Clear; qaux.sql.Add('update entradas_detalle set stock=0 where id_propio='+''''+qstockdetallecodigo.asstring+''''+' and idempresa='+qstockdetalleide.asstring+' and identrada in (select id from entradas where fecha<='+fecha+')'); qaux.ExecSQL; qaux.Close; qaux.sql.Clear; qaux.sql.Add('select id,idempresa,fecha from entradas where fecha<'+fecha+' and (id,idempresa) in (select identrada,idempresa from entradas_detalle where cantidad>=0 and id_propio='+''''+qstockdetallecodigo.asstring+''''+' and idempresa='+qstockdetalleide.asstring+') order by fecha desc,id desc'); qaux.open; if qaux.recordcount=0 then begin qaux.sql.Clear; qaux.sql.Add('select id,idempresa,fecha from entradas where fecha>='+fecha+' and (id,idempresa) in (select identrada,idempresa from entradas_detalle where cantidad>=0 and id_propio='+''''+qstockdetallecodigo.asstring+''''+' and idempresa='+qstockdetalleide.asstring+') order by fecha desc'); qaux.open; end; while resto>0 do // while 1 begin qaux2.Close; qaux2.sql.Clear; qaux2.sql.Add('select * from entradas_detalle where idempresa='+qaux.fields[1].AsString+' and identrada='+qaux.fields[0].AsString+' and id_propio='+''''+qstockdetallecodigo.asstring+''''+' order by id desc'); qaux2.open; if qaux2.fields[8].asfloat>=resto then begin if not qaux.Eof then begin qaux2.edit; qaux2.Fields[9].Value:=resto; qaux2.post; resto:=0; end else begin qaux2.edit; qaux2.Fields[9].Value:=qaux2.Fields[9].asfloat+resto; qaux2.post; resto:=0; end; end; if qaux2.fields[8].asfloat<=resto then begin if not qaux.Eof then begin qaux2.edit; resto:=resto-qaux2.fields[8].asfloat; qaux2.Fields[9].Value:=qaux2.fields[8].asfloat; qaux2.post; end else begin qaux2.edit; qaux2.Fields[9].Value:=qaux2.Fields[9].asfloat+resto; qaux2.post; resto:=0; end; end; qaux.Next; end; // end while 1 end; if qaux.RecordCount=0 then begin decodedate(qstockdetallefecha.AsDateTime,anyo,mes,dia); fecha:=''''+floattostr(anyo)+'/'+floattostr(mes)+'/'+floattostr(dia)+''''; qaux2.close; qaux2.SQL.Clear; qaux2.SQL.Add('select * from entradas where idproveedor=0 and fecha='+fecha+' and idempresa='+qstockdetalleide.asstring); qaux2.Open; if qaux2.RecordCount=0 then begin qauxentradas.Open; qauxentradas.Append; qauxentradasidempresa.Value:=qstockdetalleide.asinteger; qauxentradasidproveedor.Value:=0; qauxentradasfecha.Value:=qstockdetallefecha.AsDateTime; qauxentradasdocumento.Value:='INV.'+qstockdetallefecha.AsSTRING; qauxentradas.Post; end else begin qauxentradas.Open; qauxentradas.Locate('documento','INV.'+qstockdetallefecha.AsSTRING,[locaseinsensitive]); end; qauxentradasdetalle.Open; qauxentradasdetalle.Append; qauxentradasdetalleidempresa.Value:=qauxentradasidempresa.AsInteger; qauxentradasdetalleidentrada.Value:=qauxentradasid.AsInteger; qauxentradasdetalleidproveedor.Value:=qauxentradasidproveedor.AsInteger; qauxentradasdetallecodigo.Value:=qstockdetallecodigo.asstring; qauxentradasdetalleid_propio.Value:=qstockdetallecodigo.asstring; qauxentradasdetalledescripcion.Value:=qstockdetalledescripcion.asstring; qauxentradasdetallelote.Value:=qauxentradasdocumento.asstring; qauxentradasdetallecantidad.Value:=qstockdetallestock_real.asfloat; qauxentradasdetallestock.Value:=qstockdetallestock_real.asfloat; qauxentradasdetalleprecio.Value:=0; qauxentradasdetalletipo_iva.Value:=0; qauxentradasdetalle.Post; end; qstockdetalle.next; end; except showmessage('error en el codigo '+qstockdetallecodigo.AsString); end; qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('update articulosf af set stock=(select sum(stock) as stock from entradas_detalle where id_propio=af.codigo and idempresa=af.idempresa group by id_propio )'); qaux.ExecSQL; qaux.SQL.Clear; qaux.SQL.Add('update articulosf af set preciocoste=(SELECT SUM((SELECT PRECIO*STOCK FROM entradas_detalle WHERE ID=ed.id))/sum(stock) FROM `entradas_detalle` ed where id_propio=af.codigo) where idempresa=af.idempresa and codigo=af.codigo'); qaux.ExecSQL; qaux.SQL.Clear; qaux.SQL.Add('select * from articulosf where stock_minimo>stock and avisar_stock=1'); qaux.Open; ///// while not qpesadas.Eof do begin pbar.StepIt; id:=qpesadasid.AsString; { if id='6939' then begin showmessage('6939'); end; } lid.Caption:=id; qaux.Close; qaux.sql.clear; qaux.sql.Add('delete from ea_materiales where ide='+qpesadasidempresa.AsString+' and idea='+qpesadasid.AsString+' and idea2='+qpesadasidea.AsString); qaux.execsql; qlotes.Close; qlotes.SQL.Clear; qlotes.SQL.Add('select * from lotes_pesadas where ide='+qpesadasidempresa.AsString+' and idea='+qpesadasid.AsString+' and idea2='+qpesadasidea.AsString); qlotes.Open; if qlotes.RecordCount>0 then begin qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('insert into ea_materiales '); qaux.SQL.Add('select idempresa,'+qpesadasid.AsString+' as idea,'+qpesadasidea.AsString+' as idea2,idarticulof,sum(cantidadtotal) as cantidadtotal,sum(pesototal) as pesototal,null,sum(preciototal) as preciototal from '); //// materiales de los envases qaux.SQL.Add('(SELECT ac.idempresa,ac.idarticuloalmacen,ac.idarticulof,(ac.cantidad*lp.cajas) as cantidadtotal,(ac.peso*lp.cajas) as pesototal,(ac.preciocoste*lp.cajas) as preciototal '); qaux.SQL.Add(' FROM articulos_componentes ac,(SELECT lp.ide,lp.idea,lp.idea2,sum(cajas) as cajas,aa.id as id_envase FROM lotes_pesadas lp,articulos_almacen aa where aa.ide=lp.ide and aa.codigo=lp.id_envase '); qaux.SQL.Add(' and lp.ide='+qpesadasidempresa.AsString+' and lp.idea='+qpesadasid.AsString+' and lp.idea2='+qpesadasidea.AsString+' group by lp.id_envase) as lp '); qaux.SQL.Add(' where ac.idempresa=lp.ide and ac.idarticuloalmacen=lp.id_envase '); qaux.SQL.Add(' union '); // materiales de los formatos qaux.SQL.Add(' SELECT ac.ide,ac.idcfg,ac.idaf,(ac.cantidad*lp.cajas) as cantidadtotal,(ac.peso*lp.cajas) as pesototal,(ac.coste*lp.cajas) as preciototal FROM '); qaux.SQL.Add(' configuraciones_detalle ac,(SELECT lp.ide,lp.idea,lp.idea2,sum(cajas) as cajas,aa.id as id_envase FROM lotes_pesadas lp, '); qaux.SQL.Add(' configuraciones aa where aa.ide=lp.ide and aa.id=lp.id_formato and lp.ide='+qpesadasidempresa.AsString+' and lp.idea='+qpesadasid.AsString+' and lp.idea2='+qpesadasidea.AsString+' group by lp.id_envase) as lp '); qaux.SQL.Add(' where ac.ide=lp.ide and ac.idcfg=lp.id_envase '); qaux.SQL.Add(' union '); //// materiales de los palets qaux.SQL.Add(' SELECT ac.idempresa,ac.idarticuloalmacen,ac.idarticulof,(ac.cantidad*'+qpesadasnum_palets.AsString+') as cantidadtotal,(ac.peso*'+qpesadasnum_palets.AsString+') as pesototal,(ac.preciocoste*'+qpesadasnum_palets.AsString+') as preciototal'); qaux.SQL.Add(' FROM articulos_componentes ac where ac.idempresa='+qpesadasidempresa.AsString+' and ac.idarticuloalmacen=(select id from articulos_almacen where codigo='+''''+qpesadasid_palet.AsString+''''+')'); qaux.SQL.Add(' ) as ea_materiales_tmp group by idarticulof '); qaux.execsql; end; qaux.sql.clear; qaux.sql.Add('select sum(peso),sum(precio) from ea_materiales where ide='+qpesadasidempresa.AsString+' and idea='+qpesadasid.AsString+' and idea2='+qpesadasidea.AsString); qaux.open; qpesadas.Edit; qpesadastara.Value:=qaux.Fields[0].AsFloat; qpesadascosto_materiales.Value:=qaux.Fields[1].AsFloat; qpesadas.Post; qpesadas.next end; pbar.Visible:=false; showmessage('¡¡¡Actualización realizada¡¡¡¡¡'); qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('update articulosf af set stock=(select sum(stock) as stock from entradas_detalle where id_propio=af.codigo and idempresa=af.idempresa group by id_propio )'); qaux.ExecSQL; qaux.SQL.Clear; qaux.SQL.Add('update articulosf af set preciocoste=(SELECT SUM((SELECT PRECIO*STOCK FROM entradas_detalle WHERE ID=ed.id))/sum(stock) FROM `entradas_detalle` ed where id_propio=af.codigo) where idempresa=af.idempresa and codigo=af.codigo'); qaux.ExecSQL; qaux.SQL.Clear; qaux.SQL.Add('select * from articulosf where stock_minimo>stock and avisar_stock=1'); qaux.Open; end; procedure Trecalculostock.FormKeyPress(Sender: TObject; var Key: Char); begin if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Trecalculostock.FormShow(Sender: TObject); begin qinventarios.Open; qstockdetalle.Open; end; end. ======================================== FICHERO: fseleccionartaquilla.pas ======================================== unit fseleccionartaquilla; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.DBGrids, Data.DB; type Tseleccionartaquilla = class(TForm) dsqtaquillas: TDataSource; DBGrid1: TDBGrid; procedure DBGrid1DblClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var seleccionartaquilla: Tseleccionartaquilla; implementation {$R *.dfm} uses empleados; procedure Tseleccionartaquilla.DBGrid1DblClick(Sender: TObject); begin close; end; end. ======================================== FICHERO: fselecparcelas.pas ======================================== unit fselecparcelas; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Data.DB, ZAbstractRODataset, ZDataset, Vcl.StdCtrls, Vcl.DBCtrls, ZAbstractDataset; type Tselecparcelas = class(TForm) qvariedadesparcelas: TZReadOnlyQuery; qparcelas: TZReadOnlyQuery; qvariedadesparcelasvariedad: TWideStringField; dsqvariedades: TDataSource; Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; Panel4: TPanel; DBGrid1: TDBGrid; DBGrid2: TDBGrid; qparcelascodpar: TWideStringField; qparcelasnombre: TWideStringField; qparcelassuperficie: TFloatField; qparcelasancho_calle: TFloatField; qparcelasempresa: TIntegerField; dsqparcelas: TDataSource; DBGrid3: TDBGrid; DBText1: TDBText; dsrecomendaciones: TDataSource; Label1: TLabel; DBText2: TDBText; Label2: TLabel; DBText3: TDBText; Label3: TLabel; DBText4: TDBText; Label4: TLabel; DBText5: TDBText; Label5: TLabel; DBText6: TDBText; Label6: TLabel; DBText7: TDBText; Label7: TLabel; dsqparcelasrecomendacion: TDataSource; Button1: TButton; Button2: TButton; qparcelasrecomendacion: TZQuery; qparcelasnumero: TWideStringField; qparcelasrecomendacionid: TIntegerField; qparcelasrecomendacionide: TIntegerField; qparcelasrecomendacionidtb: TIntegerField; qparcelasrecomendacionparcela: TWideStringField; qparcelasrecomendacionsuperficie: TFloatField; qparcelasrecomendacionancho_calle: TFloatField; qparcelasrecomendaciondistancialineal: TFloatField; qparcelasrecomendacionidparcela: TWideStringField; procedure FormShow(Sender: TObject); procedure dsqvariedadesDataChange(Sender: TObject; Field: TField); procedure Button2Click(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var selecparcelas: Tselecparcelas; implementation {$R *.dfm} uses ftratamientosbase; procedure Tselecparcelas.Button1Click(Sender: TObject); begin qparcelasrecomendacion.delete; qparcelas.Refresh; end; procedure Tselecparcelas.Button2Click(Sender: TObject); begin qparcelasrecomendacion.Append; qparcelasrecomendacionide.value:=tratamientosbase.qtratamientoside.AsInteger; qparcelasrecomendacionidtb.value:=tratamientosbase.qtratamientosid.AsInteger; qparcelasrecomendacionidparcela.value:=qparcelasnumero.AsSTRING; qparcelasrecomendacionparcela.value:=qparcelasnombre.AsString; qparcelasrecomendacionsuperficie.value:=qparcelassuperficie.AsFloat; qparcelasrecomendacionancho_calle.value:=qparcelasancho_calle.AsFloat; qparcelasrecomendacion.Post; qparcelas.Refresh; qparcelasrecomendacion.Refresh end; procedure Tselecparcelas.dsqvariedadesDataChange(Sender: TObject; Field: TField); var vvariedad:string; begin qparcelas.Close; qparcelas.Prepare; qparcelas.ParamByName('EMPRESA').AsInteger:=tratamientosbase.qtratamientoside.AsInteger; if qvariedadesparcelasvariedad.AsString=' CUALQUIERA' then vvariedad:='%' else vvariedad:=qvariedadesparcelasvariedad.AsString; qparcelas.ParamByName('VARIEDAD').AsString:=vvariedad; qparcelas.ParamByName('RECOMENDACION').AsInteger:=tratamientosbase.qtratamientosid.AsInteger; qparcelas.Open; end; procedure Tselecparcelas.FormShow(Sender: TObject); begin qvariedadesparcelas.open; qparcelasrecomendacion.Close; qparcelasrecomendacion.Prepare; qparcelasrecomendacion.ParamByName('EMPRESA').AsInteger:=tratamientosbase.qtratamientoside.asinteger; qparcelasrecomendacion.ParamByName('TRATAMIENTO').AsInteger:=tratamientosbase.qtratamientosid.asinteger; qparcelasrecomendacion.Open; end; end. ======================================== FICHERO: fselectalbaranes.pas ======================================== unit fselectalbaranes; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls; type Tseleccionaralbaranes = class(TForm) Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; DBGrid3: TDBGrid; Panel9: TPanel; btALnuevo: TButton; Button1: TButton; panelpedidos: TPanel; Panel6: TPanel; DBGrid2: TDBGrid; qaux: TZQuery; Button2: TButton; Button3: TButton; DBGrid1: TDBGrid; DBGrid4: TDBGrid; qinsertarfacturasdetalles: TZQuery; actualizaralbaranes: TZQuery; actualizaralbaranesdetalles: TZQuery; actualizarpedidosdetalle: TZQuery; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btALnuevoClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var seleccionaralbaranes: Tseleccionaralbaranes; const rojo=$00AAAAFF; amarillo=$00B9FFFF; verde=$00C7FBAA; azul=$00FFFFBB; implementation {$R *.dfm} uses ffacturas; procedure Tseleccionaralbaranes.btALnuevoClick(Sender: TObject); var serie,empresa,idfactura,idalbaran,observaciones:string; pesobruto,pesoneto,pesonetoteorico,numpalets,documento:string; facturado:integer; begin documento:=''; idfactura:=facturas.facturasid.asstring; serie:=facturas.facturasserie.AsString; empresa:=facturas.facturasidempresa.AsString; idalbaran:=facturas.qalbaranesid.asstring; observaciones:=facturas.facturasobservaciones.asstring; facturas.facturas.Edit; facturas.facturasobservaciones.value:=observaciones+' '+facturas.qalbaranesobservaciones.AsString; facturas.facturas.Post; facturas.facturasdetalle.Append; facturas.facturasdetalleidempresa.Value:=strtoint(empresa); facturas.facturasdetalleserie.Value:=serie; facturas.facturasdetalleidfactura.Value:=strtoint(idfactura); facturas.facturasdetalledescripcion.Value:='Albaran '+idalbaran+' de fecha:'+facturas.qalbaranesfecha.AsString; facturas.facturasdetalletipoiva.value:=0; facturas.facturasdetalle.Post; qaux.sql.clear; qaux.sql.add('insert into facturas_detalles (idempresa,serie,idfactura,idarticulo,descripcion,cal,lote,bultos,cantidad,precio,descuento,totaldescuento,base,tipoiva,iva,total,idalbaran,coste_transporte,coste_comision,coste_otros,palets,'); qaux.sql.add('pesobruto,envase,referencia,ean,unidadescaja,mprima,parcela,formato,pais)'); qaux.sql.add(' (SELECT '+''''+empresa+''''+' as idempresa,'+''''+serie+''''+' as serie,'+''''+idfactura+''''+' as idfactura,idarticulo,descripcion,cal,lote,bultos,cantidad,'); qaux.sql.add('precio,descuento,totaldescuento,base,tipoiva,iva,total,idalbaran,coste_transporte,coste_comision,coste_otros,palets,pesobruto,envase,referencia,ean,unidadescaja,mprima,parcela,formato,pais'); qaux.sql.add(' FROM albaranes_detalles where id='+facturas.qalbaranesdetalleid.AsString+')'); qaux.execsql; facturas.qalbaranesdetalle.Edit; facturas.qalbaranesdetalleidfactura.AsInteger:=strtoint(idfactura); facturas.qalbaranesdetalle.Post; facturas.qalbaranesdetalle.Refresh; if facturas.qalbaranesdetalle.RecordCount=0 then begin facturado:=1; actualizarpedidosdetalle.Close; actualizarpedidosdetalle.Prepare; actualizarpedidosdetalle.ParamByName('documento').AsString:= serie+'/'+idfactura; actualizarpedidosdetalle.ParamByName('albaran').AsString:= serie+'/'+idalbaran; actualizarpedidosdetalle.ExecSQL; end else begin facturado:=0; actualizarpedidosdetalle.Close; actualizarpedidosdetalle.Prepare; actualizarpedidosdetalle.ParamByName('documento').AsString:=serie+'/'+idfactura; actualizarpedidosdetalle.ParamByName('albaran').AsString:= serie+'/'+idalbaran; actualizarpedidosdetalle.ExecSQL; end; qaux.SQL.Clear; qaux.SQL.Add('select distinct(idfactura) from albaranes_detalles where idfactura='+idfactura+' and serie='+''''+serie+''''); qaux.Open; if qaux.RecordCount>0 then begin documento:=documento+qaux.Fields[0].AsString+' '; qaux.next; end; facturas.qalbaranes.edit; facturas.qalbaranesidfactura.value:=facturas.facturasid.asinteger; facturas.qalbaranesfacturado.Value:=facturado; facturas.qalbaranesdocumento.Value:='Factura Nº: '+documento; facturas.qalbaranes.post; facturas.qalbaranes.Refresh; facturas.qalbaranesdetalle.Refresh; facturas.qalbaranes2.Refresh; facturas.qalbaranesdetalle2.Refresh; // facturas.facturasdetalle.Refresh; end; procedure Tseleccionaralbaranes.Button1Click(Sender: TObject); var serie,empresa,idalbaran,idfactura:string; begin serie:=facturas.qalbaranes2serie.Asstring; empresa:=facturas.qalbaranes2idempresa.Asstring; idalbaran:=facturas.qalbaranes2id.Asstring; idfactura:=facturas.qalbaranes2idfactura.asstring; qaux.sql.clear; qaux.sql.add('delete from facturas_detalles where (idempresa,serie,idfactura,idarticulo) in '); qaux.sql.add(' (SELECT idempresa,serie,'+''''+idfactura+''''+' as idfactura,idarticulo FROM albaranes_detalles where id='+facturas.qalbaranesdetalle2id.asstring+' and idfactura='+idfactura+' and idempresa='+empresa+' and serie='+''''+serie+''''+')'); qaux.execsql; qaux.sql.clear; qaux.sql.add('update albaranes_detalles set idfactura=null where id='+facturas.qalbaranesdetalle2id.AsString); qaux.execsql; facturas.qalbaranes2.Edit; facturas.qalbaranes2facturado.Value:=0; facturas.qalbaranes2.Post; facturas.qalbaranesdetalle.Refresh; facturas.qalbaranes.Refresh; facturas.qalbaranesdetalle2.Refresh; facturas.qalbaranes2.Refresh; facturas.facturasdetalle.Refresh; if facturas.qalbaranesdetalle2.RecordCount=0 then begin actualizarpedidosdetalle.Close; actualizarpedidosdetalle.Prepare; actualizarpedidosdetalle.ParamByName('documento').AsString:=''; actualizarpedidosdetalle.ParamByName('albaran').AsString:= serie+'/'+idalbaran; actualizarpedidosdetalle.ExecSQL; end; end; procedure Tseleccionaralbaranes.Button2Click(Sender: TObject); var serie,empresa,idfactura,idalbaran,observaciones:string; pesobruto,pesoneto,pesonetoteorico,numpalets:string; begin idfactura:=facturas.facturasid.asstring; serie:=facturas.facturasserie.AsString; empresa:=facturas.facturasidempresa.AsString; idalbaran:=facturas.qalbaranesid.asstring; observaciones:=facturas.facturasobservaciones.asstring; facturas.facturas.Edit; facturas.facturasobservaciones.value:=observaciones+' '+facturas.qalbaranesobservaciones.AsString; facturas.facturascomision.value:=facturas.qalbaranescomision.Asfloat; facturas.facturas.Post; facturas.facturasdetalle.Append; facturas.facturasdetalleidempresa.Value:=strtoint(empresa); facturas.facturasdetalleserie.Value:=serie; facturas.facturasdetalleidfactura.Value:=strtoint(idfactura); facturas.facturasdetalledescripcion.Value:='Albaran '+idalbaran+' de fecha:'+facturas.qalbaranesfecha.AsString; facturas.facturasdetalletipoiva.value:=0; facturas.facturasdetalle.Post; qinsertarfacturasdetalles.close; qinsertarfacturasdetalles.prepare; qinsertarfacturasdetalles.ParamByName('EMPRESA').AsInteger:=facturas.facturasidempresa.AsInteger; qinsertarfacturasdetalles.ParamByName('FACTURA').AsInteger:=facturas.facturasid.AsInteger; qinsertarfacturasdetalles.ParamByName('ALBARAN').AsInteger:=strtoint(idalbaran); qinsertarfacturasdetalles.ParamByName('SERIE').AsString:=facturas.facturasserie.AsString; qinsertarfacturasdetalles.ExecSQL; actualizaralbaranesdetalles.Close; actualizaralbaranesdetalles.Prepare; actualizaralbaranesdetalles.ParamByName('factura').AsInteger:= facturas.facturasid.AsInteger; actualizaralbaranesdetalles.ParamByName('empresa').AsInteger:= facturas.facturasidempresa.AsInteger; actualizaralbaranesdetalles.ParamByName('serie').AsString:= facturas.facturasserie.Asstring; actualizaralbaranesdetalles.ParamByName('albaran').AsInteger:= strtoint(idalbaran); actualizaralbaranesdetalles.ExecSQL; actualizaralbaranes.Close; actualizaralbaranes.Prepare; actualizaralbaranes.ParamByName('albaran').AsInteger:= strtoint(idalbaran); actualizaralbaranes.ParamByName('serie').Asstring:= facturas.facturasserie.Asstring; actualizaralbaranes.ParamByName('documento').AsString:= 'Factura Nº: '+facturas.facturasid.AsString; actualizaralbaranes.ParamByName('factura').AsInteger:=facturas.facturasid.AsInteger; actualizaralbaranes.ExecSQL; actualizarpedidosdetalle.Close; actualizarpedidosdetalle.Prepare; actualizarpedidosdetalle.ParamByName('documento').AsString:= facturas.facturasserie.Asstring+'/'+facturas.facturasid.AsString; actualizarpedidosdetalle.ParamByName('albaran').AsString:= serie+'/'+idalbaran; actualizarpedidosdetalle.ExecSQL; {qaux.sql.clear; qaux.sql.add('update albaranes_detalles set idfactura='+facturas.facturasid.AsString+' where idempresa='+empresa+' and serie='+''''+serie+''''+' and idalbaran='+idalbaran); qaux.execsql;} { facturas.qalbaranes.edit; facturas.qalbaranesidfactura.value:=facturas.facturasid.asinteger; facturas.qalbaranesfacturado.Value:=1; facturas.qalbaranesdocumento.Value:='Factura Nº: '+facturas.facturasid.AsString; facturas.qalbaranes.post; } { qaux.sql.clear; qaux.sql.add('insert into facturas_detalles (idempresa,serie,idfactura,idarticulo,descripcion,cal,lote,bultos,cantidad,precio,descuento,totaldescuento,base,tipoiva,iva,total,idalbaran,coste_transporte,coste_comision,palets)'); qaux.sql.add(' (SELECT '+''''+empresa+''''+' as idempresa,'+''''+serie+''''+' as serie,'+''''+idfactura+''''+' as idfactura,idarticulo,descripcion,cal,lote,bultos,cantidad,'); qaux.sql.add('precio,descuento,totaldescuento,base,tipoiva,iva,total,idalbaran,coste_transporte,coste_comision,palets'); qaux.sql.add(' FROM albaranes_detalles where (idalbaran,idempresa,serie) in (select id,idempresa,serie from albaranes where idfactura='+idfactura+' and idempresa='+empresa+' and serie='+''''+serie+''''+' and id='+idalbaran+'))'); qaux.execsql;} facturas.qalbaranesdetalle.Refresh; facturas.qalbaranes.Refresh; facturas.qalbaranes2.Refresh; facturas.qalbaranesdetalle2.Refresh; facturas.facturasdetalle.Refresh; { pesobruto:=qaux.fields[0].asstring; pesobruto:=stringreplace(pesobruto,',','.',[rfreplaceall]); pesoneto:=qaux.fields[1].asstring; pesoneto:=stringreplace(pesoneto,',','.',[rfreplaceall]); pesonetoteorico:=qaux.fields[2].asstring; pesonetoteorico:=stringreplace(pesonetoteorico,',','.',[rfreplaceall]); numpalets:=qaux.fields[3].asstring; numpalets:=stringreplace(numpalets,',','.',[rfreplaceall]); qaux.SQL.Clear; qaux.SQL.Add('update facturas set peso_bruto='+pesobruto+',kilos='+pesoneto+',kilosventa='+pesonetoteorico+',numpalets='+numpalets+' where serie='+''''+serie+''''+' and id='+idfactura+' and idempresa='+facturas.facturasidempresa.AsString); qaux.execsql;} facturas.facturas.refresh; facturas.facturas.Locate('serie,id',vararrayof([serie,idfactura]),[locaseinsensitive]) end; procedure Tseleccionaralbaranes.Button3Click(Sender: TObject); var serie,empresa,idalbaran,idfactura:string; begin serie:=facturas.qalbaranes2serie.Asstring; empresa:=facturas.qalbaranes2idempresa.Asstring; idalbaran:=facturas.qalbaranes2id.Asstring; idfactura:=facturas.qalbaranes2idfactura.asstring; qaux.sql.clear; qaux.sql.add('delete from facturas_detalles where (idempresa,serie,idfactura,idarticulo) in '); qaux.sql.add(' (SELECT idempresa,serie,'+''''+idfactura+''''+' as idfactura,idarticulo FROM albaranes_detalles where (idempresa,serie,idalbaran) in (select idempresa,serie,id from albaranes where idfactura='+idfactura+' and idempresa='+empresa+' and serie='+''''+serie+''''+' and id='+idalbaran+'))'); qaux.execsql; qaux.SQL.Clear; qaux.SQL.Add('update albaranes set idfactura=null,facturado=0,documento=null where idempresa='+empresa+' and serie='+''''+serie+''''+' and id='+idalbaran); qaux.ExecSQL; qaux.SQL.Clear; qaux.SQL.Add('update albaranes_detalles set idfactura=null where idempresa='+empresa+' and serie='+''''+serie+''''+' and idalbaran='+idalbaran); qaux.ExecSQL; actualizarpedidosdetalle.Close; actualizarpedidosdetalle.Prepare; actualizarpedidosdetalle.ParamByName('documento').AsString:=''; actualizarpedidosdetalle.ParamByName('albaran').AsString:=serie+'/'+idalbaran; actualizarpedidosdetalle.ExecSQL; facturas.qalbaranes.Refresh; facturas.qalbaranesdetalle.Refresh; facturas.qalbaranes2.Refresh; facturas.qalbaranesdetalle2.Refresh; facturas.facturasdetalle.Refresh; end; procedure Tseleccionaralbaranes.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; end. ======================================== FICHERO: fselectpedidos.pas ======================================== unit fselectpedidos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls,falbaranes, Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset; type Tseleccionarpedidos = class(TForm) panelpedidos: TPanel; Panel6: TPanel; DBGrid2: TDBGrid; Panel5: TPanel; DBGrid1: TDBGrid; Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; DBGrid3: TDBGrid; Panel4: TPanel; DBGrid4: TDBGrid; Panel9: TPanel; btALnuevo: TButton; Button1: TButton; Panel7: TPanel; qaux: TZQuery; qidspedidodetalle: TZQuery; insertarpedidodetalle: TZQuery; actualizarids: TZQuery; qidspedidodetalleidea: TIntegerField; qidspedidodetallebultos: TIntegerField; qidspedidodetallelote: TIntegerField; procedure btALnuevoClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBGrid4DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); private { Private declarations } public { Public declarations } end; var seleccionarpedidos: Tseleccionarpedidos; const rojo=$00AAAAFF; amarillo=$00B9FFFF; verde=$00C7FBAA; azul=$00FFFFBB; implementation {$R *.dfm} procedure Tseleccionarpedidos.btALnuevoClick(Sender: TObject); var iva,num_albaran,idalbaran,serie,empresa,id,idpedido,desclinalbaran,idiva:string; pesobruto,pesoneto,pesonetoteorico,numpalets,precio:string; cajas,idpesada:integer; begin id:=albaranes.qpedidosdetalleid.asstring; idpedido:=albaranes.qpedidospedidocliente.asstring; serie:=albaranes.albaranesserie.AsString; idalbaran:=albaranes.albaranesid.asstring; num_albaran:=serie+'/'+idalbaran; empresa:=albaranes.albaranesidempresa.AsString; precio:=albaranes.qpedidosdetalleprecio.asstring; desclinalbaran:=albaranes.qpedidosdetalledesc_producto.AsString+' '+albaranes.qpedidosdetalledesc_calidad.AsString+' '+albaranes.qpedidosdetalledesc_envase.AsString+' '+albaranes.qpedidosdetalledesc_acabado.AsString; qaux.sql.clear; qaux.sql.add('select exento_iva from clientes where id='+albaranes.albaranesidcliente.AsString); qaux.Open; idiva:=qaux.Fields[0].AsString; qaux.sql.clear; qaux.sql.add('select tipo from tipos_iva where id='+idiva); qaux.Open; iva:=''''+qaux.fields[0].asstring+''''; albaranes.qpedidosdetalle.edit; albaranes.qpedidosdetalleidalbaran.value:=num_albaran;//albaranes.albaranesserie.asstring+'/'+albaranes.albaranesid.asstring; albaranes.qpedidosdetalle.post; albaranes.qpedidos.Refresh; albaranes.qpedidos.Locate('pedidocliente',vararrayof([idpedido]),[locaseinsensitive]); albaranes.qpedidos2.Refresh; albaranes.qpedidos2.Locate('pedidocliente',vararrayof([idpedido]),[locaseinsensitive]); albaranes.qpedidosdetalle.Refresh; albaranes.qpedidosdetalle2.Refresh; albaranes.albaranes.refresh; albaranes.albaranes.Locate('serie,id',vararrayof([serie,idalbaran]),[locaseinsensitive]); qidspedidodetalle.close; qidspedidodetalle.Prepare; qidspedidodetalle.ParamByName('empresa').Asstring:=empresa; qidspedidodetalle.ParamByName('serie').AsString:= serie; qidspedidodetalle.ParamByName('albaran').AsInteger:= strtoint(idalbaran); qidspedidodetalle.ParamByName('desclinalbaran').AsString:= desclinalbaran; qidspedidodetalle.ParamByName('idpedidodetalle').AsInteger:= strtoint(id); qidspedidodetalle.open; { qaux.sql.clear; qaux.sql.add(' (SELECT '+''''+empresa+''''+' as idempresa,'+''''+serie+''''+' as serie,'+''''+idalbaran+''''+' as idalbaran,lp.idea,'+''''+desclinalbaran+''''+' as descripcion,lp.desc_calibre as cal,lp.lote,cajas as bultos,pesoneto_teorico as cantidad,'); qaux.sql.add(''''+'0'+''''+' as precio,'+''''+'0'+''''+' as descuento,'+''''+'0'+''''+' as totaldescuento,'+''''+'0'+''''+' as base,'+iva+' as tipoiva,'+''''+'0'+''''+' as iva,'+''''+'0'+''''+' as total'); qaux.sql.add(' FROM lotes_pesadas lp,materias_primas mp where lp.mprima=mp.id and (lp.idea,lp.idea2) in (select id,idea from ea_pesadas where (idea=0 or iddestino in (select id from almacenes where final=1)) and idpedido in (select id from pedidosdetalle'); qaux.sql.add(' where idalbaran='+''''+num_albaran+''''+' and ide='+empresa+' and id='+id+')))'); qaux.open;} if qidspedidodetalle.RecordCount>0 then begin idpesada:=0; while not qidspedidodetalle.Eof do begin if idpesada<>qidspedidodetalleidea.asinteger then begin idpesada:=qidspedidodetalleidea.asinteger; cajas:=qidspedidodetallebultos.asinteger; end else begin idpesada:=qidspedidodetalleidea.asinteger; cajas:=0; end; insertarpedidodetalle.Close; insertarpedidodetalle.Prepare; insertarpedidodetalle.ParamByName('empresa').AsInteger:=strtoint(empresa); insertarpedidodetalle.ParamByName('serie').AsString:=serie; insertarpedidodetalle.ParamByName('albaran').AsInteger:=strtoint(idalbaran); insertarpedidodetalle.ParamByName('desclinalbaran').AsString:=desclinalbaran; insertarpedidodetalle.ParamByName('cajas').AsInteger:=cajas; insertarpedidodetalle.ParamByName('precio').AsFloat:=strtofloat(precio); insertarpedidodetalle.ParamByName('idpesada').AsInteger:=idpesada; insertarpedidodetalle.ParamByName('lote').Asstring:=qidspedidodetallelote.asstring; insertarpedidodetalle.ParamByName('idpedido').AsInteger:=strtoint(id); insertarpedidodetalle.execsql; qidspedidodetalle.Next; end; { qaux.sql.clear; qaux.sql.add('insert into albaranes_detalles (idempresa,serie,idalbaran,idarticulo,descripcion,cal,lote,bultos,cantidad,precio,descuento,totaldescuento,base,tipoiva,iva,total)'); qaux.sql.add(' (SELECT '+''''+empresa+''''+' as idempresa,'+''''+serie+''''+' as serie,'+''''+idalbaran+''''+' as idalbaran,lp.idea,'+''''+desclinalbaran+''''+' as descripcion,lp.desc_calibre as cal,lp.lote,cajas as bultos,pesoneto_teorico as cantidad,'); qaux.sql.add(''''+precio+''''+' as precio,'+''''+'0'+''''+' as descuento,'+''''+'0'+''''+' as totaldescuento,'+''''+'0'+''''+' as base,'+iva+' as tipoiva,'+''''+'0'+''''+' as iva,'+''''+'0'+''''+' as total'); qaux.sql.add(' FROM lotes_pesadas lp,materias_primas mp where lp.mprima=mp.id and (lp.idea,lp.idea2) in (select id,idea from ea_pesadas where (idea=0 or iddestino in (select id from almacenes where final=1)) and idpedido in (select id from pedidosdetalle'); qaux.sql.add(' where idalbaran='+''''+num_albaran+''''+' and ide='+empresa+' and id='+id+')))'); qaux.execsql; } albaranes.albaranesdetalle.Refresh; actualizarids.close; actualizarids.Prepare; actualizarids.ParamByName('serie').AsString:=serie; actualizarids.ParamByName('albaran').Asinteger:=strtoint(idalbaran); actualizarids.ParamByName('idpedidodetalle').Asinteger:=strtoint(id); actualizarids.ParamByName('empresa').Asinteger:=strtoint(empresa); actualizarids.ExecSQL; { qaux.close; qaux.SQL.Clear; qaux.SQL.Add('update ea_pesadas set id_palet2='+''''+'FACTURANDO'+''''+',idalbaran='+''''+num_albaran+''''+' where idpedido='+id+' and idempresa='+empresa); qaux.ExecSQL;} qaux.SQL.Clear; qaux.SQL.Add('select sum(peso_bruto-tara0),sum(peso_neto),sum(peso_neto_teorico),sum(num_palets) from ea_pesadas where idalbaran='+''''+num_albaran+''''+' and idempresa='+albaranes.albaranesidempresa.asstring); qaux.open; pesobruto:=qaux.fields[0].asstring; pesobruto:=stringreplace(pesobruto,',','.',[rfreplaceall]); pesoneto:=qaux.fields[1].asstring; pesoneto:=stringreplace(pesoneto,',','.',[rfreplaceall]); pesonetoteorico:=qaux.fields[2].asstring; pesonetoteorico:=stringreplace(pesonetoteorico,',','.',[rfreplaceall]); numpalets:=qaux.fields[3].asstring; numpalets:=stringreplace(numpalets,',','.',[rfreplaceall]); qaux.SQL.Clear; qaux.SQL.Add('update albaranes set peso_bruto='+pesobruto+',kilos=+'+pesoneto+',kilosventa='+pesonetoteorico+',numpalets=+'+numpalets+' where serie='+''''+serie+''''+' and id='+idalbaran+' and idempresa='+albaranes.albaranesidempresa.AsString);; qaux.execsql; end else showmessage('NO HAY ID ASOCIADO A LA LINEA DE PEDIDO'); end; procedure Tseleccionarpedidos.Button1Click(Sender: TObject); var serie,empresa,idalbaran,idalbaran2,id,num_albaran:string; pesobruto,pesoneto,pesonetoteorico,numpalets:string; begin id:=albaranes.qpedidosdetalle2id.asstring; idalbaran:=albaranes.qpedidosdetalle2idalbaran.asstring; num_albaran:=idalbaran; idalbaran2:=albaranes.albaranesserie.AsString+'/'+albaranes.albaranesid.AsString; empresa:=albaranes.qpedidosdetalle2ide.Asstring; qaux.sql.clear; qaux.sql.add('delete from albaranes_detalles where idarticulo in '); qaux.sql.add(' (select id from ea_pesadas where idpedido in (select id from pedidosdetalle where idalbaran='+''''+idalbaran+''''+' and ide='+empresa+' and id='+id+'))'); // qaux.sql.add(' (SELECT idea FROM lotes_pesadas lp,materias_primas mp where lp.mprima=mp.id and lp.idea in (select id from ea_pesadas where idpedido in (select id from pedidosdetalle where idalbaran='+''''+idalbaran+''''+' and ide='+empresa+' and id='+id+')))'); qaux.execsql; qaux.SQL.Clear; qaux.SQL.Add('update pedidosdetalle set idalbaran=null where ide='+empresa+' and id='+id); qaux.ExecSQL; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('update ea_pesadas set id_palet2='+''''+'TRIGGUER_OFF'+''''+',idalbaran=null where idpedido='+id+' and idempresa='+empresa); qaux.ExecSQL; albaranes.qpedidos2.Close; albaranes.qpedidos2.SQL.Clear; albaranes.qpedidos2.SQL.Add('select p.id,p.ide,p.idcliente,p.iddestino,p.fecha_pedido,p.fecha_entrega,c.nombre_corto as cliente,d.descripcion as destino,p.pedidocliente from pedidos p,clientes c,clientes_destinos d where'); albaranes.qpedidos2.SQL.Add(' p.ide=c.idempresa and p.idcliente=c.id and p.ide=d.idempresa and p.idcliente=d.idcliente and p.iddestino=d.codigo and'); albaranes.qpedidos2.SQL.Add(' p.id in (select pd.idpedido from pedidosdetalle pd where pd.idalbaran='+''''+albaranes.albaranesserie.AsString+'/'+albaranes.albaranesid.AsString+''''+')'); albaranes.qpedidos2.Open; albaranes.qpedidosdetalle2.close; albaranes.qpedidosdetalle2.SQL.Clear; albaranes.qpedidosdetalle2.SQL.Add('select * from pedidosdetalle where idalbaran='+''''+albaranes.albaranesserie.asstring+'/'+albaranes.albaranesid.AsString+''''); albaranes.qpedidosdetalle2.Open; albaranes.qpedidosdetalle.Refresh; albaranes.qpedidos.Refresh; albaranes.albaranesdetalle.Refresh; qaux.SQL.Clear; qaux.SQL.Add('select sum(peso_bruto-tara0),sum(peso_neto),sum(peso_neto_teorico),sum(num_palets) from ea_pesadas where idalbaran='+''''+idalbaran+''''+' and idempresa='+albaranes.albaranesidempresa.asstring); qaux.open; pesobruto:=qaux.fields[0].asstring; pesobruto:=stringreplace(pesobruto,',','.',[rfreplaceall]); if pesobruto='' then pesobruto:='0'; pesoneto:=qaux.fields[1].asstring; pesoneto:=stringreplace(pesoneto,',','.',[rfreplaceall]); if pesoneto='' then pesoneto:='0'; pesonetoteorico:=qaux.fields[2].asstring; pesonetoteorico:=stringreplace(pesonetoteorico,',','.',[rfreplaceall]); if pesonetoteorico='' then pesonetoteorico:='0'; numpalets:=qaux.fields[3].asstring; numpalets:=stringreplace(numpalets,',','.',[rfreplaceall]); if numpalets='' then numpalets:='0'; qaux.SQL.Clear; qaux.SQL.Add('update albaranes set peso_bruto='+pesobruto+',kilos=+'+pesoneto+',kilosventa='+pesonetoteorico+',numpalets=+'+numpalets+' where serie='+''''+albaranes.albaranesserie.asstring+''''+' and id='+albaranes.albaranesid.asstring+' and idempresa='+albaranes.albaranesidempresa.AsString);; qaux.execsql; serie:=albaranes.albaranesserie.AsString; idalbaran:=albaranes.albaranesid.AsString; albaranes.albaranes.refresh; albaranes.albaranes.Locate('serie,id',vararrayof([serie,idalbaran]),[locaseinsensitive]) end; procedure Tseleccionarpedidos.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if albaranes.qpedidosdetallecantidadservida.Asinteger>albaranes.qpedidosdetallecantidad.Asinteger then begin dbgrid1.Canvas.brush.Color := rojo; end; if albaranes.qpedidosdetallecantidadservida.Asinteger=albaranes.qpedidosdetallecantidad.Asinteger then begin dbgrid1.Canvas.brush.Color := verde; end; dbgrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure Tseleccionarpedidos.DBGrid4DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if albaranes.qpedidosdetalle2cantidadservida.Asinteger>albaranes.qpedidosdetalle2cantidad.Asinteger then begin dbgrid4.Canvas.brush.Color := rojo; end; if albaranes.qpedidosdetalle2cantidadservida.Asinteger=albaranes.qpedidosdetalle2cantidad.Asinteger then begin dbgrid4.Canvas.brush.Color := verde; end; dbgrid4.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; end. ======================================== FICHERO: fstockalmacen.pas ======================================== unit fstockalmacen; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls, Data.DB, ZAbstractRODataset, ZDataset, Vcl.Grids, Vcl.DBGrids; type Tstocksalmacen = class(TForm) Panel1: TPanel; Button1: TButton; Button2: TButton; DBGrid1: TDBGrid; dsqstock: TDataSource; qstock: TZReadOnlyQuery; Panel2: TPanel; Label1: TLabel; Edit1: TEdit; Button3: TButton; qstockid: TIntegerField; qstockfamilia: TWideStringField; qstockcodigo: TWideStringField; qstockdescripcion: TWideStringField; qstockstock: TFloatField; SaveDialog1: TSaveDialog; procedure FormShow(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var stocksalmacen: Tstocksalmacen; implementation uses principal; {$R *.dfm} procedure Tstocksalmacen.Button1Click(Sender: TObject); var archivo: string; begin SaveDialog1.FileName :='STOCKS DE INSUMOS.xlsx'; SaveDialog1.Execute(); archivo := SaveDialog1.FileName; try base.ExportaraExcel(archivo, 'STOCKS', DBGrid1); finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure Tstocksalmacen.Button3Click(Sender: TObject); var vbuscar:string; begin if edit1.Text='' then vbuscar:='%' else vbuscar:='%'+edit1.Text+'%'; qstock.close; qstock.Prepare; qstock.ParamByName('BUSCAR').AsString:=vbuscar; qstock.Open end; procedure Tstocksalmacen.FormShow(Sender: TObject); begin qstock.close; qstock.Prepare; qstock.ParamByName('BUSCAR').AsString:='%'; qstock.Open end; end. ======================================== FICHERO: ftaquillas.pas ======================================== unit ftaquillas; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZDataset, ZAbstractRODataset, ZAbstractDataset, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids; type Ttaquillas = class(TForm) DBGrid1: TDBGrid; Panel1: TPanel; btnuevo: TButton; btmodificar: TButton; btborrar: TButton; btguardar: TButton; btcancelar: TButton; qtaquillas: TZQuery; qid: TZReadOnlyQuery; qidid: TLargeintField; dsqtaquillas: TDataSource; qtaquillaside: TIntegerField; qtaquillasid: TIntegerField; qtaquillascodigo: TWideStringField; qtaquillasidt: TIntegerField; qtaquillasnombre: TWideStringField; Label1: TLabel; procedure FormShow(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure dsqtaquillasStateChange(Sender: TObject); procedure qtaquillasAfterInsert(DataSet: TDataSet); procedure qtaquillasAfterPost(DataSet: TDataSet); procedure qtaquillasBeforeDelete(DataSet: TDataSet); procedure qtaquillasBeforePost(DataSet: TDataSet); procedure DBGrid1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnuevoClick(Sender: TObject); procedure btmodificarClick(Sender: TObject); procedure btborrarClick(Sender: TObject); procedure btguardarClick(Sender: TObject); procedure btcancelarClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var taquillas: Ttaquillas; implementation {$R *.dfm} uses datos, fbuscarempleado; procedure Ttaquillas.btborrarClick(Sender: TObject); begin qtaquillas.Delete; end; procedure Ttaquillas.btcancelarClick(Sender: TObject); begin qtaquillas.Cancel; end; procedure Ttaquillas.btguardarClick(Sender: TObject); begin qtaquillas.Post; end; procedure Ttaquillas.btmodificarClick(Sender: TObject); begin qtaquillas.edit; end; procedure Ttaquillas.btnuevoClick(Sender: TObject); begin qtaquillas.append; end; procedure Ttaquillas.DBGrid1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (key=115) then begin buscarempleado := Tbuscarempleado.Create(nil); try fbuscarempleado.filtro:=qtaquillasnombre.AsString; buscarempleado.Edit1.Text:=qtaquillasnombre.AsString; buscarempleado.showmodal(); finally if qtaquillas.State in [dsbrowse] then qtaquillas.Edit; qtaquillasidt.Value:=buscarempleado.qempleadosid.Asinteger; qtaquillasnombre.Value:=buscarempleado.qempleadosnombre.Asstring; buscarempleado.Free; end; end; end; procedure Ttaquillas.dsqtaquillasStateChange(Sender: TObject); begin if qtaquillas.State in [dsedit,dsinsert] then begin btnuevo.Enabled:=false; btmodificar.Enabled:=false; btborrar.Enabled:=false; btcancelar.Enabled:=true; btguardar.Enabled:=true; end else begin btnuevo.Enabled:=true; btmodificar.Enabled:=true; btborrar.Enabled:=true; btcancelar.Enabled:=false; btguardar.Enabled:=false; end; end; procedure Ttaquillas.FormKeyPress(Sender: TObject; var Key: Char); begin key:=upcase(key); if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Ttaquillas.FormShow(Sender: TObject); begin qtaquillas.Open; dm.tempresa.Open; end; procedure Ttaquillas.qtaquillasAfterInsert(DataSet: TDataSet); begin qid.close; qid.ParamByName('EMPRESA').AsInteger:=dm.tempresaid.AsInteger; qid.open; if qidid.asstring='' then begin qtaquillasid.value:=1; qtaquillascodigo.value:='1'; end else begin qtaquillasid.Value:=qidid.asinteger; qtaquillascodigo.Value:=qidid.asstring; end; end; procedure Ttaquillas.qtaquillasAfterPost(DataSet: TDataSet); begin qtaquillas.Cancel; qtaquillas.Refresh; end; procedure Ttaquillas.qtaquillasBeforeDelete(DataSet: TDataSet); begin case dm.PedirConfirmacion('¿Confirma que desea borrar esta taquilla?',true,true,false) of mrno:Abort; end; end; procedure Ttaquillas.qtaquillasBeforePost(DataSet: TDataSet); var x:integer; begin if qtaquillas.State in [dsinsert] then qtaquillaside.Value:=dm.tempresaid.AsInteger; if qtaquillas.state=dsinsert then x:=dm.PedirConfirmacion('¿Confirma que desea dar de alta esta taquilla?',true,true,true) else x:=dm.PedirConfirmacion('¿Confirma que desea modificar esta taquilla?',true,true,true); case x of mrno: begin qtaquillas.cancel; abort; end; mrcancel:BEGIN abort; END; end; end; end. ======================================== FICHERO: fticados.pas ======================================== unit fticados; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Data.DB, ZAbstractRODataset, ZDataset, ZAbstractDataset, Vcl.ComCtrls, Vcl.ImgList, frxExportCSV, frxClass, frxExportPDF, frxDBSet, Vcl.DBCtrls,comobj,excel2000, Vcl.Mask,math, frxExportBaseDialog, Bde.DBTables; type Tticados = class(TForm) Panel1: TPanel; Panel2: TPanel; Label1: TLabel; Label2: TLabel; DBGrid1: TDBGrid; qempleados: TZReadOnlyQuery; dsqempleados: TDataSource; Panel3: TPanel; Panel4: TPanel; qticados: TZQuery; dsqticados: TDataSource; Panel5: TPanel; buscarempleado: TEdit; Panel6: TPanel; qticadosid: TLargeintField; qticadoside: TSmallintField; qticadosfecha: TDateField; qticadosidt: TIntegerField; qticadosTRABAJADOR: TWideStringField; qticadoshorasm: TFloatField; qticadoshorasm_m: TFloatField; qticadoshorast: TFloatField; qticadoshorast_m: TFloatField; qticadosnum_horas: TFloatField; qticadosnum_horas_m: TFloatField; qticadosimprimir: TIntegerField; qticadosobservaciones: TWideStringField; qticadosfestivo: TIntegerField; Button1: TButton; ImageList1: TImageList; ticadosdb: TfrxDBDataset; rTicados: TfrxReport; frxPDFExport1: TfrxPDFExport; frxCSVExport1: TfrxCSVExport; qtotalhoras: TZQuery; qtotalhorastotalhoras: TFloatField; dstotalhoras: TDataSource; qtotalhorasidt: TIntegerField; pmodificaciones: TPanel; Label3: TLabel; fdesde: TDateTimePicker; fhasta: TDateTimePicker; Label4: TLabel; Label5: TLabel; DBText1: TDBText; Button2: TButton; lentsal: TComboBox; Label7: TLabel; Button3: TButton; CheckBox1: TCheckBox; Edit2: TEdit; Label9: TLabel; btJexcel: TButton; checkacumulados: TCheckBox; qtotales: TZQuery; dsqtotales: TDataSource; qtotalesidt: TIntegerField; qtotalestrabajador: TWideStringField; qtotalestotalhoras: TFloatField; Label10: TLabel; v_descuento: TEdit; Button4: TButton; qticadosdescuentohoras: TFloatField; Label11: TLabel; v_hora: TMaskEdit; qticadoshorascobrar: TFloatField; Label6: TLabel; v_horas: TEdit; Button5: TButton; qticadosentradam: TTimeField; qticadossalidam: TTimeField; qticadossalidam_m: TTimeField; qticadosentradat: TTimeField; qticadossalidat: TTimeField; qticadossalidat_m: TTimeField; qticadoshorafinmostrar: TTimeField; tgrupo: TDBLookupComboBox; qgrupostrabajadores2: TZReadOnlyQuery; dsqgrupostrabajadores2: TDataSource; qgrupostrabajadores2ide: TIntegerField; qgrupostrabajadores2id: TIntegerField; qgrupostrabajadores2descripcion: TWideStringField; Label8: TLabel; Label212: TLabel; ljcentro: TDBLookupComboBox; Label213: TLabel; ljtrabajo: TDBLookupComboBox; Label214: TLabel; ljhora: TDBLookupComboBox; qparcelas: TZReadOnlyQuery; dsqparcelas: TDataSource; qparcelascodpar: TWideStringField; qparcelasempresa: TIntegerField; qparcelasnombre: TWideStringField; qtipohoras: TZReadOnlyQuery; dsqtipohoras: TDataSource; qtrabajos: TZReadOnlyQuery; dsqtrabajos: TDataSource; qtipohorascodart: TWideStringField; qtipohorasdescrip: TWideStringField; qtipohorasprecio: TFloatField; qtipohorasempresa: TIntegerField; qtrabajosid: TWideStringField; qtrabajosnombre: TWideStringField; qtrabajosempresa: TIntegerField; v_precio: TDBText; checkborrar: TCheckBox; qaux: TZReadOnlyQuery; qjornales: TZQuery; qjornalesid: TIntegerField; qjornalesempresa: TIntegerField; qjornalesfecha: TDateField; qjornalesparcela: TWideStringField; qjornalesidt: TIntegerField; qjornalestrabajador: TWideStringField; qjornalestypework: TWideStringField; qjornalesarticulo: TWideStringField; qjornalesqhoras: TFloatField; qjornalesprecio: TFloatField; qjornalestotal: TFloatField; qjornalesestado: TWideStringField; Button6: TButton; lnumtrabajadores: TLabel; Button7: TButton; qticadoshoras_reales: TFloatField; qticadosmostrar: TIntegerField; gcrpagado: TDBCheckBox; qticadosmodificando: TIntegerField; gridnormal: TDBGrid; gridtotales: TDBGrid; gridampliado: TDBGrid; qempleadosid: TSmallintField; qempleadosnombre: TWideStringField; qempleadoside: TIntegerField; chktodos: TCheckBox; qempleadoscodart: TWideStringField; btactualizar: TButton; Button8: TButton; Button9: TButton; dsqasistencia: TDataSource; gridasistencia: TDBGrid; qempleadosnif: TWideStringField; SaveDialog1: TSaveDialog; qtotalestotalhorascompu: TFloatField; qticadostiempoalmuerzo: TFloatField; qempleadoshorascontrato: TFloatField; qticadossalidam_mm: TTimeField; qticadoshorasm_mm: TFloatField; qticadosentradat_mm: TTimeField; qticadossalidat_mm: TTimeField; qticadoshorast_mm: TFloatField; Button10: TButton; dbticadosdetalle: TfrxDBDataset; qticadosdetalle: TZQuery; dsqticadosdetalle: TDataSource; qticadosdetalleid: TLargeintField; qticadosdetalleide: TSmallintField; qticadosdetallefecha: TDateField; qticadosdetalleidt: TIntegerField; qticadosdetalleTRABAJADOR: TWideStringField; qticadosdetalleENTRADA_REAL: TTimeField; qticadosdetalleSALIDA_REAL: TTimeField; qticadosdetalletiempo: TFloatField; qticadosdetallecentro: TWideStringField; qjornalesorigen: TWideStringField; qjornalesobservaciones: TWideStringField; qasistir: TZQuery; qasistiride: TIntegerField; qasistiridt: TIntegerField; qasistiranyo: TIntegerField; qasistirmes: TWideStringField; qasistirnif: TWideStringField; qasistirnombre: TWideStringField; qasistird1: TWideStringField; qasistird2: TWideStringField; qasistird3: TWideStringField; qasistird4: TWideStringField; qasistird5: TWideStringField; qasistird6: TWideStringField; qasistird7: TWideStringField; qasistird8: TWideStringField; qasistird9: TWideStringField; qasistird10: TWideStringField; qasistird11: TWideStringField; qasistird12: TWideStringField; qasistird13: TWideStringField; qasistird14: TWideStringField; qasistird15: TWideStringField; qasistird16: TWideStringField; qasistird17: TWideStringField; qasistird18: TWideStringField; qasistird19: TWideStringField; qasistird20: TWideStringField; qasistird21: TWideStringField; qasistird22: TWideStringField; qasistird23: TWideStringField; qasistird24: TWideStringField; qasistird25: TWideStringField; qasistird26: TWideStringField; qasistird27: TWideStringField; qasistird28: TWideStringField; qasistird29: TWideStringField; qasistird30: TWideStringField; qasistird31: TWideStringField; qasistirfechaalta: TDateField; qasistirfechabaja: TDateField; qasistirnombre2: TWideStringField; procedure tgrupoChange(Sender: TObject); procedure buscarempleadoChange(Sender: TObject); procedure fdesdeChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure Panel5Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure gridampliadoDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure gridnormalDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure Button2Click(Sender: TObject); procedure v_horasEnter(Sender: TObject); procedure Button3Click(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btJexcelClick(Sender: TObject); procedure checkacumuladosClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure gridampliadoTitleClick(Column: TColumn); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure gridnormalTitleClick(Column: TColumn); procedure Button6Click(Sender: TObject); procedure qticadosAfterOpen(DataSet: TDataSet); procedure qticadosBeforePost(DataSet: TDataSet); procedure Button7Click(Sender: TObject); procedure gridampliadoCellClick(Column: TColumn); procedure qticadosBeforeEdit(DataSet: TDataSet); procedure qempleadosAfterOpen(DataSet: TDataSet); procedure qempleadosBeforeOpen(DataSet: TDataSet); procedure btactualizarClick(Sender: TObject); procedure gridampliadoDblClick(Sender: TObject); procedure Button8Click(Sender: TObject); procedure Button9Click(Sender: TObject); procedure qticadosAfterPost(DataSet: TDataSet); procedure Button10Click(Sender: TObject); procedure dsqgrupostrabajadores2DataChange(Sender: TObject; Field: TField); private { Private declarations } public { Public declarations } procedure ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar = nil); end; var ticados: Tticados; filtrotrabajadores,tlimitado:string; grupo:integer; desdeactualizar:integer; oldhoras:real; vidticados:integer; const rojo=$00AAAAFF; amarillo=$00B9FFFF; verde=$00C7FBAA; azul=$00FFFFBB; implementation uses datos, fdlgticados; {$R *.dfm} procedure tticados.ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar); procedure ProgressBarInit; begin ProgressBarXls.Max := DBGrid.DataSource.DataSet.RecordCount; ProgressBarXls.Position := 0; ProgressBarXls.Visible := True; end; const xlWBATworksheet = -4167; var Excel, WorkBook, WorkSheet: OleVariant; I, J: Integer; PBookmark: TBookmark; begin // Guardar la posición en la DB y desactivar que se mueva el registro PBookmark := DBGrid.DataSource.DataSet.GetBookmark; DBGrid.DataSource.DataSet.DisableControls; DBGrid.DataSource.DataSet.First; // Comprobar si existe el component TProgressBar if (ProgressBarXls <> nil) then ProgressBarInit; // Crear instancia de la aplicación Excel Excel := CreateOleObject('Excel.Application'); // Evitar que nos pregunte si deseamos sobreescribir el archivo Excel.DisplayAlerts := False; // Agregar libro de trabajo WorkBook := Excel.Workbooks.Add(xlWBATWorksheet); // Tomar una referencia a la hoja creada WorkSheet := WorkBook.WorkSheets[1]; // Se describe el nombre de la hoja WorkSheet.Name := SheetName; // Llenamos las celdas // Toma en cuenta que las columnas y filas empiezan en 1, y que en el // WorkSheet.Cells[I, J], I es la fila y J es la columna. // Extrae los nombres de los campos del DBGrid y los coloca en el primer registro, // excluyendo los campos que están ocultos for J := 0 to DBGrid.FieldCount -1 do if DBGrid.Fields[J].Visible then begin // Poner la fuente de letra en Negrita WorkSheet.Cells[1, J +1].Font.Bold := True; // Centrar la celda // WorkSheet.Cells[1, J +1].HorizontalAlignment := xlCenter; // Asignamos Valor del titulo del DBrid WorkSheet.Cells[1, J +1] := DBGrid.Columns[J].Title.Caption; end; // Guardar los registros for I := 0 to DBGrid.DataSource.DataSet.RecordCount -1 do begin // Identificamos los campos y lo grabamos según su tipo for J := 0 to DBGrid.FieldCount -1 do case DBGrid.Fields[J].DataType of ftAutoInc, ftBytes, ftInteger, ftSmallint, ftWord: // Auto o Numérico WorkSheet.Cells[I +2, J +1] := DBGrid.Fields[J].AsInteger; ftBCD, ftFloat, ftCurrency: // Numérico con decimales WorkSheet.Cells[I +2, J +1] := DBGrid.Fields[J].AsFloat; ftDateTime, ftDate, ftTime: // Fecha y Hora WorkSheet.Cells[I +2, J +1] := DBGrid.Fields[J].AsDateTime; else // Todo lo demas caracteres WorkSheet.Cells[I +2, J +1] := DBGrid.Fields[J].AsString; end; // Saltamos de registro DBGrid.DataSource.DataSet.Next; // Comprobar si existe el component TProgressBar if (ProgressBarXls <> nil) then ProgressBarXls.Position := ProgressBarXls.Position +1; end; // Comprobar si existe el component TProgressBar if (ProgressBarXls <> nil) then ProgressBarXls.Visible := False; // Redimensionar todas las celdas para que esten según su tamaño WorkSheet.Cells.Columns.AutoFit; // Guardar el archivo WorkBook.SaveAs(FileNameXLS); // Cierra el archivo WorkBook.Close(FileNameXLS); // Salir de Excel Excel.Quit; // posicionar el registro donde estaba DBGrid.DataSource.DataSet.GotoBookmark(PBookmark); DBGrid.DataSource.DataSet.FreeBookmark(PBookmark); DBGrid.DataSource.DataSet.EnableControls; end; procedure Tticados.btJexcelClick(Sender: TObject); var archivo:string; begin if gridampliado.Visible then begin archivo:='c:\agrigest\TICADOS.xlsx'; try Exportaraexcel(archivo,'TICADOS',GRIDampliado); finally showmessage('Los datos han sido exportados correctamente a C:\agrigest'); end; end; if gridnormal.Visible then begin archivo:='c:\agrigest\TICADOS.xlsx'; try Exportaraexcel(archivo,'TICADOS',GRIDnormal); finally showmessage('Los datos han sido exportados correctamente a C:\agrigest'); end; end; if gridtotales.Visible then begin archivo:='c:\agrigest\TICADOS.xlsx'; try Exportaraexcel(archivo,'TICADOS',GRIDtotales); finally showmessage('Los datos han sido exportados correctamente a C:\agrigest'); end; end; end; procedure Tticados.buscarempleadoChange(Sender: TObject); begin filtrotrabajadores:='%'+buscarempleado.Text+'%'; qempleados.Close; qempleados.open; end; procedure Tticados.Button10Click(Sender: TObject); begin qticadosdetalle.close; qticadosdetalle.Prepare; qticadosdetalle.ParamByName('FECHAINICIO').AsDate:=fdesde.Date; qticadosdetalle.ParamByName('FECHAFIN').AsDate:=fhasta.Date; qticadosdetalle.ParamByName('IDE').Asinteger:=dm.tempresaid.AsInteger; qticadosdetalle.Open; if checkbox1.Checked then begin ticadosdb.Datasource:=dsqticados; qticados.SortedFields:='fecha,trabajador'; qticados.SortType:=stascending; rTicados.Report.Clear; rTicados.LoadFromFile('c:\agrigest\informes\controlhorariogrupo.fr3'); // rTicados.Variables.Variables['tdesde']:=QUOTEDSTR('Desde: '+datetostr(fdesde.Date)); // rTicados.Variables.Variables['thasta']:=QUOTEDSTR('Hasta: '+DATETOSTR(fhasta.DATE)); rticados.Report.FileName:='Control horario '; rticados.ShowReport(); rTicados.Clear; ticadosdb.Datasource:=dsqticados; qticados.SortedFields:='trabajador,fecha'; qticados.SortType:=stascending; rTicados.Report.Clear; rTicados.LoadFromFile('c:\agrigest\informes\controlhorariodetalle.fr3'); rTicados.Variables.Variables['tdesde']:=QUOTEDSTR('Desde: '+datetostr(fdesde.Date)); rTicados.Variables.Variables['thasta']:=QUOTEDSTR('Hasta: '+DATETOSTR(fhasta.DATE)); rticados.Report.FileName:='Control horario ' + qticadostrabajador.asstring; rticados.ShowReport(); rTicados.Clear; end else begin ticadosdb.Datasource:=dsqticados; qticados.SortedFields:='trabajador,fecha'; qticados.SortType:=stascending; rTicados.Report.Clear; rTicados.LoadFromFile('c:\agrigest\informes\controlhorariodetalle.fr3'); rTicados.Variables.Variables['tdesde']:=QUOTEDSTR('Desde: '+datetostr(fdesde.Date)); rTicados.Variables.Variables['thasta']:=QUOTEDSTR('Hasta: '+DATETOSTR(fhasta.DATE)); rticados.Report.FileName:='Control horario ' + qticadostrabajador.asstring; rticados.ShowReport(); rTicados.Clear; end; end; procedure Tticados.Button1Click(Sender: TObject); begin qticados.Delete; end; procedure Tticados.Button2Click(Sender: TObject); begin if checkacumulados.Checked then begin ticadosdb.Datasource:=dsqtotales; rTicados.Report.Clear; rTicados.LoadFromFile('c:\agrigest\informes\controlhorariototales.fr3'); rTicados.Variables.Variables['tdesde']:=QUOTEDSTR('Desde: '+datetostr(fdesde.Date)); rTicados.Variables.Variables['thasta']:=QUOTEDSTR('Hasta: '+DATETOSTR(fhasta.DATE)); rticados.Report.FileName:='Control horario ' + qticadostrabajador.asstring; rticados.ShowReport(); rTicados.Clear end else begin if checkbox1.Checked then begin ticadosdb.Datasource:=dsqticados; qticados.SortedFields:='fecha,trabajador'; qticados.SortType:=stascending; rTicados.Report.Clear; rTicados.LoadFromFile('c:\agrigest\informes\controlhorariogrupo.fr3'); // rTicados.Variables.Variables['tdesde']:=QUOTEDSTR('Desde: '+datetostr(fdesde.Date)); // rTicados.Variables.Variables['thasta']:=QUOTEDSTR('Hasta: '+DATETOSTR(fhasta.DATE)); rticados.Report.FileName:='Control horario '; rticados.ShowReport(); rTicados.Clear; ticadosdb.Datasource:=dsqticados; qticados.SortedFields:='trabajador,fecha'; qticados.SortType:=stascending; rTicados.Report.Clear; rTicados.LoadFromFile('c:\agrigest\informes\controlhorario.fr3'); rTicados.Variables.Variables['tdesde']:=QUOTEDSTR('Desde: '+datetostr(fdesde.Date)); rTicados.Variables.Variables['thasta']:=QUOTEDSTR('Hasta: '+DATETOSTR(fhasta.DATE)); rticados.Report.FileName:='Control horario ' + qticadostrabajador.asstring; rticados.ShowReport(); rTicados.Clear; end else begin ticadosdb.Datasource:=dsqticados; qticados.SortedFields:='trabajador,fecha'; qticados.SortType:=stascending; rTicados.Report.Clear; rTicados.LoadFromFile('c:\agrigest\informes\controlhorario.fr3'); rTicados.Variables.Variables['tdesde']:=QUOTEDSTR('Desde: '+datetostr(fdesde.Date)); rTicados.Variables.Variables['thasta']:=QUOTEDSTR('Hasta: '+DATETOSTR(fhasta.DATE)); rticados.Report.FileName:='Control horario ' + qticadostrabajador.asstring; rticados.ShowReport(); rTicados.Clear; end; end; end; procedure Tticados.Button3Click(Sender: TObject); var ad,entsal,aleatorio,aleatorio2,positivo:integer; dia,mes,anyo:word; tfecha:string; begin qticados.First; desdeactualizar:=1; entsal:=lentsal.ItemIndex; if v_hora.Text<>' : : ' then begin case entsal of 0: begin qticados.First; while not qticados.Eof do begin if v_hora.text<>'00:00:00' then begin randomize; positivo:=random(2); if positivo=0 then positivo:=-1; randomize; aleatorio:=positivo*random(10); randomize; aleatorio2:=random(60); end; qticados.Edit; decodedate(qticadosfecha.AsDateTime,anyo,mes,dia); tfecha:=inttostr(anyo)+'/'+inttostr(mes)+'/'+inttostr(dia); qticadosentradam.Value:=strtotime(v_hora.Text); qticadosentradam.Value:=qticadosentradam.AsdateTime+aleatorio/1440+aleatorio2/86400; if edit2.Text <>'' then qticadosobservaciones.Value:=Edit2.Text; qticados.post; qticados.Next; end; end; 1: begin qticados.First; while not qticados.Eof do begin if v_hora.text<>'00:00:00' then begin randomize; positivo:=random(2); if positivo=0 then positivo:=-1; randomize; aleatorio:=positivo*random(10); randomize; aleatorio2:=random(60); end; qticados.Edit; decodedate(qticadosfecha.AsDateTime,anyo,mes,dia); tfecha:=inttostr(anyo)+'/'+inttostr(mes)+'/'+inttostr(dia); qticadossalidam.Value:=strtotime(v_hora.Text); qticadossalidam.Value:=qticadossalidam.AsdateTime+aleatorio/1440+aleatorio2/86400; if edit2.Text <>'' then qticadosobservaciones.Value:=Edit2.Text; qticados.post; qticados.Next; end; end; 2: begin qticados.First; while not qticados.Eof do begin if v_hora.Text<>'00:00:00' then begin randomize; positivo:=random(2); if positivo=0 then positivo:=-1; randomize; aleatorio:=positivo*random(10); randomize; aleatorio2:=random(60); end; qticados.Edit; decodedate(qticadosfecha.AsDateTime,anyo,mes,dia); tfecha:=inttostr(anyo)+'/'+inttostr(mes)+'/'+inttostr(dia); qticadosentradat.Value:=strtotime(v_hora.Text); qticadosentradat.Value:=qticadosentradat.AsdateTime+aleatorio/1440+aleatorio2/86400; if edit2.Text <>'' then qticadosobservaciones.Value:=Edit2.Text; qticados.post; qticados.Next; end; end; 3: begin qticados.First; while not qticados.Eof do begin if v_hora.Text<>'00:00:00' then begin randomize; positivo:=random(2); if positivo=0 then positivo:=-1; randomize; aleatorio:=positivo*random(10); randomize; aleatorio2:=random(60); end; qticados.Edit; decodedate(qticadosfecha.AsDateTime,anyo,mes,dia); tfecha:=inttostr(anyo)+'/'+inttostr(mes)+'/'+inttostr(dia); qticadossalidat.Value:=strtotime(v_hora.Text); qticadossalidat.Value:=qticadossalidat.AsdateTime+aleatorio/1440+aleatorio2/86400; if edit2.Text <>'' then qticadosobservaciones.Value:=Edit2.Text; qticados.post; qticados.Next; end; end; end; end; if (v_hora.Text=' : : ') and (edit2.text<>'') then begin qticados.First; while not qticados.Eof do begin qticados.Edit; if edit2.Text <>'' then qticadosobservaciones.Value:=Edit2.Text; qticados.post; qticados.Next; end; end; qticados.Refresh; desdeactualizar:=0; qticados.First; end; procedure Tticados.Button4Click(Sender: TObject); var punto:string; formatos:tformatsettings; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; qticados.First; if punto=',' then v_descuento.text:=stringreplace(v_descuento.Text,'.',',',[rfreplaceall]); while not qticados.Eof do begin qticados.Edit; qticadosdescuentohoras.Value:=strtofloat(v_descuento.Text); qticados.post; qticados.Next; end; qticados.refresh; qticados.First; end; procedure Tticados.Button5Click(Sender: TObject); var contador,vide,vidt:integer; dia,mes,anyo:word; tfecha:string; totaljornal:real; begin qjornales.Open; qticados.First; qaux.SQL.Clear; qaux.SQL.Add('select max(id)+1 from trabajo_diario'); qaux.Open; contador:=qaux.Fields[0].AsInteger; if qticados.RecordCount>0 then begin qticados.First; while not qticados.Eof do begin vide:=qticadoside.Asinteger; vidt:=qticadosidt.AsInteger; qempleados.Locate('ide,id',vararrayof([vide,vidt]),[locaseinsensitive]); decodedate(qticadosfecha.AsDateTime,anyo,mes,dia); tfecha:=floattostr(anyo)+'-'+floattostr(mes)+'-'+floattostr(dia); if checkborrar.Checked then begin qaux.SQL.Clear; qaux.SQL.Add('select * from trabajo_diario where idt='+qticadosidt.AsString+' and fecha='+''''+tfecha+''''+' and empresa='+qticadoside.AsString); qaux.open; if qaux.RecordCount>0 then begin qaux.SQL.Clear; qaux.SQL.Add('delete from trabajo_diario where idt='+qticadosidt.AsString+' and fecha='+''''+tfecha+''''+' and empresa='+qticadoside.AsString); qaux.execsql; end; end; qjornales.append; qjornalesid.Value:=contador; qjornalesfecha.Value:=qticadosfecha.AsDateTime; qjornalesparcela.value:=ljcentro.KeyValue; qjornalesidt.Value:=qticadosidt.asinteger; qjornalestrabajador.Value:=qticadostrabajador.asstring; qjornalestypework.Value:=ljtrabajo.KeyValue; qjornalesarticulo.Value:=ljhora.KeyValue; qjornalesqhoras.Value:=qticadoshorascobrar.AsFloat; qjornalesprecio.value:=qtipohorasprecio.AsFloat; qjornalesobservaciones.value:=qticadosobservaciones.AsString; totaljornal:=qticadoshorascobrar.asfloat*qtipohorasprecio.AsFloat; qjornalestotal.Value:=strtofloat(FormatFloat('0.00',totaljornal)); qjornalesestado.Value:='C'; qjornales.Post; contador:=contador+1; qticados.Next; end; end else begin showmessage('DEBE SELECCIONAR AL MENOS UN TRABAJADOR'); end; qticados.First; end; procedure Tticados.Button6Click(Sender: TObject); begin qticados.First; v_horas.text:=stringreplace(v_horas.Text,' ','',[rfreplaceall]); if v_horas.text<>'' then begin v_horas.text:=stringreplace(v_horas.Text,'.',',',[rfreplaceall]); while not qticados.Eof do begin qticados.Edit; qticadoshorascobrar.Value:=strtofloat(v_horas.Text); qticados.post; qticados.Next; end; end; qticados.refresh; qticados.First; end; procedure Tticados.Button7Click(Sender: TObject); begin dlgticados := Tdlgticados.Create(nil); try dlgticados.qticados.ParamByName('IDE').AsInteger:=qticadoside.AsInteger; dlgticados.qticados.ParamByName('IDT').AsInteger:=qticadosidt.AsInteger; dlgticados.qticados.ParamByName('FECHA').Asdatetime:=qticadosfecha.Asdatetime; dlgticados.qticados.prepare; dlgticados.qticados.Open; dlgticados.showmodal(); finally dlgticados.Free; qticados.Refresh; end; end; procedure Tticados.Button8Click(Sender: TObject); var minutosajuste,ajusteentrada,ajustesalida:integer; horaentrada,horasalida:ttime; hora,minutos,horaaj,minutosaj,anyo,mes,dia:word; dhora,dminutos,dsegundos,dmilisegundos:word; horasfact:real; tid,descuento:integer; vmes,vdia,vanyo,vfecha,sdescuento:string; begin qticados.First; if dm.tempresaajuste15.AsInteger=1 then minutosajuste:=15; if dm.tempresaajuste30.AsInteger=1 then minutosajuste:=30; ajusteentrada:=dm.tempresaajusteentrada.AsInteger; ajustesalida:=dm.tempresaajustesalida.AsInteger; while not qticados.Eof do begin horasfact:=0; if qticadosentradam.Asstring<>'' then begin //1 horaentrada:=qticadosentradam.AsDateTime; if qticadossalidam.Asstring<>'' then begin //2 horasalida:=qticadossalidam.AsDateTime; if minutosajuste=30 then begin //4 decodetime(horaentrada,dhora,dminutos,dsegundos,dmilisegundos); horaaj:=dhora; if dminutos<=ajusteentrada then minutosaj:=0; if (dminutos>ajusteentrada) and (dminutos<=ajusteentrada+30) then minutosaj:=30; if dminutos>30+ajusteentrada then begin minutosaj:=0; horaaj:=horaaj+1; end; horaentrada:=encodetime(horaaj,minutosaj,0,0); decodetime(horasalida,dhora,dminutos,dsegundos,dmilisegundos); horaaj:=dhora; if dminutos<=ajustesalida then minutosaj:=0; if (dminutos>ajustesalida) and (dminutos<=ajustesalida+30) then minutosaj:=30; if dminutos>30+ajustesalida then begin minutosaj:=0; horaaj:=horaaj+1; end; horasalida:=encodetime(horaaj,minutosaj,0,0); horasfact:=(horasalida-horaentrada)*24; end; //4 if minutosajuste=15 then begin //4 decodetime(horaentrada,dhora,dminutos,dsegundos,dmilisegundos); horaaj:=dhora; if dminutos<=ajusteentrada then minutosaj:=0; if (dminutos>ajusteentrada) and (dminutos<=ajusteentrada+15) then minutosaj:=15; if (dminutos>15+ajusteentrada) and (dminutos<=ajusteentrada+30) then minutosaj:=30; if (dminutos>30+ajusteentrada) and (dminutos<=ajusteentrada+45) then minutosaj:=45; if dminutos>45+ajusteentrada then begin minutosaj:=0; horaaj:=horaaj+1; end; horaentrada:=encodetime(horaaj,minutosaj,0,0); decodetime(horasalida,dhora,dminutos,dsegundos,dmilisegundos); horaaj:=dhora; if dminutos<=ajusteentrada then minutosaj:=0; if (dminutos>ajusteentrada) and (dminutos<=ajusteentrada+15) then minutosaj:=15; if (dminutos>15+ajusteentrada) and (dminutos<=ajusteentrada+30) then minutosaj:=30; if (dminutos>30+ajusteentrada) and (dminutos<=ajusteentrada+45) then minutosaj:=45; if dminutos>45+ajusteentrada then begin minutosaj:=0; horaaj:=horaaj+1; end; horasalida:=encodetime(horaaj,minutosaj,0,0); horasfact:=(horasalida-horaentrada)*24; end; end; //2 end;//1 if qticadosentradat.Asstring<>'' then begin //1 horaentrada:=qticadosentradat.AsDateTime; if qticadossalidat.Asstring<>'' then begin //2 horasalida:=qticadossalidat.AsDateTime; if minutosajuste=30 then begin //4 decodetime(horaentrada,dhora,dminutos,dsegundos,dmilisegundos); horaaj:=dhora; if dminutos<=ajusteentrada then minutosaj:=0; if (dminutos>ajusteentrada) and (dminutos<=ajusteentrada+30) then minutosaj:=30; if dminutos>30+ajusteentrada then begin minutosaj:=0; horaaj:=horaaj+1; end; horaentrada:=encodetime(horaaj,minutosaj,0,0); decodetime(horasalida,dhora,dminutos,dsegundos,dmilisegundos); horaaj:=dhora; if dminutos<=ajustesalida then minutosaj:=0; if (dminutos>ajustesalida) and (dminutos<=ajustesalida+30) then minutosaj:=30; if dminutos>30+ajustesalida then begin minutosaj:=0; horaaj:=horaaj+1; end; horasalida:=encodetime(horaaj,minutosaj,0,0); horasfact:=horasfact+((horasalida-horaentrada)*24); end; //4 if minutosajuste=15 then begin //4 decodetime(horaentrada,dhora,dminutos,dsegundos,dmilisegundos); horaaj:=dhora; if dminutos<=ajusteentrada then minutosaj:=0; if (dminutos>ajusteentrada) and (dminutos<=ajusteentrada+15) then minutosaj:=15; if (dminutos>15+ajusteentrada) and (dminutos<=ajusteentrada+30) then minutosaj:=30; if (dminutos>30+ajusteentrada) and (dminutos<=ajusteentrada+45) then minutosaj:=45; if dminutos>45+ajusteentrada then begin minutosaj:=0; horaaj:=horaaj+1; end; horaentrada:=encodetime(horaaj,minutosaj,0,0); decodetime(horasalida,dhora,dminutos,dsegundos,dmilisegundos); horaaj:=dhora; if dminutos<=ajusteentrada then minutosaj:=0; if (dminutos>ajusteentrada) and (dminutos<=ajusteentrada+15) then minutosaj:=15; if (dminutos>15+ajusteentrada) and (dminutos<=ajusteentrada+30) then minutosaj:=30; if (dminutos>30+ajusteentrada) and (dminutos<=ajusteentrada+45) then minutosaj:=45; if dminutos>45+ajusteentrada then begin minutosaj:=0; horaaj:=horaaj+1; end; horasalida:=encodetime(horaaj,minutosaj,0,0); horasfact:=horasfact+((horasalida-horaentrada)*24); end; //4 end; //2 end; //1 qticados.Edit; qticadoshorascobrar.asfloat:=0; qticadosmodificando.asinteger:=1; qticados.Post; qticados.Edit; qticadoshorascobrar.asfloat:=horasfact-qticadosdescuentohoras.AsFloat; qticadosmodificando.asinteger:=0; qticados.Post; qticados.Next; end; end; procedure Tticados.Button9Click(Sender: TObject); var archivo,vmes,vnombre,vnif,vhoras:string; tdia,tmes,tanyo:word; vdia,vanyo,vide,vidt:integer; begin qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('delete from emp_asistencia'); qaux.execsql; qticados.First; while not qticados.Eof do begin decodedate(qticadosfecha.AsDateTime,tanyo,tmes,tdia); vdia:=tdia; vanyo:=tanyo; vhoras:=floattostr(qticadosnum_horas_m.AsFloat); case tmes of 1:vmes:='ENERO'; 2:vmes:='FEBRERO'; 3:vmes:='MARZO'; 4:vmes:='ABRIL'; 5:vmes:='MAYO'; 6:vmes:='JUNIO'; 7:vmes:='JULIO'; 8:vmes:='AGOSTO'; 9:vmes:='SEPTIEMBRE'; 10:vmes:='OCTUBRE'; 11:vmes:='NOVIEMBRE'; 12:vmes:='DICIEMBRE'; end; vide:=qticadoside.AsInteger; vidt:=qticadosidt.AsInteger; qempleados.Locate('ide,id',vararrayof([vide,vidt]),[locaseinsensitive]); vnif:=qempleadosnif.asstring; vnombre:=qempleadosnombre.AsString; qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('select * from emp_asistencia where ide=:EMPRESA and idt=:TRABAJADOR and anyo=:ANYO and mes=:MES'); qaux.Prepare; qaux.ParamByName('EMPRESA').AsInteger:=vide; qaux.ParamByName('TRABAJADOR').AsInteger:=vidt; qaux.ParamByName('ANYO').AsInteger:=vanyo; qaux.ParamByName('MES').Asstring:=vmes; qaux.Open; if qaux.RecordCount=0 then begin qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('insert into emp_asistencia (ide,idt,nif,nombre,anyo,mes) values (:EMPRESA,:TRABAJADOR,:NIF,:NOMBRE,:ANYO,:MES)'); qaux.Prepare; qaux.ParamByName('EMPRESA').AsInteger:=vide; qaux.ParamByName('TRABAJADOR').AsInteger:=vidt; qaux.ParamByName('NIF').Asstring:=vnif; qaux.ParamByName('NOMBRE').Asstring:=vnombre; qaux.ParamByName('ANYO').AsInteger:=vanyo; qaux.ParamByName('MES').Asstring:=vmes; qaux.execsql; qasistir.close; qasistir.Open; qasistir.Locate('ide,idt,anyo,mes',vararrayof([vide,vidt,vanyo,vmes]),[locaseinsensitive]); end; qasistir.Edit; case vdia of 1:qasistird1.value:='X'; 2:qasistird2.value:='X'; 3:qasistird3.value:='X'; 4:qasistird4.value:='X'; 5:qasistird5.value:='X'; 6:qasistird6.value:='X'; 7:qasistird7.value:='X'; 8:qasistird8.value:='X'; 9:qasistird9.value:='X'; 10:qasistird10.value:='X'; 11:qasistird11.value:='X'; 12:qasistird12.value:='X'; 13:qasistird13.value:='X'; 14:qasistird14.value:='X'; 15:qasistird15.value:='X'; 16:qasistird16.value:='X'; 17:qasistird17.value:='X'; 18:qasistird18.value:='X'; 19:qasistird19.value:='X'; 20:qasistird20.value:='X'; 21:qasistird21.value:='X'; 22:qasistird22.value:='X'; 23:qasistird23.value:='X'; 24:qasistird24.value:='X'; 25:qasistird25.value:='X'; 26:qasistird26.value:='X'; 27:qasistird27.value:='X'; 28:qasistird28.value:='X'; 29:qasistird29.value:='X'; 30:qasistird30.value:='X'; 31:qasistird31.value:='X'; end; qasistir.Post; qticados.Next; end; decodedate(fdesde.date,tanyo,tmes,tdia); case tmes of 1:vmes:='ENERO'; 2:vmes:='FEBRERO'; 3:vmes:='MARZO'; 4:vmes:='ABRIL'; 5:vmes:='MAYO'; 6:vmes:='JUNIO'; 7:vmes:='JULIO'; 8:vmes:='AGOSTO'; 9:vmes:='SEPTIEMBRE'; 10:vmes:='OCTUBRE'; 11:vmes:='NOVIEMBRE'; 12:vmes:='DICIEMBRE'; end; qasistir.Close; qasistir.SQL.Clear; qasistir.SQL.Add('select * from v_emp_asistencia where ide=:EMPRESA and anyo=:ANYO and mes=:MES order by anyo,nombre2'); qasistir.Prepare; qasistir.ParamByName('EMPRESA').AsInteger:=vide; qasistir.ParamByName('MES').Asstring:=vmes; qasistir.ParamByName('ANYO').Asinteger:=vanyo; qasistir.Open; savedialog1.FileName:='PARTE COMUNICACION.xlsx'; savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'PARTE',GRIDASISTENCIA); finally showmessage('Los datos han sido exportados correctamente a '+archivo); end; { qasistencia.Close; qasistencia.SQL.Clear; qasistencia.SQL.Add('select * from v_emp_asistencia order by ide,idt,anyo,mes'); qasistencia.Open;} end; procedure Tticados.btactualizarClick(Sender: TObject); var i,p_empresa:integer; p_activo,p_grupo,p_empleados,p_mostrar:string; begin if dm.tempresa.Active then p_empresa:=dm.tempresaid.AsInteger else begin dm.tempresa.Open; p_empresa:=dm.tempresaid.AsInteger; end; if grupo=0 then p_grupo:='%' else p_grupo:=inttostr(grupo); p_empleados:='%'+buscarempleado.Text+'%'; if chktodos.Checked then p_activo:='%' else p_activo:='1'; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=0 where seleccionado=1'); qaux.Execsql; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=1 where ide=:EMPRESA and id=:ID and mostrar like(:ACTIVO)' ); qaux.Prepare; if dbgrid1.SelectedRows.Count>0 then for i := 0 to dbgrid1.Selectedrows.Count - 1 do begin qempleados.GotoBookmark ((dbgrid1.selectedrows[i])); qaux.ParamByName('ID').AsInteger:=qempleadosid.asinteger; qaux.ParamByName('EMPRESA').AsInteger:=qempleadoside.asinteger; qaux.ParamByName('ACTIVO').AsString:=p_activo; qaux.Execsql; end else begin qaux.close; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=1 where ide=:EMPRESA and activo like(:GRUPO) and nombre like(:EMPLEADO) and mostrar like (:ACTIVO)'); qaux.Prepare; qaux.parambyname('EMPRESA').AsInteger:=p_empresa; qaux.parambyname('GRUPO').Asstring:=p_grupo; qaux.parambyname('EMPLEADO').Asstring:=p_empleados; qaux.parambyname('ACTIVO').Asstring:=p_activo; qaux.Execsql; end; if gridampliado.Visible then p_mostrar:='%' else p_mostrar:='1'; if checkbox1.Checked then begin qticados.Close; // qticados.SQL.Clear; // qticados.SQL.Add('select * from ticadoscompleto where mostrar like(:MOSTRAR) and fecha>=:FECHAINICIO and fecha<=:FECHAFIN and idt in (select id from trabajadores where seleccionado=1) order by trabajador,fecha desc,entradam,entradat'); qticados.Prepare; qticados.ParamByName('FECHAINICIO').AsDate:=fdesde.Date; qticados.ParamByName('FECHAFIN').AsDate:=fhasta.Date; qticados.ParamByName('MOSTRAR').Asstring:=p_mostrar; qticados.MasterSource:=nil; qticados.Open; qtotalhoras.Close; qtotalhoras.MasterSource:=nil; qtotalhoras.SQL.Clear; qtotalhoras.SQL.Add('select idt,sum(num_horas_m) as totalhoras from ticadoscompleto where mostrar=1 and fecha>=:FECHAINICIO and fecha<=:FECHAFIN and idt in (select id from trabajadores where seleccionado=1) '); qtotalhoras.Prepare; qtotalhoras.ParamByName('FECHAINICIO').AsDate:=fdesde.Date; qtotalhoras.ParamByName('FECHAFIN').AsDate:=fhasta.Date; qtotalhoras.Open; end else begin qticados.Close; // qticados.SQL.Clear; // qticados.SQL.Add('select * from ticadoscompleto where mostrar like(:MOSTRAR) and fecha>=:FECHAINICIO and fecha<=:FECHAFIN and idt in (select id from trabajadores where seleccionado=1) order by trabajador,fecha desc,entradam,entradat'); qticados.Prepare; qticados.ParamByName('FECHAINICIO').AsDate:=fdesde.Date; qticados.ParamByName('FECHAFIN').AsDate:=fhasta.Date; qticados.ParamByName('MOSTRAR').Asstring:=p_mostrar; qticados.MasterSource:=dsqempleados; qticados.Open; qtotalhoras.Close; qtotalhoras.MasterSource:=dsqempleados; qtotalhoras.SQL.Clear; qtotalhoras.SQL.Add('select idt,sum(num_horas_m) as totalhoras from ticadoscompleto where mostrar=1 and fecha>=:FECHAINICIO and fecha<=:FECHAFIN and idt in (select id from trabajadores where seleccionado=1) group by idt order by idt'); qtotalhoras.Prepare; qtotalhoras.ParamByName('FECHAINICIO').AsDate:=fdesde.Date; qtotalhoras.ParamByName('FECHAFIN').AsDate:=fhasta.Date; qtotalhoras.Open; end; end; procedure Tticados.CheckBox1Click(Sender: TObject); var p_mostrar:string; begin btactualizar.Click; end; procedure Tticados.dsqgrupostrabajadores2DataChange(Sender: TObject; Field: TField); begin grupo:=qgrupostrabajadores2id.asinteger; qempleados.Close; qempleados.Open; end; procedure Tticados.checkacumuladosClick(Sender: TObject); begin if checkacumulados.Checked then begin if checkbox1.Checked then begin qticados.Close; qtotalhoras.Close; qticados.MasterSource:=nil; qticados.Open; qtotalhoras.MasterSource:=nil; qtotalhoras.Open; qtotales.MasterSource:=nil; qtotales.Open; end else begin qticados.Close; qtotalhoras.Close; qticados.MasterSource:=dsqempleados; qticados.Open; qtotalhoras.MasterSource:=dsqempleados; qtotalhoras.Open; qtotales.MasterSource:=dsqempleados; qtotales.Open; end; gridtotales.Visible:=true; gridnormal.Visible:=false; gridampliado.Visible:=false; gridtotales.Columns[2].Title.caption:='Horas desde el '+datetostr(fdesde.Date)+' hasta el '+datetostr(fhasta.Date); end else begin if checkbox1.Checked then begin qticados.Close; qtotalhoras.Close; qticados.MasterSource:=nil; qticados.Open; qtotalhoras.MasterSource:=nil; qtotalhoras.Open; qtotales.MasterSource:=nil; qtotales.Open; end else begin qticados.Close; qtotalhoras.Close; qticados.MasterSource:=dsqempleados; qticados.Open; qtotalhoras.MasterSource:=dsqempleados; qtotalhoras.Open; qtotales.MasterSource:=dsqempleados; qtotales.Open; end; gridtotales.Visible:=false; gridnormal.Visible:=true; gridampliado.Visible:=false; end; end; procedure Tticados.gridnormalDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if qticadosfestivo.Asinteger=1 then begin gridnormal.Canvas.brush.Color := rojo; end; gridnormal.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure Tticados.gridnormalTitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=qticados.SortType; qticados.SortedFields:=Column.FieldName; If st = stAscending then qticados.SortType:=stDescending else qticados.SortType:=stAscending; dsqticados.DataSet.First; end; procedure Tticados.v_horasEnter(Sender: TObject); begin v_horas.Text:=''; end; procedure Tticados.fdesdeChange(Sender: TObject); begin btactualizar.Click; end; procedure Tticados.FormClose(Sender: TObject; var Action: TCloseAction); begin qaux.close; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=0 where seleccionado=1'); qaux.Execsql; qticados.Close; qtotalhoras.Close; qempleados.Close; end; procedure Tticados.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is tdbgrid) then begin key:=','; end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tticados.FormShow(Sender: TObject); begin DM.tempresa.Open; fdesde.Date:=date()-1; fhasta.Date:=date()-1; gridampliado.Visible:=false; panel6.Visible:=false; pmodificaciones.Visible:=false; gridnormal.Visible:=true; desdeactualizar:=0; qgrupostrabajadores2.Prepare; qgrupostrabajadores2.ParamByName('IDEMPRESA').AsInteger:=dm.tempresaid.AsInteger; qgrupostrabajadores2.open; tgrupo.KeyValue:=qgrupostrabajadores2id.AsString; qparcelas.Open; qtipohoras.Open; qtrabajos.Open; end; procedure Tticados.gridampliadoCellClick(Column: TColumn); begin if column.Field.FieldName ='mostrar' then begin if qticadosmostrar.asinteger=1 then begin qticados.Edit; qticadosmostrar.value:=0; qticados.Post; // qticados.Refresh; gridampliado.selectedIndex:=18; end else begin qticados.edit; qticadosmostrar.Value:=1; qticados.Post; // qticados.Refresh; gridampliado.SelectedIndex:=18; end; end; qtotalhoras.close; qtotalhoras.Open; end; procedure Tticados.gridampliadoDblClick(Sender: TObject); var vidticados:integer; begin vidticados:=qticadosid.AsInteger; dlgticados := Tdlgticados.Create(nil); try dlgticados.qticados.ParamByName('IDE').AsInteger:=qticadoside.AsInteger; dlgticados.qticados.ParamByName('IDT').AsInteger:=qticadosidt.AsInteger; dlgticados.qticados.ParamByName('FECHA').Asdatetime:=qticadosfecha.Asdatetime; dlgticados.qticados.prepare; dlgticados.qticados.Open; dlgticados.idticado:=vidticados; dlgticados.showmodal(); finally dlgticados.Free; qticados.Refresh; qticados.Locate('id',vidticados,[locaseinsensitive]); end; end; procedure Tticados.gridampliadoDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); const IsChecked : array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED); var DrawState: Integer; DrawRect: TRect; begin if (gdFocused in State) then begin if qticadosfestivo.Asinteger=1 then begin Gridampliado.Canvas.brush.Color := rojo; end; gridampliado.DefaultDrawColumnCell(Rect, DataCol, Column, State); if (Column.Field.FieldName = 'mostrar') then begin gcrpagado.Left := Rect.Left + gridampliado.Left + 2; gcrpagado.Top := Rect.Top + gridampliado.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if qticadosfestivo.Asinteger=1 then begin Gridampliado.Canvas.brush.Color := rojo; end; gridampliado.DefaultDrawColumnCell(Rect, DataCol, Column, State); if (Column.Field.FieldName = 'mostrar') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; //DrawState := ISChecked[Column.Field.Asboolean]; gridampliado.Canvas.FillRect(Rect); DrawFrameControl(gridampliado.Canvas.Handle, DrawRect, DFC_BUTTON, DrawState); end; end; end; procedure Tticados.gridampliadoTitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=qticados.SortType; qticados.SortedFields:=Column.FieldName; If st = stAscending then qticados.SortType:=stDescending else qticados.SortType:=stAscending; dsqticados.DataSet.First; end; procedure Tticados.Panel5Click(Sender: TObject); var idt:integer; begin idt:=qempleadosid.AsInteger; if gridnormal.visible then begin gridampliado.Visible:=true; panel6.Visible:=true; gridnormal.Visible:=false; pmodificaciones.visible:=true; button10.Visible:=true; end else begin gridampliado.Visible:=false; panel6.Visible:=false; gridnormal.Visible:=true; pmodificaciones.visible:=false; button10.Visible:=false; end; btactualizar.Click; qempleados.Locate('id',idt,[locaseinsensitive]); end; procedure Tticados.qempleadosAfterOpen(DataSet: TDataSet); var i:integer; p_empresa:integer; p_empleados,p_grupo,p_activo,p_mostrar:string; begin if dm.tempresa.Active then p_empresa:=dm.tempresaid.AsInteger else begin dm.tempresa.Open; p_empresa:=dm.tempresaid.AsInteger; end; if grupo=0 then p_grupo:='%' else p_grupo:=inttostr(grupo); p_empleados:='%'+buscarempleado.Text+'%'; if chktodos.Checked then p_activo:='%' else p_activo:='1'; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('select * from trabajadores where seleccionado=1'); qaux.open; if qaux.RecordCount>1 then begin qaux.close; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=0 where seleccionado=1'); qaux.Execsql; end; qaux.close; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=1 where ide=:EMPRESA and id=:ID and mostrar like(:ACTIVO)' ); qaux.Prepare; if dbgrid1.SelectedRows.Count>0 then for i := 0 to dbgrid1.Selectedrows.Count - 1 do begin qempleados.GotoBookmark ((dbgrid1.selectedrows[i])); qaux.ParamByName('ID').AsInteger:=qempleadosid.asinteger; qaux.ParamByName('EMPRESA').AsInteger:=qempleadoside.asinteger; qaux.ParamByName('ACTIVO').AsString:=p_activo; qaux.Execsql; end else begin qaux.close; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=1 where ide=:EMPRESA and activo like(:GRUPO) and nombre like(:EMPLEADO) and mostrar like (:ACTIVO)'); qaux.Prepare; qaux.parambyname('EMPRESA').AsInteger:=p_empresa; qaux.parambyname('GRUPO').Asstring:=p_grupo; qaux.parambyname('EMPLEADO').Asstring:=p_empleados; qaux.parambyname('ACTIVO').Asstring:=p_activo; qaux.Execsql; end; if gridampliado.Visible then p_mostrar:='%' else p_mostrar:='1'; if checkbox1.Checked then begin qticados.Close; // qticados.SQL.Clear; // qticados.SQL.Add('select * from ticadoscompleto where mostrar like(:MOSTRAR) and fecha>=:FECHAINICIO and fecha<=:FECHAFIN and idt in (select id from trabajadores where seleccionado=1) order by trabajador,fecha desc,entradam,entradat'); qticados.Prepare; qticados.ParamByName('FECHAINICIO').AsDate:=fdesde.Date; qticados.ParamByName('FECHAFIN').AsDate:=fhasta.Date; qticados.ParamByName('MOSTRAR').Asstring:=p_mostrar; qticados.MasterSource:=nil; qticados.Open; qtotalhoras.Close; qtotalhoras.MasterSource:=nil; qtotalhoras.SQL.Clear; qtotalhoras.SQL.Add('select idt,sum(num_horas_m) as totalhoras from ticadoscompleto where mostrar like(:MOSTRAR) and fecha>=:FECHAINICIO and fecha<=:FECHAFIN and idt in (select id from trabajadores where seleccionado=1) '); qtotalhoras.Prepare; qtotalhoras.ParamByName('FECHAINICIO').AsDateTime:=fdesde.DateTime; qtotalhoras.ParamByName('FECHAFIN').AsDateTime:=fhasta.DateTime; qtotalhoras.ParamByName('MOSTRAR').Asstring:=p_mostrar; qtotalhoras.Open; qtotales.Close; qtotales.SQL.Clear; qtotales.SQL.Add('select idt,trabajador,sum(num_horas_m) as totalhoras,sum(horascobrar) as totalhorascompu'); qtotales.SQL.Add(' from ticadoscompleto where mostrar like(:MOSTRAR) and fecha>=:FECHAINICIO and fecha<=:FECHAFIN and idt in (select id from trabajadores where seleccionado=1) group by idt order by trabajador'); qtotales.Prepare; qtotales.ParamByName('FECHAINICIO').AsDate:=fdesde.Date; qtotales.ParamByName('FECHAFIN').AsDate:=fhasta.Date; qtotales.ParamByName('MOSTRAR').Asstring:=p_mostrar; qtotales.Open; end else begin qticados.Close; // qticados.SQL.Clear; // qticados.SQL.Add('select * from ticadoscompleto where mostrar like(:MOSTRAR) and fecha>=:FECHAINICIO and fecha<=:FECHAFIN and idt in (select id from trabajadores where seleccionado=1) order by trabajador,fecha desc,entradam,entradat'); qticados.Prepare; qticados.ParamByName('FECHAINICIO').AsDate:=fdesde.Date; qticados.ParamByName('FECHAFIN').AsDate:=fhasta.Date; qticados.ParamByName('MOSTRAR').Asstring:=p_mostrar; qticados.MasterSource:=dsqempleados; qticados.Open; qtotalhoras.Close; qtotalhoras.MasterSource:=dsqempleados; qtotalhoras.SQL.Clear; qtotalhoras.SQL.Add('select idt,sum(num_horas_m) as totalhoras from ticadoscompleto where mostrar like(:MOSTRAR) and fecha>=:FECHAINICIO and fecha<=:FECHAFIN and idt in (select id from trabajadores where seleccionado=1) group by idt'); qtotalhoras.Prepare; qtotalhoras.ParamByName('FECHAINICIO').AsDate:=fdesde.Date; qtotalhoras.ParamByName('FECHAFIN').AsDate:=fhasta.Date; qtotalhoras.ParamByName('MOSTRAR').Asstring:=p_mostrar; qtotalhoras.Open; qtotales.Close; qtotales.SQL.Clear; qtotales.SQL.Add('select idt,trabajador,sum(num_horas_m) as totalhoras,sum(horascobrar) as totalhorascompu '); qtotales.SQL.Add(' from ticadoscompleto where mostrar like(:MOSTRAR) and fecha>=:FECHAINICIO and fecha<=:FECHAFIN and idt in (select id from trabajadores where seleccionado=1) group by trabajador'); qtotales.Prepare; qtotales.ParamByName('FECHAINICIO').AsDate:=fdesde.Date; qtotales.ParamByName('FECHAFIN').AsDate:=fhasta.Date; qtotales.ParamByName('MOSTRAR').Asstring:=p_mostrar; qtotales.Open; end; end; procedure Tticados.qempleadosBeforeOpen(DataSet: TDataSet); var p_empresa:integer; p_empleados,p_grupo,p_activo:string; begin if dm.tempresa.Active then p_empresa:=dm.tempresaid.AsInteger else begin dm.tempresa.Open; p_empresa:=dm.tempresaid.AsInteger; end; if grupo=0 then p_grupo:='%' else p_grupo:=inttostr(grupo); p_empleados:='%'+buscarempleado.Text+'%'; if chktodos.Checked then p_activo:='%' else p_activo:='1'; qempleados.Prepare; qempleados.parambyname('EMPRESA').AsInteger:=p_empresa; qempleados.parambyname('GRUPO').Asstring:=p_grupo; qempleados.parambyname('EMPLEADO').Asstring:=p_empleados; qempleados.parambyname('ACTIVO').Asstring:=p_activo; end; procedure Tticados.qticadosAfterOpen(DataSet: TDataSet); begin qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('select count(distinct(idt)) from ('+qticados.SQL.Text+') as qticados'); qaux.open; lnumtrabajadores.Caption:='Trabajadores seleccionados: '+(qaux.fields[0].asstring); end; procedure Tticados.qticadosAfterPost(DataSet: TDataSet); begin qticados.Refresh; qticados.Locate('id',vidticados,[locaseinsensitive]); end; procedure Tticados.qticadosBeforeEdit(DataSet: TDataSet); begin oldhoras:=qticadoshorascobrar.AsFloat; end; procedure Tticados.qticadosBeforePost(DataSet: TDataSet); var hora:string; begin { if qticadossalidat.AsString<>'' then begin hora:=qticadossalidat.asstring; qticadoshorafinmostrar.Value:=strtotime(hora); end; if (qticadossalidam.AsString<>'') and (qticadossalidat.AsString='') then begin hora:=qticadossalidam.asstring; qticadoshorafinmostrar.Value:=strtotime(hora); end; } if (qticadoshorascobrar.AsFloat<>oldhoras) and (qticadosmodificando.asinteger=0) then begin qticadosmodificando.value:=1; end; vidticados:=qticadosid.AsInteger; end; procedure Tticados.tgrupoChange(Sender: TObject); begin grupo:=qgrupostrabajadores2id.asinteger; qempleados.Close; qempleados.Open; end; end. ======================================== FICHERO: ftratamientos.pas ======================================== unit ftratamientos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.DBCtrls, Vcl.ComCtrls, frxClass, frxDBSet, URLMon, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP,shellapi, Vcl.Mask; type Ttratamientos = class(TForm) Panel2: TPanel; Panel3: TPanel; DBGrid1: TDBGrid; Panel5: TPanel; Panel4: TPanel; DBGrid2: TDBGrid; qtratamientosbase: TZQuery; qtratamientosbasedetalle: TZQuery; qtratamientosbasedetalleide: TIntegerField; qtratamientosbasedetalleidt: TIntegerField; qtratamientosbasedetalleidaf: TIntegerField; qtratamientosbasedetalleidma: TIntegerField; qtratamientosbasedetalledescripcion_af: TWideStringField; qtratamientosbasedetallecantidad_base: TFloatField; qtratamientosbasedetalledosis: TFloatField; qtratamientosbasedetalleunidad_medida: TWideStringField; qtratamientosbasedetalledescripcion_ma: TWideStringField; qtratamientosbasedetalleregistro: TWideStringField; qtratamientosbasedetalleplazo: TIntegerField; Panel6: TPanel; Panel7: TPanel; Label36: TLabel; btAreutilizar: TButton; btAmodificar: TButton; btAborrar: TButton; btAnuevo: TButton; btAguardar: TButton; btAcancelar: TButton; dsqtratamientosbasedetalle: TDataSource; dsqtratamientosbase: TDataSource; qtratamientos: TZQuery; qtratamientosdetalle: TZQuery; dsqtratamientos: TDataSource; dsqtratamientosdetalle: TDataSource; qcentrocoste: TZReadOnlyQuery; qcentrocosteempresa: TIntegerField; qcentrocostecodpar: TWideStringField; qcentrocostenombre: TWideStringField; dsqcentrocoste: TDataSource; Panel9: TPanel; DBGrid3: TDBGrid; Panel10: TPanel; Panel11: TPanel; Panel12: TPanel; DBGrid4: TDBGrid; qtratamientosdetalleide: TIntegerField; qtratamientosdetalleidt: TIntegerField; qtratamientosdetalleidaf: TIntegerField; qtratamientosdetalleidma: TIntegerField; qtratamientosdetalledescripcion_af: TWideStringField; qtratamientosdetalledescripcion_ma: TWideStringField; qtratamientosdetallecantidad_base: TFloatField; qtratamientosdetalledosis: TFloatField; qtratamientosdetalleunidad_medida: TWideStringField; qtratamientosdetalleregistro: TWideStringField; qtratamientosdetalleplazo: TIntegerField; qtratamientosdetalleficha: TBlobField; qtratamientosdetallecantidad_materia: TFloatField; Panel13: TPanel; Panel1: TPanel; Button2: TButton; Button3: TButton; qresponsables: TZReadOnlyQuery; dsqresponsables: TDataSource; qresponsablesnif: TWideStringField; qresponsablesnombre: TWideStringField; qresponsablesfirma: TBlobField; qaux: TZQuery; Ffecha: TDateTimePicker; combocentrocoste: TDBLookupComboBox; comboresponsables: TDBLookupComboBox; Panel8: TPanel; Button1: TButton; Panel15: TPanel; Label2: TLabel; DBMemo2: TDBMemo; Button4: TButton; Button5: TButton; dbempresa: TfrxDBDataset; informes: TfrxReport; dbtratamiento: TfrxDBDataset; dbtratamientosdetalle: TfrxDBDataset; qtratamientosdetalleen_cuaderno: TIntegerField; gcrpagado: TDBCheckBox; Button7: TButton; dsqcentrocoste2: TDataSource; qcentrocoste2: TZReadOnlyQuery; dsqresponsable2: TDataSource; qresponsables2: TZReadOnlyQuery; Label4: TLabel; Label5: TLabel; combobuscarresponsables: TDBLookupComboBox; combobuscarparcelas: TDBLookupComboBox; btfiltrar: TButton; Button9: TButton; Button6: TButton; Label3: TLabel; qcentrocoste2empresa: TIntegerField; qcentrocoste2codpar: TWideStringField; qcentrocoste2nombre: TWideStringField; qresponsables2nif: TWideStringField; qresponsables2nombre: TWideStringField; qresponsables2firma: TBlobField; qtratamientosdetalleconficha: TStringField; qtratamientosbasedetalleficha: TBlobField; qtratamientosbasedetallecantidad_materia: TFloatField; qtratamientosdetallecantidad_mezcla: TFloatField; dsqconsumos: TDataSource; qconsumos: TZQuery; qconsumosid: TIntegerField; qconsumoside: TIntegerField; qconsumosidcc: TWideStringField; qconsumosidgrupo: TIntegerField; qconsumosidfamilia: TIntegerField; qconsumosidaf: TIntegerField; qconsumoscodigo: TWideStringField; qconsumosdescripcion: TWideStringField; qconsumosregistro: TWideStringField; qconsumosprecio: TFloatField; qconsumoscantidad: TFloatField; qconsumostotal: TFloatField; qconsumostotal_amortizado: TFloatField; qconsumosnumplazos: TIntegerField; qconsumoslote: TWideStringField; qconsumosidentrada: TIntegerField; qconsumosfecha: TDateField; qconsumosidfraccionado: TIntegerField; qconsumosamortizacion: TIntegerField; qarticulo: TZQuery; qarticuloidempresa: TIntegerField; qarticuloidaf: TIntegerField; qarticulodescripcion: TWideStringField; qarticulopreciocoste: TFloatField; qarticuloidgrupo: TIntegerField; qarticuloidfamilia: TIntegerField; qarticulocodigo: TWideStringField; qarticuloregistro: TWideStringField; qtratamientosdetalleidconsumo: TIntegerField; qaux2: TZReadOnlyQuery; qstock: TZReadOnlyQuery; qstockid: TIntegerField; qstockidempresa: TIntegerField; qstocklote: TWideStringField; qstockfecha: TDateField; qtractores: TZReadOnlyQuery; qtractorestractor: TWideStringField; qvelocidad: TZReadOnlyQuery; qventilador: TZReadOnlyQuery; qpresiones: TZReadOnlyQuery; qdepositos: TZReadOnlyQuery; qboquillas: TZReadOnlyQuery; qdepositosdeposito: TWideStringField; combotractores: TDBLookupComboBox; combovelocidad: TDBLookupComboBox; combodepositos: TDBLookupComboBox; comboboquillas: TDBLookupComboBox; comboventilador: TDBLookupComboBox; combopresiones: TDBLookupComboBox; dsqtractores: TDataSource; dsqvelocidad: TDataSource; dsqdepositos: TDataSource; dsqboquillas: TDataSource; dsqventilador: TDataSource; dsqpresiones: TDataSource; qboquillasboquilla: TWideStringField; qtratamientosbasedetallecantidad_mezcla: TIntegerField; qtratamientosbasedetalleorden: TIntegerField; qtratamientosdetalleorden: TIntegerField; combooperarios: TDBLookupComboBox; dsqoperarios: TDataSource; qoperarios: TZReadOnlyQuery; qoperariosoperario: TWideStringField; Label301: TLabel; combocampanyas: TDBLookupComboBox; dsqcampanyas: TDataSource; qcampanyas: TZReadOnlyQuery; qtratamientosbaseide: TIntegerField; qtratamientosbaseid: TIntegerField; qtratamientosbasedescripcion: TWideStringField; qtratamientosbasetipo: TWideStringField; qtratamientosbaseobservaciones: TWideStringField; qtratamientosbasefecha: TDateField; qcampanyasid: TIntegerField; qcampanyasidempresa: TIntegerField; qcampanyasid_anterior: TIntegerField; qcampanyasdescripcion: TWideStringField; qcampanyasfechainicio: TDateField; qcampanyasfechafin: TDateField; qcampanyasult_pesada: TIntegerField; fdesde: TDateTimePicker; fhasta: TDateTimePicker; Label1: TLabel; Label6: TLabel; chkimptodo: TCheckBox; qmateriaprima: TZReadOnlyQuery; qmateriaprimadescripcion: TWideStringField; Label7: TLabel; combovariedades: TDBLookupComboBox; qmateriaprima2: TZReadOnlyQuery; dsmateriasprimas: TDataSource; qmateriaprima2descripcion: TWideStringField; Button8: TButton; qinsertarencuaderno: TZQuery; qinsertarencuadernodetalle: TZQuery; DBGrid5: TDBGrid; qresumenproductos: TZReadOnlyQuery; dsqresumenproductos: TDataSource; qnombrecampanya: TZReadOnlyQuery; qnombrecampanyadescripcion: TWideStringField; qresumenproductosidcc: TWideStringField; qresumenproductosdesc_cc: TWideStringField; qresumenproductosdescripcion_af: TWideStringField; qresumenproductosdosis_recomendada: TWideStringField; qresumenproductoscampanya: TWideStringField; qresumenproductosnum_tratamientos: TFloatField; qresumenproductosnum_aplicaciones: TFloatField; qresumenproductosplazo_seguridad: TFloatField; qtratamientosdetalleidentrada: TIntegerField; qtratamientosdetallecantidadprevista_mezcla: TFloatField; qtratamientosdetallecantidadprevista_materia: TFloatField; qtratamientosdetallefecha: TDateField; qtratamientoside: TIntegerField; qtratamientosid: TIntegerField; qtratamientosfecha: TDateField; qtratamientosidcc: TWideStringField; qtratamientosdesc_cc: TWideStringField; qtratamientosresponsable: TWideStringField; qtratamientosidrecomendacion: TIntegerField; qtratamientoscontabilizado: TIntegerField; qtratamientosnif_responsable: TWideStringField; qtratamientosobservaciones: TWideStringField; qtratamientosoperario: TWideStringField; qtratamientosidjustificacion: TIntegerField; qtratamientoscondiciones_metereologicas: TWideStringField; qtratamientoshora_fin: TTimeField; qtratamientostractor: TWideStringField; qtratamientosdeposito: TWideStringField; qtratamientosvelocidad: TFloatField; qtratamientospresion: TIntegerField; qtratamientosboquilla: TWideStringField; qtratamientosventilador: TWideStringField; qtratamientosmostrar: TIntegerField; qtratamientosvariedad: TWideStringField; qtratamientosnum_boquillas: TIntegerField; qtratamientoslitros_hect: TIntegerField; qtratamientosdesc_boquilla: TWideStringField; qtratamientoslitros_minutos: TFloatField; qtratamientossuperficie: TFloatField; qtratamientosfecha_fin: TDateField; qtratamientoshora_inicio: TTimeField; qtratamientosfecha_inicio: TDateField; qtratamientosancho_calle: TFloatField; qvelocidadvelocidad: TFloatField; qpresionespresion: TIntegerField; qventiladorventilador: TWideStringField; qtratamientoscompletado: TIntegerField; Button10: TButton; qcargas: TZReadOnlyQuery; dbtratamientoscargas: TfrxDBDataset; dsqcargas: TDataSource; qcargasid: TIntegerField; qcargaside: TIntegerField; qcargasidt: TIntegerField; qcargasfecha: TDateField; qcargashora_inicio: TTimeField; qcargashora_fin: TTimeField; qcargasid_emp: TIntegerField; qcargasoperario: TWideStringField; qcargasid_tractor: TWideStringField; qcargastractor: TWideStringField; qcargasid_fumigadora: TWideStringField; qcargasfumigadora: TWideStringField; qcargascondiciones_meteorologicas: TWideStringField; qcargascantidad: TIntegerField; procedure FormKeyPress(Sender: TObject; var Key: Char); procedure dsqtratamientosStateChange(Sender: TObject); procedure btAreutilizarClick(Sender: TObject); procedure btAnuevoClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure DBGrid3DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure btAmodificarClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure DBGrid3TitleClick(Column: TColumn); procedure Button2Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure qtratamientosdetalleAfterPost(DataSet: TDataSet); procedure btAborrarClick(Sender: TObject); procedure DBGrid4DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBGrid4CellClick(Column: TColumn); procedure dsqtratamientosDataChange(Sender: TObject; Field: TField); procedure DBGrid3ColExit(Sender: TObject); procedure Button3Click(Sender: TObject); procedure FfechaChange(Sender: TObject); procedure Button7Click(Sender: TObject); procedure DBGrid4TitleClick(Column: TColumn); procedure Button9Click(Sender: TObject); procedure btfiltrarClick(Sender: TObject); procedure Button6Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure qtratamientosdetalleCalcFields(DataSet: TDataSet); procedure qtratamientosBeforePost(DataSet: TDataSet); procedure qtratamientosdetalleBeforePost(DataSet: TDataSet); procedure qtratamientosdetalleBeforeDelete(DataSet: TDataSet); procedure qtratamientosBeforeDelete(DataSet: TDataSet); procedure Button5Click(Sender: TObject); procedure qtratamientosAfterPost(DataSet: TDataSet); procedure DBGrid4KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure dsqcampanyasDataChange(Sender: TObject; Field: TField); procedure DBGrid3CellClick(Column: TColumn); procedure Button8Click(Sender: TObject); procedure qtratamientosdetalleAfterDelete(DataSet: TDataSet); procedure dsqtratamientosdetalleDataChange(Sender: TObject; Field: TField); procedure DBGrid5DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure Button10Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var tratamientos: Ttratamientos; contabilizando:integer; implementation {$R *.dfm} uses datos, principal, fbuscararticulos, fcargastratamientos; procedure Ttratamientos.btAborrarClick(Sender: TObject); begin qtratamientos.Delete; end; procedure Ttratamientos.btAcancelarClick(Sender: TObject); begin qtratamientos.Cancel; end; procedure Ttratamientos.btAguardarClick(Sender: TObject); begin qtratamientosidcc.value:=qcentrocostecodpar.AsString; qtratamientoside.Value:=qcentrocosteempresa.Asinteger; qtratamientosresponsable.Value:=qresponsablesnombre.AsString; qtratamientosnif_responsable.Value:=qresponsablesnif.asstring; qtratamientosfecha.Value:=ffecha.Date; qtratamientos.Post; qtratamientos.Refresh; end; procedure Ttratamientos.btAmodificarClick(Sender: TObject); begin qtratamientos.Edit; end; procedure Ttratamientos.btAnuevoClick(Sender: TObject); begin ffecha.Date:=date; qtratamientos.Append; qaux.Close; qaux.ParamByName('EMPRESA').AsInteger:=dm.tempresaid.asinteger; qaux.Prepare; qaux.Open; qtratamientoside.value:=dm.tempresaid.AsInteger; qtratamientosid.Value:=qaux.Fields[0].AsInteger; qtratamientosfecha.Value:=ffecha.Date; dbgrid3.setfocus; dbgrid3.SelectedIndex:=1; end; procedure Ttratamientos.btAreutilizarClick(Sender: TObject); begin panel2.Visible:=not panel2.Visible; button1.Visible:=not button1.Visible; end; procedure Ttratamientos.Button10Click(Sender: TObject); begin cargastratamientos := Tcargastratamientos.Create(nil); try cargastratamientos.vempresa:=qtratamientoside.AsInteger; cargastratamientos.vtratamiento:=qtratamientosid.AsInteger; cargastratamientos.ShowModal(); finally cargastratamientos.Free; qtratamientosdetalle.Refresh; qtratamientos.Refresh; end; end; procedure Ttratamientos.Button1Click(Sender: TObject); var idtratamiento,idempresa:integer; begin idtratamiento:=qtratamientosid.asinteger; idempresa:=qtratamientoside.AsInteger; qtratamientosbasedetalle.First; while not qtratamientosbasedetalle.Eof do begin qtratamientosdetalle.First; qtratamientosdetalle.Append; qtratamientosdetalleide.value:=idempresa; qtratamientosdetalleidaf.value:=qtratamientosbasedetalleidaf.asinteger; qtratamientosdetalleidma.value:=qtratamientosbasedetalleidma.asinteger; qtratamientosdetalledescripcion_af.value:=qtratamientosbasedetalledescripcion_af.asstring; qtratamientosdetalledescripcion_ma.value:=qtratamientosbasedetalledescripcion_ma.asstring; qtratamientosdetallecantidad_base.value:=qtratamientosbasedetallecantidad_base.asinteger; qtratamientosdetalledosis.value:=qtratamientosbasedetalledosis.asfloat; qtratamientosdetalleunidad_medida.value:=qtratamientosbasedetalleunidad_medida.asstring; qtratamientosdetalleregistro.value:=qtratamientosbasedetalleregistro.asstring; qtratamientosdetalleplazo.value:=qtratamientosbasedetalleplazo.asinteger; qtratamientosdetalleorden.value:=qtratamientosbasedetalleorden.asinteger; qtratamientosdetalle.Post; qtratamientosbasedetalle.Next; end; qtratamientos.Edit; qtratamientosobservaciones.Value:=qtratamientosbaseobservaciones.AsString; qtratamientos.Post; qtratamientos.Locate('ide,id',vararrayof([idempresa,idtratamiento]),[locaseinsensitive]); end; procedure Ttratamientos.Button2Click(Sender: TObject); begin qtratamientosdetalle.Delete; end; procedure Ttratamientos.Button3Click(Sender: TObject); begin if qtratamientosdetalleficha.AsString<>'' then begin qtratamientosdetalleficha.SaveToFile('c:\agrigest\tmp\'+qtratamientosdetalleregistro.AsString+'.pdf'); ShellExecute(Handle,nil,PChar('c:\agrigest\tmp\'+qtratamientosdetalleregistro.AsString+'.pdf'),'','',SW_SHOWNORMAL); end; end; procedure Ttratamientos.Button4Click(Sender: TObject); var imprimirtodo,vparcela,vresponsable:string; begin if combobuscarparcelas.keyvalue=null then vparcela:='%' else vparcela:=combobuscarparcelas.keyvalue; if combobuscarresponsables.keyvalue=null then vresponsable:='%' else vresponsable:=combobuscarresponsables.keyvalue; if chkimptodo.Checked then imprimirtodo:='%' else imprimirtodo:='1'; qtratamientos.Close; qtratamientos.Prepare; qtratamientos.ParamByName('parcela').AsString:=vparcela; qtratamientos.ParamByName('responsable').AsString:=vresponsable; qtratamientos.ParamByName('DESDE').AsDate:=fdesde.Date; qtratamientos.ParamByName('HASTA').AsDate:=fhasta.Date; qtratamientos.ParamByName('MOSTRAR').asstring:=imprimirtodo; qtratamientos.Open; qcargas.Close; qcargas.Prepare; qcargas.ParamByName('EMPRESA').AsInteger:=qtratamientoside.AsInteger; qcargas.ParamByName('TRATAMIENTO').AsString:='%'; qcargas.Open; qtratamientosdetalle.Filter:='en_cuaderno=1'; qtratamientosdetalle.Filtered:=true; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\inftratamientos.fr3'); informes.ShowReport(); qtratamientos.Filtered:=false; qtratamientosdetalle.Filtered:=false; end; procedure Ttratamientos.Button5Click(Sender: TObject); begin if qtratamientoscontabilizado.AsInteger=0 then begin contabilizando:=1; try qconsumos.Open; qtratamientosdetalle.First; while not qtratamientosdetalle.Eof do begin qarticulo.Close; qarticulo.Prepare; qarticulo.ParamByName('IDAF').AsString:=qtratamientosdetalleidaf.AsString; qarticulo.ParamByName('IDEMPRESA').AsString:=qtratamientoside.AsString; qarticulo.Open; qstock.Close; qstock.Prepare; qstock.ParamByName('CODIGO').AsString:=qarticulocodigo.AsString; qstock.ParamByName('EMPRESA').AsString:=qtratamientoside.AsString; qstock.Open; try qconsumos.Append; qaux2.Close; qaux2.Open; qconsumosid.Value:=qaux2.Fields[0].asinteger; qconsumosidfraccionado.Value:=qaux2.Fields[0].asinteger;; qconsumoside.Value:=dm.tempresaid.asinteger; qconsumosnumplazos.value:=1; qconsumosdescripcion.Value:=qtratamientosdetalledescripcion_af.AsString; qconsumoscantidad.Value:=qtratamientosdetallecantidad_materia.Asfloat; qconsumosprecio.Value:=qarticulopreciocoste.AsFloat; qconsumostotal.Value:=qtratamientosdetallecantidad_materia.Asfloat*qarticulopreciocoste.AsFloat; qconsumostotal_amortizado.value:=qtratamientosdetallecantidad_materia.Asfloat*qarticulopreciocoste.AsFloat; qconsumosfecha.Value:=qtratamientosfecha.AsDateTime; qconsumosidcc.Value:=qtratamientosidcc.Asstring; qconsumoscodigo.Value:=qarticulocodigo.AsString; qconsumosidgrupo.Value:=qarticuloidgrupo.AsInteger; qconsumosidfamilia.Value:=qarticuloidfamilia.Asinteger; qconsumoslote.AsString:=qstocklote.AsString; qconsumosregistro.AsString:=qarticuloregistro.AsString; qconsumosidentrada.Value:=qstockid.AsInteger; qconsumosamortizacion.Value:=0; qconsumos.Post; finally qtratamientosdetalle.Edit; qtratamientosdetalleidconsumo.value:=qaux2.Fields[0].AsInteger; qtratamientosdetalle.Post; qtratamientosdetalle.Next; end; end; finally qtratamientos.Edit; qtratamientoscontabilizado.Value:=1; qtratamientos.Post; end; contabilizando:=0; end; end; procedure Ttratamientos.Button6Click(Sender: TObject); begin qcargas.Close; qcargas.Prepare; qcargas.ParamByName('EMPRESA').AsInteger:=qtratamientoside.AsInteger; qcargas.ParamByName('TRATAMIENTO').AsString:=qtratamientosid.AsString; qcargas.Open; qtratamientos.Filter:='id='+qtratamientosid.Asstring; qtratamientos.Filtered:=true; qtratamientosdetalle.Filter:='en_cuaderno=1'; qtratamientosdetalle.Filtered:=true; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\inftratamientos.fr3'); informes.ShowReport(); qtratamientos.Filtered:=false; qtratamientosdetalle.Filtered:=false; end; procedure Ttratamientos.Button7Click(Sender: TObject); var direccion:pwidechar; registro,cadena:string; begin while not qtratamientosdetalle.eof do begin registro:= qtratamientosdetalleregistro.AsString; if registro<>'' then begin qaux.SQL.Clear; qaux.SQL.Add('select registro,autorizado from productos_fitosanitarios where registro=:REGISTRO'); qaux.Prepare; qaux.ParamByName('REGISTRO').AsString:=registro; qaux.Open; if qaux.RecordCount>0 then begin if qaux.Fields[1].AsInteger=1 then begin cadena:='https://www.mapa.gob.es/agricultura/pags/fitos/registro/productos/pdf/'+registro+'.pdf'; direccion:=pwidechar(widestring(cadena)); URLDownloadToFile(nil, direccion, 'C:\agrigest\tmp\ficha.pdf', 0, nil); qtratamientosdetalle.Edit; qtratamientosdetalleficha.LoadFromFile('c:\agrigest\tmp\ficha.pdf'); end else showmessage('PRODUCTO NO AUTORIZADO EN PRODUCTOS FITOSANITARIOS AUTORIZADOS'); end else showmessage('PRODUCTO NO ENCONTRADO EN PRODUCTOS FITOSANITARIOS AUTORIZADOS'); end; qtratamientosdetalle.Next; end; end; procedure Ttratamientos.Button8Click(Sender: TObject); var vparcela,vresponsable,vvariedad:string; begin if combobuscarparcelas.keyvalue=null then vparcela:='%' else vparcela:=combobuscarparcelas.keyvalue; if combobuscarresponsables.keyvalue=null then vresponsable:='%' else vresponsable:=combobuscarresponsables.keyvalue; if combovariedades.keyvalue=null then vvariedad:='%' else vvariedad:=combovariedades.keyvalue; qinsertarencuaderno.Close; qinsertarencuaderno.Prepare; qinsertarencuaderno.ParamByName('parcela').AsString:=vparcela; qinsertarencuaderno.ParamByName('responsable').AsString:=vresponsable; qinsertarencuaderno.ParamByName('variedad').AsString:=vvariedad; qinsertarencuaderno.ParamByName('DESDE').AsDate:=fdesde.Date; qinsertarencuaderno.ParamByName('HASTA').AsDate:=fhasta.Date; qinsertarencuaderno.ExecSQL; qinsertarencuadernodetalle.Close; qinsertarencuadernodetalle.Prepare; qinsertarencuadernodetalle.ParamByName('parcela').AsString:=vparcela; qinsertarencuadernodetalle.ParamByName('responsable').AsString:=vresponsable; qinsertarencuadernodetalle.ParamByName('variedad').AsString:=vvariedad; qinsertarencuadernodetalle.ParamByName('DESDE').AsDate:=fdesde.Date; qinsertarencuadernodetalle.ParamByName('HASTA').AsDate:=fhasta.Date; qinsertarencuadernodetalle.ExecSQL; end; procedure Ttratamientos.btfiltrarClick(Sender: TObject); var vparcela,vresponsable,vvariedad:string; begin if combobuscarparcelas.keyvalue=null then vparcela:='%' else vparcela:=combobuscarparcelas.keyvalue; if combobuscarresponsables.keyvalue=null then vresponsable:='%' else vresponsable:=combobuscarresponsables.keyvalue; if combovariedades.keyvalue=null then vvariedad:='%' else vvariedad:=combovariedades.keyvalue; qtratamientos.Close; qtratamientos.Prepare; qtratamientos.ParamByName('parcela').AsString:=vparcela; qtratamientos.ParamByName('responsable').AsString:=vresponsable; qtratamientos.ParamByName('variedad').AsString:=vvariedad; qtratamientos.ParamByName('DESDE').AsDate:=fdesde.Date; qtratamientos.ParamByName('HASTA').AsDate:=fhasta.Date; qtratamientos.ParamByName('MOSTRAR').asstring:='%'; qtratamientos.Open; qtratamientosdetalle.Open; end; procedure Ttratamientos.Button9Click(Sender: TObject); begin combobuscarparcelas.KeyValue:=null; combobuscarresponsables.KeyValue:=null; combovariedades.KeyValue:=null; btfiltrar.click; end; procedure Ttratamientos.DBGrid3CellClick(Column: TColumn); begin if column.Field.FieldName ='completado' then begin if qtratamientoscompletado.asinteger=1 then begin qtratamientos.Edit; qtratamientoscompletado.Value:=0; qtratamientos.Post; dbgrid3.selectedIndex:=1; end else begin qtratamientos.Edit; qtratamientoscompletado.Value:=1; qtratamientos.Post; qtratamientos.Refresh; dbgrid3.SelectedIndex:=1; end; end; end; procedure Ttratamientos.DBGrid3ColExit(Sender: TObject); begin if qtratamientos.State in [dsinsert,dsedit] then begin qtratamientosfecha.Value:=ffecha.Date; end else begin // qtratamientos.Edit; // qtratamientosfecha.Value:=ffecha.Date; end; end; procedure Ttratamientos.DBGrid3DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); const IsChecked : array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED); var DrawState,imgindex,bmpwidth: Integer; DrawRect: TRect; begin if (qtratamientoscontabilizado.Asinteger=0)then begin DBGrid3.Canvas.brush.Color := rojo; end else DBGrid3.Canvas.brush.Color := verde; if (qtratamientoscompletado.Asinteger=1) and (qtratamientoscontabilizado.Asinteger=0)then begin DBGrid3.Canvas.brush.Color := azul; end; DBGrid3.DefaultDrawColumnCell(Rect, DataCol, Column, State); if (gdFocused in State) then begin if (Column.Field.FieldName = 'contabilizado') then begin gcrpagado.Left := Rect.Left + DBgrid3.Left + 2; gcrpagado.Top := Rect.Top + DBgrid3.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'contabilizado') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; DBgrid3.Canvas.FillRect(Rect); DrawFrameControl(DBgrid3.Canvas.Handle, DrawRect,DFC_BUTTON, DrawState); end; end; if (gdFocused in State) then begin if (Column.Field.FieldName = 'completado') then begin gcrpagado.Left := Rect.Left + DBgrid3.Left + 2; gcrpagado.Top := Rect.Top + DBgrid3.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'completado') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; DBgrid3.Canvas.FillRect(Rect); DrawFrameControl(DBgrid3.Canvas.Handle, DrawRect,DFC_BUTTON, DrawState); end; end; gcrpagado.visible:=false; if (gdFocused in State) then begin if (Column.Field.FieldName = combocentrocoste.DataField) then with combocentrocoste do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else combocentrocoste.Visible:=false; if (Column.Field.FieldName = comboresponsables.DataField) then with comboresponsables do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else comboresponsables.Visible:=false; if (Column.Field.FieldName = combotractores.DataField) then with combotractores do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else combotractores.Visible:=false; if (Column.Field.FieldName = combodepositos.DataField) then with combodepositos do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else combodepositos.Visible:=false; if (Column.Field.FieldName = combovelocidad.DataField) then with combovelocidad do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else combovelocidad.Visible:=false; if (Column.Field.FieldName = combopresiones.DataField) then with combopresiones do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else combopresiones.Visible:=false; if (Column.Field.FieldName = comboboquillas.DataField) then with comboboquillas do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else comboboquillas.Visible:=false; if (Column.Field.FieldName = comboventilador.DataField) then with comboventilador do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else comboventilador.Visible:=false; if (Column.Field.FieldName = combooperarios.DataField) then with combooperarios do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else combooperarios.Visible:=false; if (Column.Field.FieldName = 'fecha') then with ffecha do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; end else begin ffecha.Visible:=false; end; end; end; procedure Ttratamientos.DBGrid3TitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=qtratamientos.SortType; qtratamientos.SortedFields:=Column.FieldName; If st = stAscending then qtratamientos.SortType:=stDescending else qtratamientos.SortType:=stAscending; dsqtratamientos.DataSet.First; end; procedure Ttratamientos.DBGrid4CellClick(Column: TColumn); begin if column.Field.FieldName ='en_cuaderno' then begin if qtratamientosdetalleen_cuaderno.asinteger=1 then begin qtratamientosdetalle.Edit; qtratamientosdetalleen_cuaderno.Value:=0; qtratamientosdetalle.Post; dbgrid4.selectedIndex:=1; end else begin qtratamientosdetalle.Edit; qtratamientosdetalleen_cuaderno.Value:=1; qtratamientosdetalle.Post; qtratamientosdetalle.Refresh; dbgrid4.SelectedIndex:=1; end; end; end; procedure Ttratamientos.DBGrid4DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); const IsChecked : array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED); var DrawState,imgindex,bmpwidth: Integer; DrawRect: TRect; fixRect:TRect; bitmap:tbitmap; begin fixRect := Rect; if (gdFocused in State) then begin if (Column.Field.FieldName = 'en_cuaderno') then begin gcrpagado.Left := Rect.Left + DBgrid4.Left + 2; gcrpagado.Top := Rect.Top + DBgrid4.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'en_cuaderno') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; // DrawState := ISChecked[Column.Field.Asboolean]; DBgrid4.Canvas.FillRect(Rect); DrawFrameControl(DBgrid4.Canvas.Handle, DrawRect,DFC_BUTTON, DrawState); end; end; gcrpagado.visible:=false; fixRect := Rect; if column.Title.Caption ='Ficha' then begin if qtratamientosdetalle.FieldByname('conficha').Asstring=' ' then imgIndex := 88 else imgIndex := -1; bitmap := TBitmap.Create; try base.listaiconos.GetBitmap(imgIndex,bitmap); bmpWidth := (Rect.Bottom - Rect.Top); fixRect.right := Rect.Left + bmpWidth; DBGrid4.Canvas.StretchDraw(fixRect,bitmap); finally bitmap.Free; end; fixRect := Rect; fixRect.Left := fixRect.Left + bmpWidth; // DBgrid4.Canvas.FillRect(Rect); DBGrid4.DefaultDrawColumnCell(fixRect,-1,Column,State); end; end; procedure Ttratamientos.DBGrid4KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (key=115) then begin buscararticulos := Tbuscararticulos.Create(nil); try fbuscararticulos.filtro:=qtratamientosdetalledescripcion_af.AsString; buscararticulos.Edit1.Text:=qtratamientosdetalledescripcion_af.AsString; buscararticulos.showmodal(); finally if qtratamientosdetalle.State in [dsbrowse] then qtratamientosdetalle.Edit; qtratamientosdetalleidaf.Value:=buscararticulos.qarticulosid.Asinteger; qtratamientosdetalleregistro.Value:=buscararticulos.qarticulosregistro.Asstring; qtratamientosdetalledescripcion_af.value:=buscararticulos.qarticulosdescripcion.AsString; qtratamientosdetalledescripcion_ma.Value:=buscararticulos.qarticulosmateria_activa.Asstring; qtratamientosdetalledosis.value:=0; qtratamientosdetalleplazo.value:=buscararticulos.qarticulosplazo_seguridad.Asinteger; buscararticulos.Free; end; end; end; procedure Ttratamientos.DBGrid4TitleClick(Column: TColumn); var st:ZAbstractRODataset.TSortType; begin st:=qtratamientosdetalle.SortType; qtratamientos.SortedFields:=Column.FieldName; If st = stAscending then qtratamientosdetalle.SortType:=stDescending else qtratamientosdetalle.SortType:=stAscending; dsqtratamientosdetalle.DataSet.First; end; procedure Ttratamientos.DBGrid5DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if (qresumenproductosnum_tratamientos.Asinteger>qresumenproductosnum_aplicaciones.asinteger)then begin DBGrid5.Canvas.brush.Color := rojo; end ; DBGrid5.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure Ttratamientos.dsqcampanyasDataChange(Sender: TObject; Field: TField); begin qtratamientosbase.Close; qtratamientosbase.Prepare; qtratamientosbase.ParamByName('FINICIO').AsDate:=qcampanyasfechainicio.asdatetime; qtratamientosbase.ParamByName('FFIN').AsDate:=qcampanyasfechafin.asdatetime; qtratamientosbase.ParamByName('EMPRESA').Asinteger:=qcampanyasidempresa.AsInteger; qtratamientosbase.Open; end; procedure Ttratamientos.dsqtratamientosDataChange(Sender: TObject; Field: TField); begin if qtratamientos.State in [dsbrowse] then begin ffecha.Date:=qtratamientosfecha.AsDateTime; comboresponsables.Visible:=false; combocentrocoste.Visible:=false; end; qnombrecampanya.Prepare; qnombrecampanya.ParamByName('FECHA').AsDateTime:=qtratamientosfecha.AsDateTime; qnombrecampanya.refresh; qresumenproductos.Prepare; qresumenproductos.ParamByName('PARCELA').AsString:=qtratamientosidcc.AsString; qresumenproductos.ParamByName('CAMPANYA').AsString:=qnombrecampanyadescripcion.asstring; qresumenproductos.refresh; qtratamientosdetalle.Prepare; qtratamientosdetalle.ParamByName('EMPRESA').AsInteger:=qtratamientoside.AsInteger; qtratamientosdetalle.ParamByName('TRATAMIENTO').AsInteger:=qtratamientosid.AsInteger; qtratamientosdetalle.Refresh; end; procedure Ttratamientos.dsqtratamientosdetalleDataChange(Sender: TObject; Field: TField); begin qresumenproductos.Locate('descripcion_af',qtratamientosdetalledescripcion_af.AsString,[loCaseInsensitive]); end; procedure Ttratamientos.dsqtratamientosStateChange(Sender: TObject); begin if qtratamientos.State in [dsedit,dsinsert] then begin btanuevo.Enabled:=false; btamodificar.Enabled:=false; btaborrar.Enabled:=false; btacancelar.Enabled:=true; btaguardar.Enabled:=true; btareutilizar.enabled:=false; button3.Enabled:=false; button2.Enabled:=false; end else begin btanuevo.Enabled:=true; btamodificar.Enabled:=true; btaborrar.Enabled:=true; btacancelar.Enabled:=false; btaguardar.Enabled:=false; panel2.Visible:=false; button1.Visible:=false; btareutilizar.enabled:=true; button2.Enabled:=true; button3.Enabled:=true; ffecha.visible:=false; comboresponsables.Visible:=false; combocentrocoste.Visible:=false; end; end; procedure Ttratamientos.FfechaChange(Sender: TObject); begin qtratamientos.Edit; end; procedure Ttratamientos.FormKeyPress(Sender: TObject; var Key: Char); begin key:=upcase(key); if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; // si presionamos ESC if (key=#$1B) and (activecontrol is tdblookupcombobox )then begin activecontrol.Visible:=false; end; end; procedure Ttratamientos.FormShow(Sender: TObject); var anyo,mes,dia:word; begin decodedate(date,anyo,mes,dia); fdesde.Date:=(strtodate('01/01/'+inttostr(anyo))); fhasta.Date:=(strtodate('31/12/'+inttostr(anyo))); ffecha.Date:=date; qcampanyas.Open; combocampanyas.KeyValue:=qcampanyasdescripcion.Asstring; qtratamientosbasedetalle.Close; qcentrocoste.close; qresponsables.Close; qtratamientos.Close; qtratamientosdetalle.close; qcentrocoste2.close; qresponsables2.Close; qmateriaprima2.Close; qtractores.close; qvelocidad.close; qdepositos.close; qboquillas.close; qpresiones.close; qventilador.close; qtratamientosbasedetalle.open; qcentrocoste.open; qresponsables.open; qcentrocoste2.open; qresponsables2.open; qmateriaprima2.open; qnombrecampanya.Open; qresumenproductos.Open; qtratamientosdetalle.open; qtratamientos.ParamByName('parcela').AsString:='%'; qtratamientos.ParamByName('responsable').AsString:='%'; qtratamientos.ParamByName('DESDE').AsDate:=fdesde.Date; qtratamientos.ParamByName('HASTA').AsDate:=fhasta.Date; qtratamientos.ParamByName('MOSTRAR').asstring:='%'; qtratamientos.Prepare; qtratamientos.open; qtractores.Open; qvelocidad.Open; qdepositos.Open; qboquillas.Open; qpresiones.Open; qventilador.Open; qoperarios.Open; button9.Click; end; procedure Ttratamientos.qtratamientosAfterPost(DataSet: TDataSet); begin qtractores.refresh; qvelocidad.refresh; qdepositos.refresh; qboquillas.refresh; qpresiones.refresh; qventilador.refresh; qoperarios.Refresh; end; procedure Ttratamientos.qtratamientosBeforeDelete(DataSet: TDataSet); begin case dm.PedirConfirmacion('¿Confirma que desea borrar este tratamiento?',true,true,false) of mrno:Abort; end; end; procedure Ttratamientos.qtratamientosBeforePost(DataSet: TDataSet); var x:integer; begin if contabilizando=0 then begin qmateriaprima.Close; qmateriaprima.Prepare; qmateriaprima.ParamByName('EMPRESA').AsInteger:=qtratamientoside.asinteger; qmateriaprima.ParamByName('PARCELA').Asstring:=qtratamientosidcc.asstring; qmateriaprima.Open; qtratamientosvariedad.asstring:=qmateriaprimadescripcion.AsString; qtratamientosidcc.Value:=qcentrocostecodpar.AsString; if qtratamientos.state=dsinsert then x:=dm.PedirConfirmacion('¿Confirma que desea dar de alta este tratamiento?',true,true,true) else x:=dm.PedirConfirmacion('¿Confirma que desea modificar este tratamiento?',true,true,true); case x of mrno: begin qtratamientos.cancel; abort; end; mrcancel:BEGIN abort; END; end; end; end; procedure Ttratamientos.qtratamientosdetalleAfterDelete(DataSet: TDataSet); begin qresumenproductos.Refresh; end; procedure Ttratamientos.qtratamientosdetalleAfterPost(DataSet: TDataSet); begin qtratamientosdetalle.Refresh; qresumenproductos.Refresh; end; procedure Ttratamientos.qtratamientosdetalleBeforeDelete(DataSet: TDataSet); begin case dm.PedirConfirmacion('¿Confirma que desea borrar este tratamiento?',true,true,false) of mrno:Abort; end; end; procedure Ttratamientos.qtratamientosdetalleBeforePost(DataSet: TDataSet); var x:integer; begin qtratamientosdetalleide.Value:=qtratamientoside.AsInteger; qtratamientosdetalleidt.Value:=qtratamientosid.AsInteger; if contabilizando=0 then begin if qtratamientosdetalle.state=dsinsert then x:=dm.PedirConfirmacion('¿Confirma que desea dar de alta este producto?',true,true,true) else x:=dm.PedirConfirmacion('¿Confirma que desea modificar este producto?',true,true,true); case x of mrno: begin qtratamientosdetalle.cancel; abort; end; mrcancel:BEGIN abort; END; end; end; end; procedure Ttratamientos.qtratamientosdetalleCalcFields(DataSet: TDataSet); begin if qtratamientosdetalleficha.AsString<>'' then qtratamientosdetalleconficha.Value:=' ' else qtratamientosdetalleconficha.Value:=''; end; end. ======================================== FICHERO: ftratamientosbase.pas ======================================== unit ftratamientosbase; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.DBCtrls, frxClass, frxDBSet; type Ttratamientosbase = class(TForm) qtratamientos: TZQuery; qtratamientosdetalle: TZQuery; dstratamientos: TDataSource; qtratamientoside: TIntegerField; qtratamientosid: TIntegerField; qtratamientosdescripcion: TWideStringField; qtratamientostipo: TWideStringField; qtratamientosdetalleide: TIntegerField; qtratamientosdetalleidt: TIntegerField; qtratamientosdetalleidaf: TIntegerField; qtratamientosdetalleidma: TIntegerField; qtratamientosdetalledescripcion_af: TWideStringField; qtratamientosdetallecantidad_base: TFloatField; qtratamientosdetalledosis: TFloatField; qtratamientosdetalleunidad_medida: TWideStringField; dstratamientosdetalle: TDataSource; Panel2: TPanel; Panel3: TPanel; Panel4: TPanel; Panel1: TPanel; DBGrid2: TDBGrid; qtratamientosdetalledescripcion_ma: TWideStringField; qtratamientosdetalleregistro: TWideStringField; qtratamientosdetalleplazo: TIntegerField; qtratamientosobservaciones: TWideStringField; qtratamientosdetalleficha: TBlobField; qtratamientosdetallecantidad_mezcla: TIntegerField; qtratamientosdetallecantidad_materia: TFloatField; Button4: TButton; dbtratamiento: TfrxDBDataset; dbempresa: TfrxDBDataset; dbtratamientosdetalle: TfrxDBDataset; informes: TfrxReport; btAnuevo: TButton; btAborrar: TButton; btAmodificar: TButton; btAguardar: TButton; btAcancelar: TButton; Panel13: TPanel; Button2: TButton; Button3: TButton; qaux: TZQuery; qtratamientosdetalleorden: TIntegerField; DBGrid1: TDBGrid; Panel5: TPanel; qcampanyas: TZReadOnlyQuery; qcampanyasid: TIntegerField; qcampanyasidempresa: TIntegerField; qcampanyasid_anterior: TIntegerField; qcampanyasdescripcion: TWideStringField; qcampanyasfechainicio: TDateField; qcampanyasfechafin: TDateField; qcampanyasult_pesada: TIntegerField; dsqcampanyas: TDataSource; combocampanyas: TDBLookupComboBox; Label301: TLabel; qtratamientosfecha: TDateField; Button1: TButton; qtratamientos2: TZQuery; qtratamientos2ide: TIntegerField; qtratamientos2id: TIntegerField; qtratamientos2descripcion: TWideStringField; qtratamientos2tipo: TWideStringField; qtratamientos2observaciones: TWideStringField; qtratamientos2fecha: TDateField; qinsertardetalles2: TZReadOnlyQuery; qtratamientosvelocidad: TFloatField; qtratamientosnum_boquillas: TIntegerField; Button5: TButton; qtratamientospresion: TIntegerField; qtratamientoslitros_hect: TIntegerField; qboquillas: TZReadOnlyQuery; dsqboquillas: TDataSource; comboboquillas: TDBLookupComboBox; qboquillasid: TIntegerField; qboquillascodigo: TWideStringField; qboquillasdescripcion: TWideStringField; qboquillasFloatField5bar: TFloatField; qboquillasFloatField6bar: TFloatField; qboquillasFloatField7bar: TFloatField; qboquillasFloatField8bar: TFloatField; qboquillasFloatField9bar: TFloatField; qboquillasFloatField10bar: TFloatField; qboquillasFloatField11bar: TFloatField; qboquillasFloatField12bar: TFloatField; qboquillasFloatField13bar: TFloatField; qboquillasFloatField14bar: TFloatField; qboquillasFloatField15bar: TFloatField; qboquillasFloatField16bar: TFloatField; qboquillasFloatField17bar: TFloatField; qboquillasFloatField18bar: TFloatField; qboquillasFloatField19bar: TFloatField; qboquillasFloatField20bar: TFloatField; qboquillasFloatField21bar: TFloatField; qboquillasFloatField22bar: TFloatField; qboquillasFloatField23bar: TFloatField; qboquillasFloatField24bar: TFloatField; qboquillasFloatField25bar: TFloatField; qtratamientosdesc_boquilla: TWideStringField; qlitrosminuto: TZReadOnlyQuery; qtratamientoslitros_minuto: TFloatField; qtratamientostipo_boquilla: TWideStringField; Button6: TButton; Panel6: TPanel; Panel7: TPanel; Panel8: TPanel; Panel9: TPanel; DBGrid3: TDBGrid; DBGrid4: TDBGrid; Panel10: TPanel; Button7: TButton; Button8: TButton; Panel11: TPanel; DBGrid5: TDBGrid; dsqvariedades: TDataSource; qvariedadesparcelas: TZReadOnlyQuery; qvariedadesparcelasvariedad: TWideStringField; qparcelas: TZReadOnlyQuery; qparcelascodpar: TWideStringField; qparcelasnombre: TWideStringField; qparcelassuperficie: TFloatField; qparcelasancho_calle: TFloatField; qparcelasempresa: TIntegerField; qparcelasnumero: TWideStringField; dsqparcelas: TDataSource; dsqparcelasrecomendacion: TDataSource; qparcelasrecomendacion: TZQuery; qparcelasrecomendacionid: TIntegerField; qparcelasrecomendacionide: TIntegerField; qparcelasrecomendacionidtb: TIntegerField; qparcelasrecomendacionparcela: TWideStringField; qparcelasrecomendacionsuperficie: TFloatField; qparcelasrecomendacionancho_calle: TFloatField; qparcelasrecomendacionidparcela: TWideStringField; qtratamientosancho_calle: TFloatField; qparcelasrecomendaciondistancialineal: TIntegerField; qtratamientos2velocidad: TFloatField; qtratamientos2num_boquillas: TIntegerField; qtratamientos2tipo_boquilla: TWideStringField; qtratamientos2presion: TIntegerField; qtratamientos2litros_hect: TIntegerField; qtratamientos2desc_boquilla: TWideStringField; qtratamientos2litros_minuto: TFloatField; qtratamientos2ancho_calle: TFloatField; qpresion: TZReadOnlyQuery; qpresioncodigo: TWideStringField; qpresionpresion: TIntegerField; qpresionlitros_hect: TFloatField; qtratamientosventilador: TWideStringField; procedure FormShow(Sender: TObject); procedure qtratamientosBeforePost(DataSet: TDataSet); procedure DBGrid2KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure Button4Click(Sender: TObject); procedure qtratamientosdetalleAfterPost(DataSet: TDataSet); procedure Button2Click(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure btAnuevoClick(Sender: TObject); procedure btAmodificarClick(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); procedure dstratamientosStateChange(Sender: TObject); procedure dsqcampanyasDataChange(Sender: TObject; Field: TField); procedure Button1Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure qtratamientosAfterPost(DataSet: TDataSet); procedure Button6Click(Sender: TObject); procedure Button8Click(Sender: TObject); procedure Button7Click(Sender: TObject); procedure dstratamientosDataChange(Sender: TObject; Field: TField); procedure dsqvariedadesDataChange(Sender: TObject; Field: TField); private { Private declarations } public { Public declarations } end; var tratamientosbase: Ttratamientosbase; implementation {$R *.dfm} uses datos, fbuscararticulos, fselecparcelas, fboquillas, fgenerartratamientos; procedure Ttratamientosbase.btAborrarClick(Sender: TObject); begin qtratamientos.Delete; end; procedure Ttratamientosbase.btAcancelarClick(Sender: TObject); begin qtratamientos.Cancel; end; procedure Ttratamientosbase.btAguardarClick(Sender: TObject); begin qtratamientos.Post; end; procedure Ttratamientosbase.btAmodificarClick(Sender: TObject); begin qtratamientos.Edit; end; procedure Ttratamientosbase.btAnuevoClick(Sender: TObject); begin qaux.Close; qaux.ParamByName('EMPRESA').AsInteger:=dm.tempresaid.asinteger; qaux.Prepare; qaux.Open; qtratamientos.Append; qtratamientoside.value:=dm.tempresaid.AsInteger; qtratamientosid.Value:=qaux.Fields[0].AsInteger; qtratamientosfecha.Value:=date(); end; procedure Ttratamientosbase.Button1Click(Sender: TObject); begin qaux.Close; qaux.ParamByName('EMPRESA').AsInteger:=dm.tempresaid.asinteger; qaux.Prepare; qaux.Open; qtratamientos2.Open; qtratamientos2.Append; qtratamientos2ide.value:=qtratamientoside.AsInteger; qtratamientos2id.Value:=qaux.Fields[0].AsInteger; qtratamientos2fecha.Value:=date(); qtratamientos2observaciones.value:=qtratamientosobservaciones.AsString; qtratamientos2descripcion.value:=qtratamientosdescripcion.AsString; qtratamientos2tipo.value:=qtratamientostipo.asstring; qtratamientos2velocidad.value:=qtratamientosvelocidad.Asfloat; qtratamientos2num_boquillas.value:=qtratamientosnum_boquillas.Asinteger; qtratamientos2presion.value:=qtratamientospresion.Asinteger; qtratamientos2litros_hect.value:=qtratamientoslitros_hect.Asinteger; qtratamientos2desc_boquilla.value:=qtratamientosdesc_boquilla.AsString; qtratamientos2litros_minuto.value:=qtratamientoslitros_minuto.Asinteger; qtratamientos2tipo_boquilla.value:=qtratamientostipo_boquilla.AsString; qtratamientos2ancho_calle.value:=qtratamientosancho_calle.Asfloat; qtratamientos2.post; qinsertardetalles2.Prepare; qinsertardetalles2.ParamByName('IDTNEW').AsInteger:=qaux.Fields[0].AsInteger; qinsertardetalles2.ParamByName('IDTOLD').AsInteger:=qtratamientosid.AsInteger; qinsertardetalles2.ParamByName('EMPRESA').AsInteger:=qtratamientoside.asinteger; qinsertardetalles2.ExecSQL; qcampanyas.First; combocampanyas.KeyValue:=qcampanyasdescripcion.AsString; qtratamientosdetalle.refresh; end; procedure Ttratamientosbase.Button2Click(Sender: TObject); begin qtratamientosdetalle.Delete; end; procedure Ttratamientosbase.Button4Click(Sender: TObject); begin qtratamientos.Filter:='id='+qtratamientosid.Asstring; qtratamientos.Filtered:=true; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\inftratamientosbase.fr3'); informes.ShowReport(); qtratamientos.Filtered:=false; end; procedure Ttratamientosbase.Button5Click(Sender: TObject); begin generartratamientos := Tgenerartratamientos.Create(nil); try generartratamientos.vrecomendacion:=qtratamientosid.AsInteger; generartratamientos.vempresa:=qtratamientoside.AsInteger; generartratamientos.ShowModal(); finally generartratamientos.Free; end; end; procedure Ttratamientosbase.Button6Click(Sender: TObject); begin boquillas := Tboquillas.Create(nil); try boquillas.ShowModal; finally boquillas.Free; end; end; procedure Ttratamientosbase.Button7Click(Sender: TObject); begin qparcelasrecomendacion.delete; qparcelas.Close; qparcelas.open; end; procedure Ttratamientosbase.Button8Click(Sender: TObject); begin qparcelasrecomendacion.Append; qparcelasrecomendacionide.value:=qtratamientoside.AsInteger; qparcelasrecomendacionidtb.value:=qtratamientosid.AsInteger; qparcelasrecomendacionidparcela.value:=qparcelasnumero.AsSTRING; qparcelasrecomendacionparcela.value:=qparcelasnombre.AsString; qparcelasrecomendacionsuperficie.value:=qparcelassuperficie.AsFloat; qparcelasrecomendacionancho_calle.value:=qparcelasancho_calle.AsFloat; qparcelasrecomendacion.Post; qparcelas.Refresh; qparcelasrecomendacion.Refresh end; procedure Ttratamientosbase.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if (gdFocused in State) then begin if (Column.Field.FieldName = comboboquillas.DataField) then with comboboquillas do begin Left := Rect.Left + DBGrid1.Left + 2; Top := Rect.Top + DBGrid1.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else comboboquillas.Visible:=false; end; end; procedure Ttratamientosbase.DBGrid2KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (key=115) then begin buscararticulos := Tbuscararticulos.Create(nil); try fbuscararticulos.filtro:=qtratamientosdetalledescripcion_af.AsString; buscararticulos.Edit1.Text:=qtratamientosdetalledescripcion_af.AsString; buscararticulos.showmodal(); finally if qtratamientosdetalle.State in [dsbrowse] then qtratamientosdetalle.Edit; qtratamientosdetalleidaf.Value:=buscararticulos.qarticulosid.Asinteger; qtratamientosdetalleregistro.Value:=buscararticulos.qarticulosregistro.Asstring; qtratamientosdetalledescripcion_af.value:=buscararticulos.qarticulosdescripcion.AsString; qtratamientosdetalledescripcion_ma.Value:=buscararticulos.qarticulosmateria_activa.Asstring; qtratamientosdetalledosis.value:=0; qtratamientosdetalleplazo.value:=buscararticulos.qarticulosplazo_seguridad.Asinteger; buscararticulos.Free; end; end; end; procedure Ttratamientosbase.dsqcampanyasDataChange(Sender: TObject; Field: TField); begin qtratamientos.Close; qtratamientos.Prepare; qtratamientos.ParamByName('FINICIO').AsDate:=qcampanyasfechainicio.asdatetime; qtratamientos.ParamByName('FFIN').AsDate:=qcampanyasfechafin.asdatetime; qtratamientos.ParamByName('EMPRESA').Asinteger:=qcampanyasidempresa.AsInteger; qtratamientos.Open; end; procedure Ttratamientosbase.dsqvariedadesDataChange(Sender: TObject; Field: TField); var vvariedad:string; begin qparcelas.Close; qparcelas.Prepare; qparcelas.ParamByName('EMPRESA').AsInteger:=qtratamientoside.AsInteger; if qvariedadesparcelasvariedad.AsString=' CUALQUIERA' then vvariedad:='%' else vvariedad:=qvariedadesparcelasvariedad.AsString; qparcelas.ParamByName('VARIEDAD').AsString:=vvariedad; qparcelas.ParamByName('RECOMENDACION').AsInteger:=qtratamientosid.AsInteger; qparcelas.Open; end; procedure Ttratamientosbase.dstratamientosDataChange(Sender: TObject; Field: TField); begin qvariedadesparcelas.open; qparcelasrecomendacion.Close; qparcelasrecomendacion.Prepare; qparcelasrecomendacion.ParamByName('EMPRESA').AsInteger:=qtratamientoside.asinteger; qparcelasrecomendacion.ParamByName('TRATAMIENTO').AsInteger:=qtratamientosid.asinteger; qparcelasrecomendacion.Open; end; procedure Ttratamientosbase.dstratamientosStateChange(Sender: TObject); begin if qtratamientos.State in [dsedit,dsinsert] then begin btanuevo.Enabled:=false; btamodificar.Enabled:=false; btaborrar.Enabled:=false; btacancelar.Enabled:=true; btaguardar.Enabled:=true; button3.Enabled:=false; button2.Enabled:=false; end else begin btanuevo.Enabled:=true; btamodificar.Enabled:=true; btaborrar.Enabled:=true; btacancelar.Enabled:=false; btaguardar.Enabled:=false; button2.Enabled:=true; button3.Enabled:=true; end; end; procedure Ttratamientosbase.FormKeyPress(Sender: TObject; var Key: Char); begin key:=upcase(key); if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Ttratamientosbase.FormShow(Sender: TObject); begin qcampanyas.Open; combocampanyas.KeyValue:=qcampanyasdescripcion.Asstring; qtratamientosdetalle.Open; qboquillas.Open; end; procedure Ttratamientosbase.qtratamientosAfterPost(DataSet: TDataSet); begin qtratamientos.Refresh; abort; end; procedure Ttratamientosbase.qtratamientosBeforePost(DataSet: TDataSet); var campo:string; begin if qtratamientospresion.AsString='' then begin qpresion.Close; qpresion.Prepare; qpresion.ParamByName('ANCHO').AsFloat:=qtratamientosancho_calle.AsFloat; qpresion.ParamByName('VELOCIDAD').AsInteger:=qtratamientosvelocidad.asinteger; qpresion.ParamByName('BOQUILLAS').AsInteger:=qtratamientosnum_boquillas.AsInteger; qpresion.ParamByName('LITROS').Asinteger:=qtratamientoslitros_hect.AsInteger; qpresion.ParamByName('CODBOQUILLA').AsString:=qboquillascodigo.asstring; qpresion.Open; campo:=qpresionpresion.AsString+'bar'; qlitrosminuto.Close; qlitrosminuto.SQL.Clear; qlitrosminuto.SQL.Add('select '+campo+' from boquillas where codigo=:BOQUILLA'); qlitrosminuto.Prepare; qlitrosminuto.ParamByName('BOQUILLA').AsString:=qboquillascodigo.AsString; qlitrosminuto.Open; qtratamientoside.Value:=dm.tempresaid.asinteger; qtratamientostipo_boquilla.Value:=qboquillascodigo.AsString; qtratamientoslitros_minuto.value:=qlitrosminuto.Fields[0].AsFloat; qtratamientospresion.value:=qpresionpresion.AsInteger; end else begin campo:=qtratamientospresion.AsString+'bar'; qlitrosminuto.Close; qlitrosminuto.SQL.Clear; qlitrosminuto.SQL.Add('select '+campo+' from boquillas where codigo=:BOQUILLA'); qlitrosminuto.Prepare; qlitrosminuto.ParamByName('BOQUILLA').AsString:=qboquillascodigo.AsString; qlitrosminuto.Open; qtratamientoside.Value:=dm.tempresaid.asinteger; qtratamientostipo_boquilla.Value:=qboquillascodigo.AsString; qtratamientoslitros_minuto.value:=qlitrosminuto.Fields[0].AsFloat; end; end; procedure Ttratamientosbase.qtratamientosdetalleAfterPost(DataSet: TDataSet); begin qtratamientosdetalle.Refresh; end; end. ======================================== FICHERO: ftraza_materiales.pas ======================================== unit ftraza_materiales; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZDataset, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, frxClass,frxDBSet,Excel2000, ComObj, Vcl.DBCtrls, frxExportCSV, frxExportPDF; type Ttraza_materiales = class(TForm) Panel4: TPanel; btexcel: TButton; SaveDialog1: TSaveDialog; dsqpesadas2: TDataSource; qpesadas2: TZReadOnlyQuery; qpesadas2proveedor: TWideStringField; qpesadas2documento: TWideStringField; qpesadas2codigo: TWideStringField; qpesadas2lote: TWideStringField; qpesadas2id: TIntegerField; qpesadas2idea: TIntegerField; qpesadas2fecha: TDateField; qpesadas2iddestino: TWideStringField; qpesadas2origen: TWideStringField; qpesadas2idorigen: TIntegerField; qpesadas2parcela: TWideStringField; qpesadas2lotes_detalle: TWideStringField; qpesadas2idalbaran: TWideStringField; qpesadas2nombre: TWideStringField; qpesadas2pedidocliente: TWideStringField; qpesadas2destino: TWideStringField; qpesadas2factura: TWideStringField; Panel2: TPanel; DBGrid2: TDBGrid; qpesadas: TZReadOnlyQuery; qpesadasproveedor: TWideStringField; qpesadasdocumento: TWideStringField; qpesadascodigo: TWideStringField; qpesadaslote: TWideStringField; qpesadasid: TIntegerField; qpesadasidea: TIntegerField; qpesadasfecha: TDateField; qpesadasiddestino: TWideStringField; qpesadasorigen: TWideStringField; qpesadasidorigen: TIntegerField; qpesadasparcela: TWideStringField; qpesadaslotes_detalle: TWideStringField; qpesadasidalbaran: TWideStringField; qpesadasfactura: TWideStringField; qpesadasnombre: TWideStringField; qpesadaspedidocliente: TWideStringField; qpesadasdestino: TWideStringField; procedure btexcelClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } procedure ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar = nil); end; var traza_materiales: Ttraza_materiales; implementation {$R *.dfm} procedure Ttraza_materiales.ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar); 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 // 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 Ttraza_materiales.FormShow(Sender: TObject); begin // qpesadas2.open; end; procedure Ttraza_materiales.btexcelClick(Sender: TObject); var archivo:string; begin savedialog1.FileName:='TRAZABILIDAD MATERIALES.xls'; savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'PESADAS',DBGRID2); finally showmessage('Los datos han sido exportados correctamente a '+archivo); end; end; end. ======================================== FICHERO: ftraza_materiales2.pas ======================================== unit ftraza_materiales2; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZDataset, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, frxClass,frxDBSet,Excel2000, ComObj, Vcl.DBCtrls, frxExportCSV, frxExportPDF; type Ttraza_materiales2 = class(TForm) Panel2: TPanel; Panel1: TPanel; DBGrid2: TDBGrid; Panel4: TPanel; btexcel: TButton; SaveDialog1: TSaveDialog; dsqpesadas: TDataSource; qpesadas: TZReadOnlyQuery; qpesadasidea: TIntegerField; qpesadasidea2: TIntegerField; qpesadasidaf: TIntegerField; qpesadasdescripcion: TWideStringField; qpesadascantidad: TFloatField; qpesadaslote: TWideStringField; qpesadasdoc_compra: TWideStringField; qpesadasproveedor: TWideStringField; qpesadasdocumento: TWideStringField; procedure btexcelClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar = nil); end; var traza_materiales2: Ttraza_materiales2; implementation {$R *.dfm} procedure Ttraza_materiales2.ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar); 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 // 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 Ttraza_materiales2.btexcelClick(Sender: TObject); var archivo:string; begin savedialog1.FileName:='TRAZABILIDAD MATERIALES.xls'; savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'MATERIALES AUXILIARES',DBGRID2); finally showmessage('Los datos han sido exportados correctamente a '+archivo); end; end; end. ======================================== FICHERO: fusuarios.pas ======================================== unit fusuarios; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.DBCtrls, Vcl.StdCtrls, Vcl.ExtCtrls, Data.DB, ZDataset, ZAbstractRODataset, ZAbstractDataset, Vcl.Grids, Vcl.DBGrids; type Tusuarios = class(TForm) DBGrid1: TDBGrid; dsqusuarios: TDataSource; qusuarios: TZQuery; qtrabajadores: TZReadOnlyQuery; qgrupos: TZReadOnlyQuery; dsqtrabajadores: TDataSource; dsqgrupos: TDataSource; qusuariosid: TIntegerField; qusuariosnombre: TWideStringField; qusuariosnif: TWideStringField; qusuariosempresa: TIntegerField; qusuariosdireccion: TWideStringField; qusuariosprovin: TWideStringField; qusuarioscity: TWideStringField; qusuarioscp: TWideStringField; qusuariosphone: TWideStringField; qusuariosmovil: TWideStringField; qusuariosusuario: TWideStringField; qusuarioscontra: TWideStringField; qusuariosadministrador: TIntegerField; qusuariosgestorgrupo: TIntegerField; qusuariosgrupo: TIntegerField; qusuariosgestorindividual: TIntegerField; qusuariosidemp: TIntegerField; qusuariosactive: TIntegerField; qmaxusuario: TZReadOnlyQuery; Panel7: TPanel; btAcancelar: TButton; btAmodificar: TButton; btAborrar: TButton; btAnuevo: TButton; btAguardar: TButton; combotrabajadores: TDBLookupComboBox; combogrupos: TDBLookupComboBox; qusuariosnomgrupo: TWideStringField; qusuariosnomtrabajador: TWideStringField; gcrpagado: TDBCheckBox; qgruposide: TIntegerField; qgruposid: TIntegerField; qgruposdescripcion: TWideStringField; qtrabajadoreside: TIntegerField; qtrabajadoresid: TSmallintField; qtrabajadoresnif: TWideStringField; qtrabajadoresnombre: TWideStringField; qtrabajadoresresponsable: TIntegerField; qtrabajadoresfumigador: TIntegerField; qmaxusuarioid: TLargeintField; qusuariosfumigador: TIntegerField; qusuariostecnico: TIntegerField; procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); procedure DBGrid1CellClick(Column: TColumn); procedure btAnuevoClick(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure btAmodificarClick(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); procedure qusuariosBeforePost(DataSet: TDataSet); procedure qusuariosAfterInsert(DataSet: TDataSet); private { Private declarations } public { Public declarations } end; var usuarios: Tusuarios; const rojo = $00AAAAFF; amarillo = $00B9FFFF; verde = $00C7FBAA; azul = $00FFFFBB; implementation {$R *.dfm} procedure Tusuarios.btAborrarClick(Sender: TObject); begin qusuarios.Delete; end; procedure Tusuarios.btAcancelarClick(Sender: TObject); begin qusuarios.Cancel; end; procedure Tusuarios.btAguardarClick(Sender: TObject); begin qusuarios.Post; end; procedure Tusuarios.btAmodificarClick(Sender: TObject); begin qusuarios.Edit; end; procedure Tusuarios.btAnuevoClick(Sender: TObject); begin dbgrid1.SetFocus; qusuarios.Append; end; procedure Tusuarios.DBGrid1CellClick(Column: TColumn); begin if column.Field.FieldName ='fumigador' then begin if qusuariosfumigador.asinteger=1 then begin qusuarios.Edit; qusuariosfumigador.Value:=0; qusuarios.Post; end else begin qusuarios.Edit; qusuariosfumigador.Value:=1; qusuarios.Post; qusuarios.Refresh; dbgrid1.SelectedIndex:=1; end; end; if column.Field.FieldName ='tecnico' then begin if qusuariostecnico.asinteger=1 then begin qusuarios.Edit; qusuariostecnico.Value:=0; qusuarios.Post; end else begin qusuarios.Edit; qusuariostecnico.Value:=1; qusuarios.Post; qusuarios.Refresh; dbgrid1.SelectedIndex:=1; end; end; if column.Field.FieldName ='active' then begin if qusuariosactive.asinteger=1 then begin qusuarios.Edit; qusuariosactive.Value:=0; qusuarios.Post; end else begin qusuarios.Edit; qusuariosactive.Value:=1; qusuarios.Post; qusuarios.Refresh; dbgrid1.SelectedIndex:=1; end; end; if column.Field.FieldName ='gestorindividual' then begin if qusuariosgestorindividual.asinteger=1 then begin qusuarios.Edit; qusuariosgestorindividual.Value:=0; qusuarios.Post; end else begin qusuarios.Edit; qusuariosgestorindividual.Value:=1; qusuarios.Post; qusuarios.Refresh; dbgrid1.SelectedIndex:=1; end; end; if column.Field.FieldName ='gestorgrupo' then begin if qusuariosgestorgrupo.asinteger=1 then begin qusuarios.Edit; qusuariosgestorgrupo.Value:=0; qusuarios.Post; end else begin qusuarios.Edit; qusuariosgestorgrupo.Value:=1; qusuarios.Post; qusuarios.Refresh; dbgrid1.SelectedIndex:=1; end; end; if column.Field.FieldName ='administrador' then begin if qusuariosadministrador.asinteger=1 then begin qusuarios.Edit; qusuariosadministrador.Value:=0; qusuarios.Post; end else begin qusuarios.Edit; qusuariosadministrador.Value:=1; qusuarios.Post; qusuarios.Refresh; dbgrid1.SelectedIndex:=1; end; end; dbgrid1.SelectedIndex:=1; end; procedure Tusuarios.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); const IsChecked : array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED); var DrawState,imgindex,bmpwidth: Integer; DrawRect: TRect; begin if (qusuariosactive.Asinteger=0)then begin DBGrid1.Canvas.brush.Color := rojo; end else DBGrid1.Canvas.brush.Color := verde; DBgrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State); if (gdFocused in State) then begin if (Column.Field.FieldName = 'fumigador') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'fumigador') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; DBgrid1.Canvas.FillRect(Rect); DrawFrameControl(DBgrid1.Canvas.Handle, DrawRect,DFC_BUTTON, DrawState); end; end; if (gdFocused in State) then begin if (Column.Field.FieldName = 'tecnico') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'tecnico') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; DBgrid1.Canvas.FillRect(Rect); DrawFrameControl(DBgrid1.Canvas.Handle, DrawRect,DFC_BUTTON, DrawState); end; end; if (gdFocused in State) then begin if (Column.Field.FieldName = 'active') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'active') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; DBgrid1.Canvas.FillRect(Rect); DrawFrameControl(DBgrid1.Canvas.Handle, DrawRect,DFC_BUTTON, DrawState); end; end; if (gdFocused in State) then begin if (Column.Field.FieldName = 'gestorindividual') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'gestorindividual') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; DBgrid1.Canvas.FillRect(Rect); DrawFrameControl(DBgrid1.Canvas.Handle, DrawRect,DFC_BUTTON, DrawState); end; end; if (gdFocused in State) then begin if (Column.Field.FieldName = 'gestorgrupo') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'gestorgrupo') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; DBgrid1.Canvas.FillRect(Rect); DrawFrameControl(DBgrid1.Canvas.Handle, DrawRect,DFC_BUTTON, DrawState); end; end; if (gdFocused in State) then begin if (Column.Field.FieldName = 'administrador') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'administrador') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; DBgrid1.Canvas.FillRect(Rect); DrawFrameControl(DBgrid1.Canvas.Handle, DrawRect,DFC_BUTTON, DrawState); end; end; gcrpagado.visible:=false; if (gdFocused in State) then begin if (Column.Field.FieldName = combogrupos.DataField) then with combogrupos do begin Left := Rect.Left + DBgrid1.Left + 2; Top := Rect.Top + DBgrid1.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else combogrupos.Visible:=false; if (Column.Field.FieldName = combotrabajadores.DataField) then with combotrabajadores do begin Left := Rect.Left + DBgrid1.Left + 2; Top := Rect.Top + DBgrid1.Top + 2; Width := Rect.Right - Rect.Left; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; setfocus; dropdown; end else combotrabajadores.Visible:=false; end; end; procedure Tusuarios.FormKeyPress(Sender: TObject; var Key: Char); begin key:=upcase(key); if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; // si presionamos ESC if (key=#$1B) and (activecontrol is tdblookupcombobox )then begin activecontrol.Visible:=false; end; end; procedure Tusuarios.FormShow(Sender: TObject); begin qtrabajadores.Open; qgrupos.Open; qusuarios.Open; end; procedure Tusuarios.qusuariosAfterInsert(DataSet: TDataSet); begin qmaxusuario.Close; qmaxusuario.Open; qusuariosid.Value:=qmaxusuarioid.AsInteger; end; procedure Tusuarios.qusuariosBeforePost(DataSet: TDataSet); begin qusuariosgrupo.Value:=qgruposid.AsInteger; qusuariosidemp.Value:=qtrabajadoresid.AsInteger; qusuariosnif.Value:=qtrabajadoresnif.AsString; qusuariosnombre.Value:=qtrabajadoresnombre.AsString; end; end. ======================================== FICHERO: futensilios.pas ======================================== unit futensilios; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids; type Tutensilios = class(TForm) DBGrid1: TDBGrid; dsqutensilios: TDataSource; Panel1: TPanel; btnuevo: TButton; btmodificar: TButton; btborrar: TButton; btguardar: TButton; btcancelar: TButton; qutensilios: TZQuery; qutensilioside: TIntegerField; qutensiliosid: TIntegerField; qutensiliosidentificador: TWideStringField; qutensiliosdescripcion: TWideStringField; qid: TZReadOnlyQuery; qidid: TLargeintField; qutensiliosidtrabajador: TIntegerField; qutensiliosempleado: TStringField; qempleado: TZReadOnlyQuery; qempleadonombre: TWideStringField; procedure dsqutensiliosStateChange(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure qutensiliosBeforePost(DataSet: TDataSet); procedure qutensiliosBeforeDelete(DataSet: TDataSet); procedure FormShow(Sender: TObject); procedure btnuevoClick(Sender: TObject); procedure btmodificarClick(Sender: TObject); procedure btborrarClick(Sender: TObject); procedure btguardarClick(Sender: TObject); procedure btcancelarClick(Sender: TObject); procedure qutensiliosAfterInsert(DataSet: TDataSet); procedure qutensiliosAfterPost(DataSet: TDataSet); procedure qutensiliosCalcFields(DataSet: TDataSet); private { Private declarations } public { Public declarations } end; var utensilios: Tutensilios; implementation {$R *.dfm} uses datos; procedure Tutensilios.btborrarClick(Sender: TObject); begin qutensilios.Delete; end; procedure Tutensilios.btcancelarClick(Sender: TObject); begin qutensilios.Cancel; end; procedure Tutensilios.btguardarClick(Sender: TObject); begin qutensilios.Post; end; procedure Tutensilios.btmodificarClick(Sender: TObject); begin qutensilios.Edit; end; procedure Tutensilios.btnuevoClick(Sender: TObject); begin qutensilios.Append; end; procedure Tutensilios.dsqutensiliosStateChange(Sender: TObject); begin if qutensilios.State in [dsedit,dsinsert] then begin btnuevo.Enabled:=false; btmodificar.Enabled:=false; btborrar.Enabled:=false; btcancelar.Enabled:=true; btguardar.Enabled:=true; end else begin btnuevo.Enabled:=true; btmodificar.Enabled:=true; btborrar.Enabled:=true; btcancelar.Enabled:=false; btguardar.Enabled:=false; end; end; procedure Tutensilios.FormKeyPress(Sender: TObject; var Key: Char); begin key:=upcase(key); if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tutensilios.FormShow(Sender: TObject); begin qempleado.Open; qutensilios.Open; dm.tempresa.Open; end; procedure Tutensilios.qutensiliosAfterInsert(DataSet: TDataSet); begin qid.close; qid.ParamByName('EMPRESA').AsInteger:=dm.tempresaid.AsInteger; qid.open; if qidid.asstring='' then qutensiliosid.value:=1 else qutensiliosid.Value:=qidid.asinteger; end; procedure Tutensilios.qutensiliosAfterPost(DataSet: TDataSet); begin qutensilios.Cancel; qutensilios.Refresh; end; procedure Tutensilios.qutensiliosBeforeDelete(DataSet: TDataSet); begin case dm.PedirConfirmacion('¿Confirma que desea borrar este utensilio?',true,true,false) of mrno:Abort; end; end; procedure Tutensilios.qutensiliosBeforePost(DataSet: TDataSet); var x:integer; begin if qutensilios.State in [dsinsert] then qutensilioside.Value:=dm.tempresaid.AsInteger; if qutensilios.state=dsinsert then x:=dm.PedirConfirmacion('¿Confirma que desea dar de alta este utensilio?',true,true,true) else x:=dm.PedirConfirmacion('¿Confirma que desea modificar este utensilio?',true,true,true); case x of mrno: begin qutensilios.cancel; abort; end; mrcancel:BEGIN abort; END; end; end; procedure Tutensilios.qutensiliosCalcFields(DataSet: TDataSet); begin if qutensiliosidtrabajador.AsString<>'' then begin qempleado.Prepare; qempleado.ParamByName('EMPRESA').AsInteger:=qutensilioside.AsInteger; qempleado.ParamByName('ID').AsInteger:=qutensiliosidtrabajador.AsInteger; qempleado.Refresh; qutensiliosempleado.Value:=qempleadonombre.asstring; end; end; end. ======================================== FICHERO: fvehiculos.pas ======================================== unit fvehiculos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.DBCtrls, Data.DB, ZDataset, ZAbstractRODataset, ZAbstractDataset, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, shellapi, Vcl.Mask, Vcl.ComCtrls, frxClass, frxDBSet, URLMon, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP; type Tvehiculos = class(TForm) Panel7: TPanel; btAmodificar: TButton; btAborrar: TButton; btAnuevo: TButton; btAguardar: TButton; btAcancelar: TButton; DBGrid1: TDBGrid; qmaquinaria: TZQuery; dsqmaquinaria: TDataSource; ZReadOnlyQuery1: TZReadOnlyQuery; qmaquinariaID: TWideStringField; qmaquinariaFECHA_COMPRA: TDateField; qmaquinariaPROPIO: TIntegerField; qmaquinariavehiculo: TIntegerField; qmaquinariamaquinaria: TIntegerField; qmaquinariaACTIVO: TIntegerField; qmaquinariatractor: TIntegerField; qmaquinariafumigadora: TIntegerField; qmaquinariaDESCRIPCION: TWideStringField; qmaquinariaIDEMPRESA: TIntegerField; qmaquinariaTIPO: TWideStringField; gcrpagado: TDBCheckBox; procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBGrid1CellClick(Column: TColumn); procedure FormShow(Sender: TObject); procedure btAnuevoClick(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure btAmodificarClick(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); procedure qmaquinariaBeforePost(DataSet: TDataSet); private { Private declarations } public { Public declarations } end; var vehiculos: Tvehiculos; implementation {$R *.dfm} uses datos, principal; procedure Tvehiculos.btAborrarClick(Sender: TObject); begin qmaquinaria.Delete; end; procedure Tvehiculos.btAcancelarClick(Sender: TObject); begin qmaquinaria.Cancel; end; procedure Tvehiculos.btAguardarClick(Sender: TObject); begin qmaquinaria.Post; end; procedure Tvehiculos.btAmodificarClick(Sender: TObject); begin qmaquinaria.Edit; end; procedure Tvehiculos.btAnuevoClick(Sender: TObject); begin qmaquinaria.append; end; procedure Tvehiculos.DBGrid1CellClick(Column: TColumn); begin if column.Field.FieldName ='propio' then begin if qmaquinariapropio.asinteger=1 then begin qmaquinaria.Edit; qmaquinariapropio.Value:=0; qmaquinaria.Post; dbgrid1.selectedIndex:=1; end else begin qmaquinaria.Edit; qmaquinariapropio.Value:=1; qmaquinaria.Post; qmaquinaria.Refresh; dbgrid1.SelectedIndex:=1; end; end; if column.Field.FieldName ='fumigadora' then begin if qmaquinariafumigadora.asinteger=1 then begin qmaquinaria.Edit; qmaquinariafumigadora.Value:=0; qmaquinaria.Post; dbgrid1.selectedIndex:=1; end else begin qmaquinaria.Edit; qmaquinariafumigadora.Value:=1; qmaquinaria.Post; qmaquinaria.Refresh; dbgrid1.SelectedIndex:=1; end; end; if column.Field.FieldName ='tractor' then begin if qmaquinariatractor.asinteger=1 then begin qmaquinaria.Edit; qmaquinariatractor.Value:=0; qmaquinaria.Post; dbgrid1.selectedIndex:=1; end else begin qmaquinaria.Edit; qmaquinariatractor.Value:=1; qmaquinaria.Post; qmaquinaria.Refresh; dbgrid1.SelectedIndex:=1; end; end; if column.Field.FieldName ='activo' then begin if qmaquinariaactivo.asinteger=1 then begin qmaquinaria.Edit; qmaquinariaactivo.Value:=0; qmaquinaria.Post; dbgrid1.selectedIndex:=1; end else begin qmaquinaria.Edit; qmaquinariaactivo.Value:=1; qmaquinaria.Post; qmaquinaria.Refresh; dbgrid1.SelectedIndex:=1; end; end; if column.Field.FieldName ='maquinaria' then begin if qmaquinariamaquinaria.asinteger=1 then begin qmaquinaria.Edit; qmaquinariamaquinaria.Value:=0; qmaquinaria.Post; dbgrid1.selectedIndex:=1; end else begin qmaquinaria.Edit; qmaquinariamaquinaria.Value:=1; qmaquinaria.Post; qmaquinaria.Refresh; dbgrid1.SelectedIndex:=1; end; end; if column.Field.FieldName ='vehiculo' then begin if qmaquinariavehiculo.asinteger=1 then begin qmaquinaria.Edit; qmaquinariavehiculo.Value:=0; qmaquinaria.Post; dbgrid1.selectedIndex:=1; end else begin qmaquinaria.Edit; qmaquinariavehiculo.Value:=1; qmaquinaria.Post; qmaquinaria.Refresh; dbgrid1.SelectedIndex:=1; end; end; end; procedure Tvehiculos.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); const IsChecked : array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED); var DrawState,imgindex,bmpwidth: Integer; DrawRect: TRect; begin if (gdFocused in State) then begin if (Column.Field.FieldName = 'ACTIVO') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'ACTIVO') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; DBgrid1.Canvas.FillRect(Rect); DrawFrameControl(DBgrid1.Canvas.Handle, DrawRect,DFC_BUTTON, DrawState); end; end; if (gdFocused in State) then begin if (Column.Field.FieldName = 'vehiculo') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'vehiculo') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; DBgrid1.Canvas.FillRect(Rect); DrawFrameControl(DBgrid1.Canvas.Handle, DrawRect,DFC_BUTTON, DrawState); end; end; if (gdFocused in State) then begin if (Column.Field.FieldName = 'PROPIO') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'PROPIO') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; DBgrid1.Canvas.FillRect(Rect); DrawFrameControl(DBgrid1.Canvas.Handle, DrawRect,DFC_BUTTON, DrawState); end; end; if (gdFocused in State) then begin if (Column.Field.FieldName = 'maquinaria') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'maquinaria') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; DBgrid1.Canvas.FillRect(Rect); DrawFrameControl(DBgrid1.Canvas.Handle, DrawRect,DFC_BUTTON, DrawState); end; end; if (gdFocused in State) then begin if (Column.Field.FieldName = 'tractor') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'tractor') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; DBgrid1.Canvas.FillRect(Rect); DrawFrameControl(DBgrid1.Canvas.Handle, DrawRect,DFC_BUTTON, DrawState); end; end; if (gdFocused in State) then begin if (Column.Field.FieldName = 'fumigadora') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'fumigadora') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; DBgrid1.Canvas.FillRect(Rect); DrawFrameControl(DBgrid1.Canvas.Handle, DrawRect,DFC_BUTTON, DrawState); end; end; gcrpagado.visible:=false; end; procedure Tvehiculos.FormShow(Sender: TObject); begin qmaquinaria.Open; end; procedure Tvehiculos.qmaquinariaBeforePost(DataSet: TDataSet); begin qmaquinariaidempresa.Value:=1; end; end. ======================================== FICHERO: gastosconsumos.pas ======================================== unit gastosconsumos; 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.Grids, Vcl.DBGrids, Data.DB, ZAbstractRODataset, ZDataset, Vcl.ComCtrls, ZAbstractDataset, Vcl.Mask, Vcl.DBCtrls; type Tfconsumosgastos = class(TForm) Panel4: TPanel; Label36: TLabel; btAcancelar: TButton; btAmodificar: TButton; btAborrar: TButton; btAnuevo: TButton; btAguardar: TButton; Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; Panel7: TPanel; Panel6: TPanel; Panel8: TPanel; Label3: TLabel; Label4: TLabel; Edit2: TEdit; DBGrid2: TDBGrid; Panel9: TPanel; Panel10: TPanel; Label5: TLabel; Label6: TLabel; Edit3: TEdit; DBGrid3: TDBGrid; tfecha: TDateTimePicker; Label1: TLabel; qcentrocoste: TZReadOnlyQuery; dsqcentrocoste: TDataSource; qcentrocostecodpar: TWideStringField; qcentrocosteempresa: TIntegerField; qcentrocostenombre: TWideStringField; dsqarticulos: TDataSource; qarticulos: TZReadOnlyQuery; qarticulosidempresa: TIntegerField; qarticulosid: TIntegerField; qarticuloscodigo: TWideStringField; qarticulosdescripcion: TWideStringField; DBGrid1: TDBGrid; consumosgastos: TZQuery; consumosgastosid: TIntegerField; consumosgastoside: TIntegerField; consumosgastosida: TIntegerField; consumosgastosfecha: TDateField; consumosgastoscantidad: TFloatField; consumosgastosobservaciones: TWideStringField; consumosgastosdescripcion: TWideStringField; qconsumosgastos: TZReadOnlyQuery; dsqconsumosgastos: TDataSource; qconsumosgastosid: TIntegerField; qconsumosgastoside: TIntegerField; qconsumosgastosida: TIntegerField; qconsumosgastosfecha: TDateField; qconsumosgastoscantidad: TFloatField; qconsumosgastosobservaciones: TWideStringField; qconsumosgastosdescripcion: TWideStringField; qconsumosgastosnombre: TWideStringField; qconsumosgastoscodigo: TWideStringField; DBEdit1: TDBEdit; dsconsumosgastos: TDataSource; DBText1: TDBText; qconsumosgastosidcc: TWideStringField; consumosgastosidcc: TWideStringField; DBEdit2: TDBEdit; DataSource1: TDataSource; qcentrocoste2: TZReadOnlyQuery; Label2: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; Label10: TLabel; DBEdit3: TDBEdit; DBEdit4: TDBEdit; DBMemo1: TDBMemo; qcentrocoste2empresa: TIntegerField; qcentrocoste2codpar: TWideStringField; qcentrocoste2nombre: TWideStringField; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure dsconsumosgastosStateChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure btAnuevoClick(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure btAmodificarClick(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure dsqcentrocosteDataChange(Sender: TObject; Field: TField); procedure btAcancelarClick(Sender: TObject); procedure dsqarticulosDataChange(Sender: TObject; Field: TField); procedure dsqconsumosgastosDataChange(Sender: TObject; Field: TField); procedure consumosgastosBeforeOpen(DataSet: TDataSet); private { Private declarations } public { Public declarations } end; var fconsumosgastos: Tfconsumosgastos; implementation {$R *.dfm} procedure Tfconsumosgastos.btAborrarClick(Sender: TObject); begin consumosgastos.Delete; qconsumosgastos.Refresh; end; procedure Tfconsumosgastos.btAcancelarClick(Sender: TObject); begin consumosgastos.Cancel; end; procedure Tfconsumosgastos.btAguardarClick(Sender: TObject); var id,ide:string; begin consumosgastos.post; id:=consumosgastosid.asstring; ide:=consumosgastoside.asstring; qconsumosgastos.Refresh; qconsumosgastos.Locate('ide,id',vararrayof([ide,id]),[locaseinsensitive]); consumosgastos.SQL.Clear; consumosgastos.SQL.Add('select * from consumosgastos where ide='+ide+' and id='+ide); consumosgastos.Open; end; procedure Tfconsumosgastos.btAmodificarClick(Sender: TObject); begin consumosgastos.Edit; end; procedure Tfconsumosgastos.btAnuevoClick(Sender: TObject); begin if consumosgastos.Active=false then consumosgastos.open; consumosgastos.Append; consumosgastosfecha.Value:=tfecha.Date; consumosgastoside.Value:=qcentrocosteempresa.asinteger; consumosgastosidcc.Value:=qcentrocostecodpar.AsString; consumosgastosida.Value:=qarticulosid.AsInteger; consumosgastosdescripcion.Value:=qarticulosdescripcion.AsString; end; procedure Tfconsumosgastos.consumosgastosBeforeOpen(DataSet: TDataSet); var ide,id:string; begin if qconsumosgastos.Active=true then begin ide:=qconsumosgastoside.asstring; id:=qconsumosgastosid.asstring; consumosgastos.SQL.Clear; consumosgastos.SQL.Add('select * from consumosgastos where ide='+ide+' and id='+ide); tfecha.date:=consumosgastosfecha.AsDateTime; end; end; procedure Tfconsumosgastos.dsconsumosgastosStateChange(Sender: TObject); begin if consumosgastos.State in [dsedit,dsinsert] then begin btanuevo.Enabled:=false; btamodificar.Enabled:=false; btaborrar.Enabled:=false; btacancelar.Enabled:=true; btaguardar.Enabled:=true; panel1.Enabled:=true; // btfanterior.Enabled:=false; // btfsiguiente.Enabled:=false; // btfimportar.Enabled:=false; // btfimprimir.Enabled:=false; end else begin btanuevo.Enabled:=true; btamodificar.Enabled:=true; btaborrar.Enabled:=true; btacancelar.Enabled:=false; btaguardar.Enabled:=false; panel1.Enabled:=false; // btfanterior.Enabled:=true; // btfsiguiente.Enabled:=true; // btfimportar.Enabled:=true; // btfimprimir.Enabled:=true; end; end; procedure Tfconsumosgastos.dsqarticulosDataChange(Sender: TObject; Field: TField); begin if consumosgastos.State in [dsedit,dsinsert] then begin consumosgastosida.Value:=qarticulosid.AsInteger; consumosgastosdescripcion.Value:=qarticulosdescripcion.AsString; end; end; procedure Tfconsumosgastos.dsqcentrocosteDataChange(Sender: TObject; Field: TField); var ide,id:string; begin if (qconsumosgastos.Active=true) then begin if (qconsumosgastos.RecordCount>0) then begin ide:=qconsumosgastoside.asstring; id:=qconsumosgastosid.asstring; consumosgastos.SQL.Clear; consumosgastos.SQL.Add('select * from consumosgastos where ide='+ide+' and id='+ide); consumosgastos.Open; tfecha.date:=consumosgastosfecha.AsDateTime; end; end; if consumosgastos.State in [dsedit,dsinsert] then begin consumosgastoside.Value:=qcentrocosteempresa.asinteger; consumosgastosidcc.Value:=qcentrocostecodpar.AsString; end; end; procedure Tfconsumosgastos.dsqconsumosgastosDataChange(Sender: TObject; Field: TField); var ide,id:string; begin if (qconsumosgastos.RecordCount>0) then begin ide:=qconsumosgastoside.asstring; id:=qconsumosgastosid.asstring; consumosgastos.close; consumosgastos.Open; end; end; procedure Tfconsumosgastos.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tfconsumosgastos.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is tdbgrid) then begin key:=','; end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tfconsumosgastos.FormShow(Sender: TObject); begin qcentrocoste.Close; qcentrocoste2.Close; qarticulos.Close; qconsumosgastos.Close; consumosgastos.Close; qconsumosgastos.open; qcentrocoste.open; qcentrocoste2.open; qarticulos.open; tfecha.date:=date(); end; end. ======================================== FICHERO: gruposfamilias.pas ======================================== unit gruposfamilias; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,Vcl.StdCtrls, Vcl.DBCtrls, Vcl.Mask, Vcl.ComCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, datos, ZAbstractDataset, ZDataset, Data.DB, ZAbstractRODataset, ZAbstractTable,Excel2000, ComObj; type Tfgruposfamilias = class(TForm) Panel13: TPanel; Panel17: TPanel; DBGrid3: TDBGrid; Panel7: TPanel; btGcancelar: TButton; btGmodificar: TButton; btGborrar: TButton; btGnuevo: TButton; btGguardar: TButton; Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; Panel4: TPanel; Panel5: TPanel; DBGrid1: TDBGrid; Panel6: TPanel; btfcancelar: TButton; btFmodificar: TButton; btFborrar: TButton; btFnuevo: TButton; btFguardar: TButton; Panel8: TPanel; Panel9: TPanel; Label1: TLabel; Label2: TLabel; DBGrid2: TDBGrid; dsgrupos: TDataSource; qgrupos: TZQuery; qgruposidempresa: TIntegerField; qgruposid: TIntegerField; qgruposdescripcion: TWideStringField; qgruposactivo: TIntegerField; qfamilias: TZQuery; dsfamilias: TDataSource; qarticulos: TZQuery; dsarticulos: TDataSource; qfamiliasid: TIntegerField; qfamiliasdescripcion: TWideStringField; qfamiliasactivo: TIntegerField; qfamiliasCOMUN: TIntegerField; qfamiliasABONOS: TIntegerField; qfamiliasFITOSANITARIOS: TIntegerField; qfamiliasSUMINISTROS: TIntegerField; qfamiliasGENERADORES: TIntegerField; qarticulosid: TIntegerField; qarticuloscodigo: TWideStringField; qarticulosdescripcion: TWideStringField; qarticulospreciocoste: TFloatField; qarticulosstock: TFloatField; qarticulosult_preciocompra: TFloatField; qarticulosactivo: TIntegerField; qarticulosnombre_corto: TWideStringField; qfamiliasidempresa: TIntegerField; qfamiliasgrupo: TIntegerField; qarticulosidempresa: TIntegerField; qarticulosfamilia: TIntegerField; gcrpagado: TDBCheckBox; qaux: TZReadOnlyQuery; btJexcel: TButton; btJimprimir: TButton; SaveDialog1: TSaveDialog; procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormShow(Sender: TObject); procedure dsgruposStateChange(Sender: TObject); procedure dsfamiliasStateChange(Sender: TObject); procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure FormCreate(Sender: TObject); procedure DBGrid1CellClick(Column: TColumn); procedure DBGrid3DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBGrid3CellClick(Column: TColumn); procedure DBGrid2DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure btGnuevoClick(Sender: TObject); procedure btGguardarClick(Sender: TObject); procedure btGcancelarClick(Sender: TObject); procedure btGmodificarClick(Sender: TObject); procedure btGborrarClick(Sender: TObject); procedure btFborrarClick(Sender: TObject); procedure btFmodificarClick(Sender: TObject); procedure btFguardarClick(Sender: TObject); procedure btfcancelarClick(Sender: TObject); procedure btFnuevoClick(Sender: TObject); procedure btJexcelClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure AppMessage(var Msg: Tmsg; var Handled:Boolean); procedure ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar = nil); end; var fgruposfamilias: Tfgruposfamilias; implementation {$R *.dfm} procedure Tfgruposfamilias.AppMessage(var Msg: TMSg; Var Handled:Boolean); var actual : TWincontrol; begin if Msg.message = WM_KEYDOWN then begin // esto es para controlar que con la flecha abajo se desplegen las // listas if Msg.wParam = VK_DOWN then begin Actual := Screen.ActiveControl; if Actual is TDBLookupComboBox then if not TDBLookupComboBox(Screen.ActiveForm.ActiveControl).listVisible then TDBLookupComboBox(Screen.ActiveForm.ActiveControl).DropDown; // si utilizas las RX { if Actual is TRxDBLookupCombo then if not TRxDBLookupCombo(Screen.ActiveForm.ActiveControl).listVisible then TRxDBLookupCombo(Screen.ActiveForm.ActiveControl).DropDown; } if Actual is TComboBox then SendMessage(TComboBox(Screen.ActiveForm.ActiveControl).Handle,CB_SHOWDROPDOWN,-1,0); if (Actual is TCustomEdit) then Msg.wParam := VK_TAB; // se pueden añadir mas controles.... end; // y aqui es el control del intro. if Msg.wParam = VK_RETURN THEN begin Actual := Screen.ActiveControl; // para los edit. if (Actual is TCustomEdit) and not (Actual is TCustomMemo) then Msg.wParam := VK_TAB; // para los memo. Con ctrl + enter se salta de linea dentro del // memo, si solo es intro salta al siguiente control if (Actual is TCustomMemo) and (HiWord(GetKeyState(VK_CONTROL)) = 0)then Msg.wParam := VK_TAB; // para los lookup if Actual is TDBLookupComboBox then if not TDBLookupComboBox(Actual).listVisible then Msg.wParam := VK_TAB; // Si utilizas las RX { if Actual is TRxDBLookupCombo then if not TRxDBLookupCombo(Actual).listVisible then Msg.wParam := VK_TAB; } // Los combobox if Actual is TCustomComboBox then if not TCustomComboBox(Actual).DroppedDown then Msg.wParam := VK_TAB; // el radiobutton if Actual is TRadioButton then Msg.wParam := VK_TAB; // en el grid if Actual is TDBGrid then if (TDBGrid(Actual).ReadOnly) or (HiWord(GetKeyState(VK_CONTROL)) = 1)then Msg.wParam := VK_TAB; // o esto otro Con Ctrl + intro siguiente celda con // ctrl + shift + intro celda anterior // es complicado pero es por no liar con el intro solo // que siempre pasa de un control a otro. if Actual is TDBGrid then begin if (TDBGrid(Actual).ReadOnly) or (HiWord(GetKeyState(VK_CONTROL)) = 0) then Msg.wParam := VK_TAB else if not(HiWord(GetKeyState(VK_SHIFT)) = 0) then begin if TDBGrid(Actual).selectedindex > 0 then { increment the field } TDBGrid(Actual).selectedindex := TDBGrid(Actual).selectedindex -1 else TDBGrid(Actual).selectedindex := TDBGrid(Actual).fieldcount -1; end else begin if TDBGrid(Actual).selectedindex < (TDBGrid(Actual).fieldcount -1) then { increment the field } TDBGrid(Actual).selectedindex := TDBGrid(Actual).selectedindex +1 else TDBGrid(Actual).selectedindex := 0; end; end; // ListBox if Actual is TCustomListBox then Msg.wParam := VK_TAB; // TabControl if Actual is TCustomTabControl then Msg.wParam := VK_TAB; // Aqui se pondrían todos los controles que usamos en la // aplicación y necesitamos cambiar el tab por intro. // de esta forma te despreocupas de cuantos añades y es más // limpio el código end; end; end; procedure Tfgruposfamilias.btFborrarClick(Sender: TObject); begin qfamilias.delete; end; procedure Tfgruposfamilias.btfcancelarClick(Sender: TObject); begin qfamilias.Cancel; dbgrid1.ReadOnly:=true; end; procedure Tfgruposfamilias.btFguardarClick(Sender: TObject); begin qfamilias.Post; dbgrid1.ReadOnly:=true; end; procedure Tfgruposfamilias.btFmodificarClick(Sender: TObject); begin dbgrid1.ReadOnly:=false; qfamilias.edit; end; procedure Tfgruposfamilias.btFnuevoClick(Sender: TObject); begin dbgrid1.ReadOnly:=false; qaux.sql.clear; qaux.SQL.Add('select max(id)+1 from familias'); qaux.Open; qfamilias.append; dbgrid1.setfocus; qfamiliasid.Value:=qaux.Fields[0].AsInteger; end; procedure Tfgruposfamilias.btGborrarClick(Sender: TObject); begin qgrupos.delete; end; procedure Tfgruposfamilias.btGcancelarClick(Sender: TObject); begin qgrupos.Cancel; dbgrid3.ReadOnly:=true; end; procedure Tfgruposfamilias.btGguardarClick(Sender: TObject); begin qgrupos.post; dbgrid3.ReadOnly:=true; end; procedure Tfgruposfamilias.btGmodificarClick(Sender: TObject); begin dbgrid3.ReadOnly:=false; qgrupos.edit; end; procedure Tfgruposfamilias.btGnuevoClick(Sender: TObject); begin dbgrid3.ReadOnly:=false; qaux.sql.clear; qaux.SQL.Add('select max(id)+1 from grupos'); qaux.Open; qgrupos.append; dbgrid3.setfocus; qgruposid.Value:=qaux.Fields[0].AsInteger; end; procedure Tfgruposfamilias.btJexcelClick(Sender: TObject); var archivo:string; begin savedialog1.FileName:='ARTICULOS.xls'; savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'ARTICULOS',DBGRID2); finally showmessage('Los datos han sido exportados correctamente a '+archivo); end; end; procedure Tfgruposfamilias.DBGrid1CellClick(Column: TColumn); begin if column.Field.FieldName ='COMUN' then begin if qfamiliascomun.asinteger=1 then begin qfamilias.Edit; qfamiliasCOMUN.Value:=0; qfamilias.Post; dbgrid1.selectedIndex:=1; end else begin qfamilias.Edit; qfamiliasCOMUN.Value:=1; qfamilias.Post; qfamilias.Refresh; dbgrid1.SelectedIndex:=1; end; end; if column.Field.FieldName ='ABONOS' then begin if qfamiliasABONOS.asinteger=1 then begin qfamilias.Edit; qfamiliasABONOS.Value:=0; qfamilias.Post; dbgrid1.selectedIndex:=1; end else begin qfamilias.Edit; qfamiliasABONOS.Value:=1; qfamilias.Post; qfamilias.Refresh; dbgrid1.SelectedIndex:=1; end; end; if column.Field.FieldName ='FITOSANITARIOS' then begin if qfamiliasFITOSANITARIOS.asinteger=1 then begin qfamilias.Edit; qfamiliasFITOSANITARIOS.Value:=0; qfamilias.Post; dbgrid1.selectedIndex:=1; end else begin qfamilias.Edit; qfamiliasFITOSANITARIOS.Value:=1; qfamilias.Post; qfamilias.Refresh; dbgrid1.SelectedIndex:=1; end; end; if column.Field.FieldName ='SUMINISTROS' then begin if qfamiliasSUMINISTROS.asinteger=1 then begin qfamilias.Edit; qfamiliasSUMINISTROS.Value:=0; qfamilias.Post; dbgrid1.selectedIndex:=1; end else begin qfamilias.Edit; qfamiliasSUMINISTROS.Value:=1; qfamilias.Post; qfamilias.Refresh; dbgrid1.SelectedIndex:=1; end; end; if column.Field.FieldName ='GENERADORES' then begin if qfamiliasGENERADORES.asinteger=1 then begin qfamilias.Edit; qfamiliasGENERADORES.Value:=0; qfamilias.Post; dbgrid1.selectedIndex:=1; end else begin qfamilias.Edit; qfamiliasGENERADORES.Value:=1; qfamilias.Post; qfamilias.Refresh; dbgrid1.SelectedIndex:=1; end; end; {if column.Field.FieldName ='comisiones' then begin if qfamiliascomisiones.asinteger=1 then begin qfamilias.Edit; //qfamiliascomisiones.Value:=0; qfamilias.Post; dbgrid1.selectedIndex:=1; end else begin qfamilias.Edit; //qfamiliascomisiones.Value:=1; qfamilias.Post; qfamilias.Refresh; dbgrid1.SelectedIndex:=1; end; end; if column.Field.FieldName ='transporte' then begin if qfamiliastransporte.asinteger=1 then begin qfamilias.Edit; qfamiliastransporte.Value:=0; qfamilias.Post; dbgrid1.selectedIndex:=1; end else begin qfamilias.Edit; qfamiliastransporte.Value:=1; qfamilias.Post; qfamilias.Refresh; dbgrid1.SelectedIndex:=1; end; end; if column.Field.FieldName ='otrosgastos' then begin if qfamiliasotrosgastos.asinteger=1 then begin qfamilias.Edit; qfamiliasotrosgastos.Value:=0; qfamilias.Post; dbgrid1.selectedIndex:=1; end else begin qfamilias.Edit; qfamiliasotrosgastos.Value:=1; qfamilias.Post; qfamilias.Refresh; dbgrid1.SelectedIndex:=1; end; end; } if column.Field.FieldName ='activo' then begin if qfamiliasactivo.asinteger=1 then begin qfamilias.Edit; qfamiliasactivo.Value:=0; qfamilias.Post; dbgrid1.selectedIndex:=1; end else begin qfamilias.Edit; qfamiliasactivo.Value:=1; qfamilias.Post; qfamilias.Refresh; dbgrid1.SelectedIndex:=1; end; end; end; procedure Tfgruposfamilias.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); const IsChecked : array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED); var DrawState: Integer; DrawRect: TRect; begin if (gdFocused in State) then begin if (Column.Field.FieldName = 'COMUN') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; if (Column.Field.FieldName = 'ABONOS') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; if (Column.Field.FieldName = 'FITOSANITARIOS') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; if (Column.Field.FieldName = 'SUMINISTROS') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; if (Column.Field.FieldName = 'GENERADORES') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; if (Column.Field.FieldName = 'comisiones') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; if (Column.Field.FieldName = 'transporte') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; if (Column.Field.FieldName = 'otrosgastos') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; if (Column.Field.FieldName = 'activo') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'COMUN') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; // DrawState := ISChecked[Column.Field.Asboolean]; DBgrid1.Canvas.FillRect(Rect); DrawFrameControl(DBgrid1.Canvas.Handle, DrawRect, DFC_BUTTON, DrawState); end; if (Column.Field.FieldName = 'ABONOS') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; // DrawState := ISChecked[Column.Field.Asboolean]; DBgrid1.Canvas.FillRect(Rect); DrawFrameControl(DBgrid1.Canvas.Handle, DrawRect, DFC_BUTTON, DrawState); end; if (Column.Field.FieldName = 'FITOSANITARIOS') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; // DrawState := ISChecked[Column.Field.Asboolean]; DBgrid1.Canvas.FillRect(Rect); DrawFrameControl(DBgrid1.Canvas.Handle, DrawRect, DFC_BUTTON, DrawState); end; if (Column.Field.FieldName = 'SUMINISTROS') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; // DrawState := ISChecked[Column.Field.Asboolean]; DBgrid1.Canvas.FillRect(Rect); DrawFrameControl(DBgrid1.Canvas.Handle, DrawRect, DFC_BUTTON, DrawState); end; if (Column.Field.FieldName = 'GENERADORES') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; // DrawState := ISChecked[Column.Field.Asboolean]; DBgrid1.Canvas.FillRect(Rect); DrawFrameControl(DBgrid1.Canvas.Handle, DrawRect, DFC_BUTTON, DrawState); end; if (Column.Field.FieldName = 'activo') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; // DrawState := ISChecked[Column.Field.Asboolean]; DBgrid1.Canvas.FillRect(Rect); DrawFrameControl(DBgrid1.Canvas.Handle, DrawRect, DFC_BUTTON, DrawState); end; end; end; procedure Tfgruposfamilias.DBGrid2DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); const IsChecked : array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED); var DrawState: Integer; DrawRect: TRect; begin if (gdFocused in State) then begin if (Column.Field.FieldName = 'activo') then begin gcrpagado.Left := Rect.Left + DBgrid2.Left + 2; gcrpagado.Top := Rect.Top + DBgrid2.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'activo') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; // DrawState := ISChecked[Column.Field.Asboolean]; DBgrid2.Canvas.FillRect(Rect); DrawFrameControl(DBgrid2.Canvas.Handle, DrawRect, DFC_BUTTON, DrawState); end; end; end; procedure Tfgruposfamilias.DBGrid3CellClick(Column: TColumn); begin if column.Field.FieldName ='activo' then begin if qgruposactivo.asinteger=1 then begin qgrupos.Edit; qgruposactivo.Value:=0; qgrupos.Post; dbgrid3.selectedIndex:=1; end else begin qgrupos.Edit; qgruposactivo.Value:=1; qgrupos.Post; qgrupos.Refresh; dbgrid3.SelectedIndex:=1; end; end; end; procedure Tfgruposfamilias.DBGrid3DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); const IsChecked : array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED); var DrawState: Integer; DrawRect: TRect; begin if (gdFocused in State) then begin if (Column.Field.FieldName = 'activo') then begin gcrpagado.Left := Rect.Left + DBgrid3.Left + 2; gcrpagado.Top := Rect.Top + DBgrid3.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'activo') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; // DrawState := ISChecked[Column.Field.Asboolean]; DBgrid3.Canvas.FillRect(Rect); DrawFrameControl(DBgrid3.Canvas.Handle, DrawRect, DFC_BUTTON, DrawState); end; end; gcrpagado.Visible := false; end; procedure Tfgruposfamilias.dsfamiliasStateChange(Sender: TObject); begin if qfamilias.State in [dsedit,dsinsert] then begin btfnuevo.Enabled:=false; btfmodificar.Enabled:=false; btfborrar.Enabled:=false; btfcancelar.Enabled:=true; btfguardar.Enabled:=true; end else begin btfnuevo.Enabled:=true; btfmodificar.Enabled:=true; btfborrar.Enabled:=true; btfcancelar.Enabled:=false; btfguardar.Enabled:=false; end; end; procedure Tfgruposfamilias.dsgruposStateChange(Sender: TObject); begin if qgrupos.State in [dsedit,dsinsert] then begin btGnuevo.Enabled:=false; btgmodificar.Enabled:=false; btgborrar.Enabled:=false; btgcancelar.Enabled:=true; btgguardar.Enabled:=true; btfnuevo.Enabled:=false; btfmodificar.Enabled:=false; btfborrar.Enabled:=false; btfcancelar.Enabled:=false; btfguardar.Enabled:=false; end else begin btgnuevo.Enabled:=true; btgmodificar.Enabled:=true; btgborrar.Enabled:=true; btgcancelar.Enabled:=false; btgguardar.Enabled:=false; btfnuevo.Enabled:=true; btfmodificar.Enabled:=true; btfborrar.Enabled:=true; btfcancelar.Enabled:=false; btfguardar.Enabled:=false; end; end; procedure Tfgruposfamilias.FormCreate(Sender: TObject); var I: Integer; begin Application.OnMessage := AppMessage; gcrpagado.DataField := 'pagado'; gcrpagado.Visible := False; gcrpagado.SendToBack; gcrpagado.Color := DBGrid1.Color; gcrpagado.Caption := ''; gcrpagado.ValueChecked := '0'; gcrpagado.ValueUnChecked := '1'; end; procedure Tfgruposfamilias.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tfgruposfamilias.FormKeyPress(Sender: TObject; var Key: Char); begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tfgruposfamilias.FormShow(Sender: TObject); begin qgrupos.Close; qfamilias.Close; qarticulos.Close; qgrupos.open; qfamilias.open; qarticulos.open; end; procedure Tfgruposfamilias.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; end. ======================================== FICHERO: gruposfamilias.Unit2.pas ======================================== unit gruposfamilias.Unit2; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,Vcl.StdCtrls, Vcl.DBCtrls, Vcl.Mask, Vcl.ComCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.DBLookup,datos, ZAbstractDataset, ZDataset, Data.DB, ZAbstractRODataset, ZAbstractTable; type Tfgruposfamilias = class(TForm) procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } end; var fgruposfamilias: Tfgruposfamilias; implementation {$R *.dfm} procedure Tfgruposfamilias.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tfgruposfamilias.FormKeyPress(Sender: TObject; var Key: Char); begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; end. ======================================== FICHERO: pesadas.pas ======================================== unit pesadas; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Data.DB, Vcl.DBCtrls, Vcl.Grids, Vcl.DBGrids, datosproduccion, ZAbstractDataset, ZDataset, ZAbstractRODataset, Vcl.Mask, Vcl.ImgList, ZAbstractTable,ShellApi, frxClass, frxDBSet; type Tfpesadas = class(TForm) Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; Panel4: TPanel; Panel5: TPanel; chk_entradas: TCheckBox; chk_salidas: TCheckBox; Edit1: TEdit; btbuscar: TButton; Panel6: TPanel; Panel11: TPanel; DBGrid1: TDBGrid; qlistapesadas: TZReadOnlyQuery; dsqlistapesadas: TDataSource; qpesadas: TZQuery; qpesadasid: TIntegerField; qpesadasidempresa: TIntegerField; qpesadasidEA: TIntegerField; qpesadasid_palet: TWideStringField; qpesadasnum_palets: TIntegerField; qpesadasid_envase: TWideStringField; qpesadasnum_envases: TIntegerField; qpesadasiddestino: TIntegerField; qpesadasdestino: TWideStringField; qpesadaspeso_bruto: TFloatField; qpesadastara: TFloatField; qpesadaspeso_neto: TFloatField; qpesadaspeso_neto_teorico: TFloatField; qpesadaspeso_medio: TFloatField; qpesadastemperatura: TFloatField; qpesadasfecha: TDateField; qpesadasfechatrabajo: TDateField; qpesadashora: TTimeField; qpesadasCEA: TWideStringField; qpesadasresto_cajas: TFloatField; qpesadasresto_pesoneto: TFloatField; qpesadaslote: TIntegerField; qpesadasORIGEN: TWideStringField; qpesadasidorigen: TIntegerField; qpesadasmprima: TWideStringField; qpesadasgen_caja: TIntegerField; qpesadascosto: TFloatField; qpesadascoste_manipulacion: TFloatField; qpesadasdias_camara: TIntegerField; qpesadascosto_camara: TFloatField; qpesadascodigoR: TWideStringField; qpesadasparcela: TWideStringField; qpesadasfecha_cierre: TDateField; qpesadascosto_materiales: TFloatField; qpesadascosto_cosechar: TFloatField; qpesadasborrado: TIntegerField; qpesadasseleccionado: TIntegerField; qpesadasOBSERVACIONES: TWideStringField; qpesadastipo_trabajo: TWideStringField; qpesadastipo_generador: TWideStringField; qpesadasremanipulado: TIntegerField; qpesadasfecha_envasado: TDateField; qpesadascodean: TWideStringField; qpesadascodssc: TWideStringField; qpesadaspedidocliente: TIntegerField; qpesadascosto_sinmt: TFloatField; Label1: TLabel; DBEdit1: TDBEdit; dsqpesadas: TDataSource; Label2: TLabel; DBEdit2: TDBEdit; Label3: TLabel; Label4: TLabel; DBEdit4: TDBEdit; Label5: TLabel; DBEdit6: TDBEdit; Label7: TLabel; DBEdit7: TDBEdit; Label8: TLabel; DBEdit8: TDBEdit; DBEdit9: TDBEdit; Label9: TLabel; Label10: TLabel; DBEdit11: TDBEdit; Label11: TLabel; Label6: TLabel; DBEdit13: TDBEdit; Label12: TLabel; DBEdit14: TDBEdit; Label13: TLabel; DBEdit15: TDBEdit; Label14: TLabel; DBEdit16: TDBEdit; Label15: TLabel; DBEdit17: TDBEdit; Label16: TLabel; DBEdit18: TDBEdit; Label17: TLabel; DBEdit19: TDBEdit; Label18: TLabel; Label19: TLabel; DBEdit21: TDBEdit; Label20: TLabel; DBEdit22: TDBEdit; Label21: TLabel; DBEdit23: TDBEdit; Label22: TLabel; DBEdit24: TDBEdit; DBEdit25: TDBEdit; Label23: TLabel; DBEdit26: TDBEdit; Label24: TLabel; DBEdit27: TDBEdit; Label25: TLabel; DBEdit28: TDBEdit; Label26: TLabel; Label27: TLabel; DBEdit30: TDBEdit; Label28: TLabel; DBEdit31: TDBEdit; Label29: TLabel; DBEdit32: TDBEdit; Label30: TLabel; DBMemo1: TDBMemo; Label33: TLabel; DBEdit35: TDBEdit; DBCheckBox1: TDBCheckBox; Label32: TLabel; DBEdit34: TDBEdit; Label34: TLabel; DBEdit36: TDBEdit; qpesadasid_palet2: TWideStringField; qpesadasnum_palets2: TIntegerField; dsqlotes: TDataSource; qlotes: TZQuery; qlotesid: TIntegerField; qloteside: TIntegerField; qlotesidea: TIntegerField; qlotesidea2: TIntegerField; qloteslote: TIntegerField; qlotescajas: TIntegerField; qlotespesoneto_teorico: TFloatField; qlotespesoneto_real: TFloatField; qloteses_entrada: TIntegerField; DBGrid3: TDBGrid; qenvases: TZReadOnlyQuery; qpalets: TZReadOnlyQuery; qenvasesid: TIntegerField; qenvaseside: TIntegerField; qenvasescodigo: TWideStringField; qenvasescod_logi: TIntegerField; qenvasesdescripcion: TWideStringField; qenvaseslargo: TFloatField; qenvasesalto: TFloatField; qenvasesancho: TFloatField; qenvasestara: TFloatField; qenvasespeso_venta: TFloatField; qenvasestipo: TWideStringField; qenvasespalet: TIntegerField; qenvasesenvase_trabajo: TIntegerField; qenvasesenvase_venta: TIntegerField; qenvasescosto: TFloatField; qenvasesactivo: TIntegerField; qenvasesobservaciones: TWideStringField; qenvasesfacturar_pesofijo: TIntegerField; qenvasespreguntar_gen: TIntegerField; dsqenvases: TDataSource; dsqpalets: TDataSource; btcancelar: TButton; btborrar: TButton; btaceptar: TButton; dsqorigenes: TDataSource; qorigenes: TZReadOnlyQuery; dsqalmacenes: TDataSource; qalmacenes: TZReadOnlyQuery; dsqmprimas: TDataSource; qmprimas: TZReadOnlyQuery; qmprimasidempresa: TIntegerField; qmprimasid: TWideStringField; qmprimasvariedad: TWideStringField; qmprimasdescripcion: TWideStringField; qmprimasobservaciones: TWideStringField; qmprimasimagen: TBlobField; qmprimasEAN: TWideStringField; qmprimasbasculas: TIntegerField; qmprimasactivo: TIntegerField; qmprimasusar_precio_parcela: TIntegerField; qmprimasdesechos: TIntegerField; qmprimasgenerico: TWideStringField; qmprimascompuesto: TIntegerField; comboorigen: TDBLookupComboBox; DBLookupComboBox5: TDBLookupComboBox; qalmacenesempresa: TIntegerField; qalmacenescodigo: TIntegerField; qalmacenesnombre: TWideStringField; qlistapesadasidempresa: TIntegerField; qlistapesadasfecha: TDateField; qlistapesadasid: TIntegerField; qlistapesadasidea: TIntegerField; qlistapesadasdestino: TWideStringField; qorigenesempresa: TIntegerField; qorigenescodigo: TWideStringField; qorigenesnombre: TWideStringField; qorigenes2: TZReadOnlyQuery; qorigenes2empresa: TIntegerField; qorigenes2codigo: TIntegerField; qorigenes2nombre: TWideStringField; Label36: TLabel; DBEdit3: TDBEdit; qpesadastara0: TFloatField; DBLookupComboBox1: TDBLookupComboBox; DBLookupComboBox2: TDBLookupComboBox; DBLookupComboBox3: TDBLookupComboBox; DBEdit5: TDBEdit; qpesadaslotes_detalle: TWideStringField; qlotesparcela: TWideStringField; btnuevolote: TButton; btborrarlote: TButton; Label37: TLabel; DBEdit10: TDBEdit; qlotesmprima: TWideStringField; DBCheckBox2: TDBCheckBox; qpesadasidpedido: TIntegerField; qpesadasrecuperar_envases: TIntegerField; Label38: TLabel; Label39: TLabel; DBEdit20: TDBEdit; Label40: TLabel; DBEdit29: TDBEdit; qpesadascalibre: TFloatField; qpedido: TZReadOnlyQuery; dsqpedido: TDataSource; DBText1: TDBText; DBText2: TDBText; DBText3: TDBText; DBText4: TDBText; Label42: TLabel; Label43: TLabel; Label44: TLabel; Label45: TLabel; Label46: TLabel; DBText5: TDBText; qaux: TZReadOnlyQuery; listaiconos: TImageList; documentos: TZTable; documentosid: TIntegerField; documentoside: TIntegerField; documentosfecha: TDateField; documentosdescripcion: TWideStringField; documentosarchivo: TBlobField; documentosnomarchivo: TWideStringField; documentosextension: TWideStringField; documentosidlote: TIntegerField; documentoscodpar: TWideStringField; documentosidea: TIntegerField; dsdocumentos: TDataSource; qpesadasprov_albaran: TWideStringField; qpesadasprov_fecha: TDateField; qpesadasprov_ggn: TWideStringField; qpesadasprov_lote: TWideStringField; qpesadasprov_grower: TWideStringField; qpesadasprov_puk: TWideStringField; qpesadasprov_otros: TWideStringField; Panel7: TPanel; Label47: TLabel; Label48: TLabel; Label49: TLabel; Label50: TLabel; Label51: TLabel; Label52: TLabel; Label53: TLabel; DBEdit39: TDBEdit; DBEdit40: TDBEdit; DBEdit41: TDBEdit; DBEdit42: TDBEdit; DBEdit43: TDBEdit; DBEdit44: TDBEdit; DBEdit45: TDBEdit; Label54: TLabel; qlotesid_envase: TWideStringField; qlotesid_formato: TIntegerField; qlotesdesc_envase: TWideStringField; qlotesdesc_formato: TWideStringField; qlotescalibrecalidad: TIntegerField; qlotesdesc_calibre: TWideStringField; Button1: TButton; qlotesresto_cajas: TIntegerField; qpesadasidalbaran: TWideStringField; Label41: TLabel; DBLookupComboBox4: TDBLookupComboBox; dsqtipohora: TDataSource; qtipohora: TZReadOnlyQuery; qtipohoraid: TWideStringField; qtipohoranombre: TWideStringField; qtipohoraempresa: TIntegerField; DBLookupComboBox6: TDBLookupComboBox; DBLookupComboBox7: TDBLookupComboBox; DBLookupComboBox8: TDBLookupComboBox; dsqformatos: TDataSource; qformatos: TZReadOnlyQuery; dsqcalidad: TDataSource; qcalidad: TZReadOnlyQuery; qcalidadid: TIntegerField; qcalidaddescripcion: TWideStringField; qcalidadvalor: TWideStringField; qformatosid: TIntegerField; qformatoside: TIntegerField; qformatosdescripcion: TWideStringField; qformatosactivo: TIntegerField; qformatosdescripcion2: TWideStringField; qformatoscoste: TFloatField; qformatospeso: TFloatField; qlistapesadascosto_materiales: TFloatField; btmodificarlote: TButton; qaux2: TZReadOnlyQuery; Button2: TButton; qetiquetas: TZReadOnlyQuery; dsqetiquetas: TDataSource; dsqlotespesadas: TDataSource; qlotespesadas: TZReadOnlyQuery; qetiquetasid: TIntegerField; qetiquetasidempresa: TIntegerField; qetiquetasidEA: TIntegerField; qetiquetasid_palet: TWideStringField; qetiquetasnum_palets: TIntegerField; qetiquetasid_palet2: TWideStringField; qetiquetasnum_palets2: TIntegerField; qetiquetasid_envase: TWideStringField; qetiquetasnum_envases: TIntegerField; qetiquetasiddestino: TIntegerField; qetiquetasdestino: TWideStringField; qetiquetaspeso_bruto: TFloatField; qetiquetastara: TFloatField; qetiquetaspeso_neto: TFloatField; qetiquetaspeso_neto_teorico: TFloatField; qetiquetaspeso_medio: TFloatField; qetiquetastemperatura: TFloatField; qetiquetasfecha: TDateField; qetiquetasfechatrabajo: TDateField; qetiquetashora: TTimeField; qetiquetasCEA: TWideStringField; qetiquetasresto_cajas: TFloatField; qetiquetasresto_pesoneto: TFloatField; qetiquetaslote: TIntegerField; qetiquetasORIGEN: TWideStringField; qetiquetasidorigen: TIntegerField; qetiquetasmprima: TWideStringField; qetiquetasgen_caja: TIntegerField; qetiquetascosto: TFloatField; qetiquetascoste_manipulacion: TFloatField; qetiquetasdias_camara: TIntegerField; qetiquetascosto_camara: TFloatField; qetiquetascodigoR: TWideStringField; qetiquetasparcela: TWideStringField; qetiquetasfecha_cierre: TDateField; qetiquetascosto_materiales: TFloatField; qetiquetascosto_cosechar: TFloatField; qetiquetasborrado: TIntegerField; qetiquetasseleccionado: TIntegerField; qetiquetasOBSERVACIONES: TWideStringField; qetiquetastipo_trabajo: TWideStringField; qetiquetastipo_generador: TWideStringField; qetiquetasremanipulado: TIntegerField; qetiquetasfecha_envasado: TDateField; qetiquetascodean: TWideStringField; qetiquetascodssc: TWideStringField; qetiquetaspedidocliente: TIntegerField; qetiquetascosto_sinmt: TFloatField; qetiquetastara0: TFloatField; qetiquetaslotes_detalle: TWideStringField; qetiquetasidpedido: TIntegerField; qetiquetasidalbaran: TWideStringField; qetiquetasrecuperar_envases: TIntegerField; qetiquetascalibre: TFloatField; qetiquetasprov_albaran: TWideStringField; qetiquetasprov_fecha: TDateField; qetiquetasprov_ggn: TWideStringField; qetiquetasprov_lote: TWideStringField; qetiquetasprov_grower: TWideStringField; qetiquetasprov_puk: TWideStringField; qetiquetasprov_otros: TWideStringField; qetiquetasidfactura: TWideStringField; qetiquetasidgrupo: TIntegerField; infpesadas: TfrxReport; informedb: TfrxDBDataset; informedb2: TfrxDBDataset; Label55: TLabel; qpesadasidfactura: TWideStringField; qinsertarmateriales: TZReadOnlyQuery; qpedidoid: TIntegerField; qpedidoide: TIntegerField; qpedidoidcliente: TIntegerField; qpedidoiddestino: TWideStringField; qpedidofecha_pedido: TDateField; qpedidofecha_carga: TDateField; qpedidofecha_entrega: TDateField; qpedidohora_carga: TTimeField; qpedidopedidocliente: TWideStringField; qpedidoabierto: TIntegerField; qpedidoobservaciones: TWideStringField; qpedidofecha_elavoracion: TDateField; qpedidofecha_caducidad: TDateField; qpedidoalbarancliente: TWideStringField; qpedidonombre_corto: TWideStringField; qpedidodescripcion: TWideStringField; DBText6: TDBText; Label31: TLabel; DBText7: TDBText; Label35: TLabel; qpedidoalbaran: TWideStringField; qpedidofactura: TWideStringField; DBText8: TDBText; DBText9: TDBText; procedure btbuscarClick(Sender: TObject); procedure chk_salidasClick(Sender: TObject); procedure chk_entradasClick(Sender: TObject); procedure btnuevoClick(Sender: TObject); procedure dsqpesadasStateChange(Sender: TObject); procedure btaceptarClick(Sender: TObject); procedure btcancelarClick(Sender: TObject); procedure dsqpesadasDataChange(Sender: TObject; Field: TField); procedure btborrarClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnuevoloteClick(Sender: TObject); procedure btborrarloteClick(Sender: TObject); procedure Edit1Exit(Sender: TObject); procedure qlotesAfterPost(DataSet: TDataSet); procedure btdborrarClick(Sender: TObject); procedure btdcancelarClick(Sender: TObject); procedure btdverClick(Sender: TObject); procedure Edit1Enter(Sender: TObject); procedure Button1Click(Sender: TObject); procedure DBGrid3DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure qlotesBeforePost(DataSet: TDataSet); procedure dsqlotesStateChange(Sender: TObject); procedure btmodificarloteClick(Sender: TObject); procedure Button2Click(Sender: TObject); procedure qpesadasBeforeDelete(DataSet: TDataSet); procedure DBGrid1CellClick(Column: TColumn); private { Private declarations } hWndC : THandle; procedure SetResolution(Width, Height: integer); public { Public declarations } var desdefuera:integer; end; var fpesadas: Tfpesadas; const WM_CAP_START = WM_USER; WM_CAP_DRIVER_CONNECT = WM_CAP_START + 10; WM_CAP_DRIVER_DISCONNECT = WM_CAP_START + 11; WM_CAP_SAVEDIB = WM_CAP_START + 25; WM_CAP_GET_VIDEOFORMAT = WM_CAP_START + 44; WM_CAP_SET_VIDEOFORMAT = WM_CAP_START + 45; WM_CAP_SET_PREVIEW = WM_CAP_START + 50; WM_CAP_SET_OVERLAY = WM_CAP_START + 51; WM_CAP_SET_PREVIEWRATE = WM_CAP_START + 52; WM_CAP_SET_SCALE = WM_CAP_START + 53; function capCreateCaptureWindowA(lpszWindowName: PCHAR; dwStyle, x, y, nWidth, nHeight: integer; ParentWin: HWND; nId: integer): HWND; stdcall external 'AVICAP32.DLL'; implementation uses datos, datostrazabilidad, datosestadisticas, fmaterialespesada, datostrazabilidad2; {$R *.dfm} procedure Tfpesadas.btaceptarClick(Sender: TObject); var id,tmultiplicador:string; multiplicador:real; begin qaux.SQL.Clear; qaux.SQL.Add('select compuesto from materias_primas where idempresa='+qpesadasidempresa.asstring+' and id='+''''+qpesadasmprima.asstring+''''); qaux.Open; if qaux.Fields[0].AsInteger=0 then multiplicador:=1 else multiplicador:=0.5; tmultiplicador:=floattostr(multiplicador); tmultiplicador:=StringReplace(tmultiplicador, ',', '.',[rfReplaceAll, rfIgnoreCase]); edit1.Text:=qpesadasid.AsString; id:=qpesadasid.AsString; qlotes.Refresh; qaux.Close; qaux.sql.clear; qaux.sql.Add('delete from ea_materiales where ide='+qpesadasidempresa.AsString+' and idea='+qpesadasid.AsString+' and idea2='+qpesadasidea.AsString); qaux.execsql; if qlotes.RecordCount>0 then begin qinsertarmateriales.prepare; qinsertarmateriales.ParamByName('EMPRESA').AsInteger:=qpesadasidempresa.AsInteger; qinsertarmateriales.ParamByName('IDEA').AsInteger:=qpesadasid.AsInteger; qinsertarmateriales.ParamByName('IDEA2').AsInteger:=qpesadasidea.AsInteger; qinsertarmateriales.ParamByName('NUMPALETS').AsInteger:=qpesadasnum_palets.AsInteger; qinsertarmateriales.ParamByName('MULTIPLICADOR').AsFLOAT:=multiplicador; qinsertarmateriales.ParamByName('IDPALET').AsString:=qpesadasid_palet.AsString; qinsertarmateriales.ExecSQL; { qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('insert into ea_materiales '); qaux.SQL.Add('select idempresa,'+qpesadasid.AsString+' as idea,'+qpesadasidea.AsString+' as idea2,idarticulof,sum(cantidadtotal) as cantidadtotal,sum(pesototal) as pesototal,null,sum(preciototal) as preciototal,0 as recuperado from '); //// materiales de los envases qaux.SQL.Add('(SELECT ac.idempresa,ac.idarticuloalmacen,ac.idarticulof,(ac.cantidad*lp.cajas*'+tmultiplicador+') as cantidadtotal,(ac.peso*lp.cajas*'+tmultiplicador+') as pesototal,(ac.cantidad*ac.preciocoste*lp.cajas*'+tmultiplicador+') as preciototal '); qaux.SQL.Add(' FROM articulos_componentes ac,(SELECT lp.ide,lp.idea,lp.idea2,sum(cajas) as cajas,aa.id as id_envase FROM lotes_pesadas lp,articulos_almacen aa where aa.ide=lp.ide and aa.codigo=lp.id_envase '); qaux.SQL.Add(' and lp.ide='+qpesadasidempresa.AsString+' and lp.idea='+qpesadasid.AsString+' and lp.idea2='+qpesadasidea.AsString+' group by lp.id_envase ) as lp '); qaux.SQL.Add(' where ac.idempresa=lp.ide and ac.idarticuloalmacen=lp.id_envase '); qaux.SQL.Add(' union ALL'); // materiales de los formatos qaux.SQL.Add(' SELECT ac.ide,ac.idcfg,ac.idaf,(ac.cantidad*lp.cajas*'+tmultiplicador+') as cantidadtotal,(ac.peso*lp.cajas*'+tmultiplicador+') as pesototal,(ac.coste*lp.cajas*'+tmultiplicador+') as preciototal FROM '); qaux.SQL.Add(' configuraciones_detalle ac,(SELECT lp.ide,lp.idea,lp.idea2,sum(cajas) as cajas,aa.id as id_envase FROM lotes_pesadas lp, '); qaux.SQL.Add(' configuraciones aa where aa.ide=lp.ide and aa.id=lp.id_formato and lp.ide='+qpesadasidempresa.AsString+' and lp.idea='+qpesadasid.AsString+' and lp.idea2='+qpesadasidea.AsString+' group by lp.id_envase ) as lp '); qaux.SQL.Add(' where ac.ide=lp.ide and ac.idcfg=lp.id_envase '); qaux.SQL.Add(' union ALL'); //// materiales de los palets qaux.SQL.Add(' SELECT ac.idempresa,ac.idarticuloalmacen,ac.idarticulof,(ac.cantidad*'+qpesadasnum_palets.AsString+') as cantidadtotal,(ac.peso*'+qpesadasnum_palets.AsString+') as pesototal,(ac.coste*'+qpesadasnum_palets.AsString+') as preciototal'); qaux.SQL.Add(' FROM articulos_componentes ac where ac.idempresa='+qpesadasidempresa.AsString+' and ac.idarticuloalmacen=(select id from articulos_almacen where codigo='+''''+qpesadasid_palet.AsString+''''+' )'); qaux.SQL.Add(' ) as ea_materiales_tmp group by idarticulof'); qaux.execsql;} end; if qpesadasrecuperar_envases.AsInteger=1 then begin qaux.SQL.Clear; qaux.SQL.Add('update ea_materiales ea set recuperado=-1 where ea.ide='+qpesadasidempresa.asstring+' and ea.idea='+qpesadasid.AsString+' and ea.idea2='+qpesadasidea.AsString); qaux.execsql; end else begin qaux.SQL.Clear; qaux.SQL.Add('update ea_materiales ea set recuperado=0 where ea.ide='+qpesadasidempresa.asstring+' and ea.idea='+qpesadasid.AsString+' and ea.idea2='+qpesadasidea.AsString); qaux.execsql; end; if qpesadas.State in [dsbrowse] then qpesadas.Edit; qpesadasid_palet2.Value:='TRIGGER_ON'; if qpesadascosto_sinmt.Asstring='' then qpesadascosto_sinmt.Value:=0; qaux.sql.clear; qaux.sql.Add('select sum(peso),sum(precio) from ea_materiales where ide='+qpesadasidempresa.AsString+' and idea='+qpesadasid.AsString+' and idea2='+qpesadasidea.AsString); qaux.open; qpesadastara.Value:=qaux.Fields[0].AsFloat; qaux.sql.clear; qaux.sql.Add('select sum(peso),sum(precio) from ea_materiales where recuperado=0 and ide='+qpesadasidempresa.AsString+' and idea='+qpesadasid.AsString+' and idea2='+qpesadasidea.AsString); qaux.open; qpesadascosto_materiales.Value:=qaux.Fields[1].AsFloat; qpesadascosto.Value:=qpesadascosto_cosechar.AsFloat+qpesadascosto_camara.AsFloat+qpesadascosto_materiales.AsFloat+qpesadascosto_sinmt.AsFloat+qpesadascoste_manipulacion.AsFloat; qpesadas.Post; qaux.sql.clear; qaux.sql.Add('select ea.ide,af.codigo from ea_materiales ea,articulosf af where ea.ide=af.idempresa and ea.idaf=af.id and ea.recuperado=0 and ea.ide='+qpesadasidempresa.AsString+' and ea.idea='+qpesadasid.AsString+' and ea.idea2='+qpesadasidea.AsString); qaux.open; { while not qaux.Eof do begin qaux2.SQL.Clear; qaux2.SQL.Add('update articulosf set stock=(select sum(stock) from entradas_detalle where stock>0 and id_propio='+''''+qaux.Fields[1].asstring+''''+' and idempresa='+qaux.Fields[0].asstring+')'); qaux2.SQL.Add(' where idempresa='+qaux.Fields[0].AsString+' and codigo='+''''+qaux.Fields[1].asstring+''''); qaux2.execsql; qaux.Next; end; } dbedit1.Enabled:=false; qlistapesadas.Refresh; qpesadas.Refresh; qlistapesadas.Locate('id',id,[locaseinsensitive]); if dmproduccion.qsalidas2.Active=true then dmproduccion.qsalidas2.Refresh; if dmproduccion.qsalidaslotes.Active=true then dmproduccion.qsalidaslotes.Refresh; if dmproduccion.qentradas2.Active=true then dmproduccion.qentradas2.Refresh; if dmproduccion.qentradas.Active=true then dmproduccion.qentradas.Refresh; if dmtr.qsalidas.Active=true then dmtr.qsalidas.Refresh; if dmtr.qea_pesadas.Active=true then dmtr.qea_pesadas.Refresh; if dmestadisticas.qproduccion_almacen.active then dmestadisticas.qproduccion_almacen.Refresh; // btbuscar.Click; end; procedure Tfpesadas.btborrarClick(Sender: TObject); begin qpesadas.Delete; dbedit1.Enabled:=false; qlistapesadas.Refresh; qpesadas.Refresh; if dmproduccion.qsalidas2.Active then dmproduccion.qsalidas2.Refresh; if dmproduccion.qsalidaslotes.Active then dmproduccion.qsalidaslotes.Refresh; edit1.SetFocus; end; procedure Tfpesadas.btborrarloteClick(Sender: TObject); begin qlotes.Delete; end; procedure Tfpesadas.btbuscarClick(Sender: TObject); var vid:string; begin if edit1.Text<>'' then begin vid:=edit1.Text; end else vid:='%'; { qlistapesadas.Open; qlistapesadas.Refresh; qlistapesadas.locate('id',edit1.Text,[locaseinsensitive]); } // qpesadas.Close; // qlotes.Close; qlistapesadas.close; qlistapesadas.Prepare; qlistapesadas.ParamByName('ID').AsString:=vid; qlistapesadas.Open; // qlistapesadas.SQL.Clear; // qlistapesadas.SQL.Add('select idempresa,fecha,id,idea,destino,costo_materiales from ea_pesadas where id='+edit1.Text+' and idempresa='+dm.tempresaid.AsString+' order by fecha desc, id desc limit 500'); if qlistapesadas.RecordCount=0 then showmessage('CODIGO NO ENCONTRADO'); qpesadas.Prepare; qpesadas.ParamByName('id').AsInteger:=qlistapesadasid.AsInteger; qpesadas.ParamByName('idea').AsInteger:=qlistapesadasidea.AsInteger; qpesadas.Refresh; // qpesadas.SQL.Clear; // qpesadas.SQL.Add('select * from ea_pesadas where id='+qlistapesadasid.AsString+' and idea='+qlistapesadasidea.AsString+' order by fecha desc'); qlotes.Prepare; qlotes.ParamByName('id').AsInteger:=qlistapesadasid.AsInteger; qlotes.ParamByName('idea').AsInteger:=qlistapesadasidea.AsInteger; qlotes.Refresh; end; procedure Tfpesadas.btcancelarClick(Sender: TObject); begin qpesadas.Cancel; dbedit1.Enabled:=false; end; procedure Tfpesadas.btdborrarClick(Sender: TObject); begin documentos.Delete; end; procedure Tfpesadas.btdcancelarClick(Sender: TObject); begin documentos.cancel end; procedure Tfpesadas.btdverClick(Sender: TObject); var nomarchivo:string; begin nomarchivo:=documentosnomarchivo.asstring; ShellExecute(Handle,nil,PChar('c:\agrigest\tmp\'+nomarchivo),'','',SW_SHOWNORMAL); end; procedure Tfpesadas.btmodificarloteClick(Sender: TObject); begin qlotes.Edit; dbgrid3.SetFocus; dbgrid3.SelectedIndex:=0; end; procedure Tfpesadas.btnuevoClick(Sender: TObject); begin qpesadas.Append; dbedit1.Enabled:=true; dbedit1.SetFocus; end; procedure Tfpesadas.btnuevoloteClick(Sender: TObject); begin qlotes.Append; dbgrid3.SetFocus; end; procedure Tfpesadas.Button1Click(Sender: TObject); begin materialespesadas := Tmaterialespesadas.Create(nil); try materialespesadas.qmateriales.close; materialespesadas.qmateriales.sql.Clear; materialespesadas.qmateriales.sql.Add('select a.id,a.codigo,a.descripcion,ea.ide,ea.idea,ea.idea2,ea.idaf,ea.cantidad,ea.peso,ea.lote,ea.precio,ea.recuperado from ea_materiales ea,articulosf a where ea.ide=a.idempresa and ea.idaf=a.id '); materialespesadas.qmateriales.sql.Add(' and ea.ide='+qpesadasidempresa.asstring+' and ea.idea='+qpesadasid.AsString+' and ea.idea2='+qpesadasidea.AsString+' order by a.descripcion'); // materialespesadas.qmateriales.open; materialespesadas.qmateriales2.close; materialespesadas.qmateriales2.sql.Clear; materialespesadas.qmateriales2.sql.Add('select * from ea_materiales ea where ea.ide='+qpesadasidempresa.asstring+' and ea.idea='+qpesadasid.AsString+' and ea.idea2='+qpesadasidea.AsString); // materialespesadas.qmateriales2.open; materialespesadas .showmodal(); finally materialespesadas .Free; qaux.sql.clear; qaux.sql.Add('select sum(peso) from ea_materiales where ide='+qpesadasidempresa.AsString+' and idea='+qpesadasid.AsString+' and idea2='+qpesadasidea.AsString); qaux.open; if qpesadas.State in [dsbrowse] then qpesadas.Edit; qpesadasid_palet2.Value:='TRIGGER_OFF'; if qpesadascosto_sinmt.Asstring='' then qpesadascosto_sinmt.Value:=0; qpesadastara.Value:=qaux.Fields[0].AsFloat; qaux.sql.clear; qaux.sql.Add('select sum(peso),sum(precio) from ea_materiales where recuperado=0 and ide='+qpesadasidempresa.AsString+' and idea='+qpesadasid.AsString+' and idea2='+qpesadasidea.AsString); qaux.open; qpesadascosto_materiales.Value:=qaux.Fields[1].AsFloat; // qpesadascosto.Value:=qpesadascosto_cosechar.AsFloat+qpesadascosto_camara.AsFloat+qpesadascosto_materiales.AsFloat+qpesadascosto_sinmt.AsFloat+qpesadascoste_manipulacion.AsFloat; qpesadas.Post; qpesadas.refresh; end; end; procedure Tfpesadas.Button2Click(Sender: TObject); begin qetiquetas.Close; qetiquetas.prepare; qetiquetas.ParamByName('PID').AsInteger:=qpesadasid.asinteger; qetiquetas.ParamByName('PIDEA').AsInteger:=qpesadasidea.asinteger; qetiquetas.ParamByName('PEMPRESA').AsInteger:=qpesadasidempresa.asinteger; qetiquetas.open; qlotespesadas.close; qlotespesadas.prepare; qlotespesadas.ParamByName('PID').AsInteger:=qpesadasid.asinteger; qlotespesadas.ParamByName('PIDEA').AsInteger:=qpesadasidea.asinteger; qlotespesadas.ParamByName('PEMPRESA').AsInteger:=qpesadasidempresa.asinteger; // qlotespesadas.SQL.add('SELECT lp.ide,lp.idea,lp.idea2,lp.lote,lp.cajas,lp.pesoneto_teorico,lp.pesoneto_real,l.fecha,l.parcela,l.PAISORIGEN,l.mprima,lp.desc_envase,lp.desc_formato,lp.desc_calibre,l.trazabilidad,pc.nombre '); // qlotespesadas.SQL.Add(' FROM `lotes_pesadas` lp, lotes l,parcelas pc where lp.parcela=pc.codpar and lp.ide=pc.empresa and lp.lote=l.codigo and lp.ide=l.idempresa and lp.idea='+dm.qpesadassalidasid.asstring+' and lp.ide='+dm.qpesadassalidasidempresa.asstring+' and lp.idea2='+dm.qpesadassalidasidea.asstring); qlotespesadas.open; informedb.Datasource:=dsqetiquetas; informedb2.DataSource:=dsqlotespesadas; infpesadas.Report.Clear; infpesadas.LoadFromFile('c:\agrigest\informes\etiquetamovimientos2.fr3'); // informes.Variables.Variables['TITULO']:=QUOTEDSTR('PARTIDA: '+qpartidasid.asstring+ ' FECHA: '+datetostr(tfecha.Date)+' PARCELA: '+qinfpartidasnombre.AsString+' VARIEDAD: '+qinfpartidasdescripcion.AsString); // informes.PrintOptions.Printer.Empty infpesadas.Report.PrepareReport(true); // informes.PrintOptions.ShowDialog:=false; // informes.Report.ShowReport(); infpesadas.Print; end; procedure Tfpesadas.chk_entradasClick(Sender: TObject); begin if (chk_entradas.Checked) and (chk_salidas.Checked) then begin qlistapesadas.close; qlistapesadas.SQL.Clear; qlistapesadas.SQL.Add('select idempresa,fecha,id,idea,destino,costo_materiales from ea_pesadas order by fecha desc, id desc limit 1000'); qlistapesadas.Open; end; if (not chk_entradas.Checked) and (chk_salidas.Checked) then begin qlistapesadas.close; qlistapesadas.SQL.Clear; qlistapesadas.SQL.Add('select idempresa,fecha,id,idea,destino,costo_materiales from ea_pesadas where idea=0 order by fecha desc, id desc limit 1000'); qlistapesadas.Open; end; if (chk_entradas.Checked) and (not chk_salidas.Checked) then begin qlistapesadas.close; qlistapesadas.SQL.Clear; qlistapesadas.SQL.Add('select idempresa,fecha,id,idea,destino,costo_materiales from ea_pesadas where idea<>0 order by fecha desc, id desc limit 1000'); qlistapesadas.Open; end; if (not chk_entradas.Checked) and (not chk_salidas.Checked) then begin qlistapesadas.close; qlistapesadas.SQL.Clear; qlistapesadas.SQL.Add('select idempresa,fecha,id,idea,destino,costo_materiales from ea_pesadas order by fecha desc, id desc limit 1000'); qlistapesadas.Open; end; end; procedure Tfpesadas.chk_salidasClick(Sender: TObject); begin if (chk_entradas.Checked) and (chk_salidas.Checked) then begin qlistapesadas.close; qlistapesadas.SQL.Clear; qlistapesadas.SQL.Add('select idempresa,fecha,id,idea,destino,costo_materiales from ea_pesadas order by fecha desc, id desc limit 1000'); qlistapesadas.Open; end; if (not chk_entradas.Checked) and (chk_salidas.Checked) then begin qlistapesadas.close; qlistapesadas.SQL.Clear; qlistapesadas.SQL.Add('select idempresa,fecha,id,idea,destino,costo_materiales from ea_pesadas where idea<=0 order by fecha desc, id desc limit 1000'); qlistapesadas.Open; end; if (chk_entradas.Checked) and (not chk_salidas.Checked) then begin qlistapesadas.close; qlistapesadas.SQL.Clear; qlistapesadas.SQL.Add('select idempresa,fecha,id,idea,destino,costo_materiales from ea_pesadas where idea<>0 order by fecha desc, id desc limit 1000'); qlistapesadas.Open; end; if (not chk_entradas.Checked) and (not chk_salidas.Checked) then begin qlistapesadas.close; qlistapesadas.SQL.Clear; qlistapesadas.SQL.Add('select idempresa,fecha,id,idea,destino,costo_materiales from ea_pesadas order by fecha desc, id desc limit 1000'); qlistapesadas.Open; end; end; procedure Tfpesadas.DBGrid1CellClick(Column: TColumn); begin if qlistapesadas.RecordCount>0 then begin // qpesadas.Close; qpesadas.Prepare; qpesadas.ParamByName('id').AsInteger:=qlistapesadasid.AsInteger; qpesadas.ParamByName('idea').AsInteger:=qlistapesadasidea.AsInteger; // qpesadas.Open; qpesadas.Refresh; // qpesadas.SQL.Clear; // qpesadas.SQL.Add('select * from ea_pesadas where id='+qlistapesadasid.AsString+' and idea='+qlistapesadasidea.AsString+' order by fecha desc'); // qlotes.Close; qlotes.Prepare; qlotes.ParamByName('id').AsInteger:=qlistapesadasid.AsInteger; qlotes.ParamByName('idea').AsInteger:=qlistapesadasidea.AsInteger; // qlotes.Open; qlotes.Refresh; // qlotes.SQL.Clear; // qlotes.SQL.Add('select * from lotes_pesadas where idea='+qlistapesadasid.AsString+' and idea2='+qlistapesadasidea.AsString+' order by idea desc'); end; end; procedure Tfpesadas.DBGrid3DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if qlotes.State in [dsedit,dsinsert] then begin { DBLookupComboBox6.Visible:=true; DBLookupComboBox7.Visible:=true; DBLookupComboBox8.Visible:=true;} if (gdFocused in State) then begin if (Column.Field.FieldName = DBLookupComboBox6.DataField) then with DBLookupComboBox6 do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; // Width := 150;//Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; end else DBLookupComboBox6.Visible:=false; if (Column.Field.FieldName = DBLookupComboBox7.DataField) then with DBLookupComboBox7 do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; // Width := 150;//Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; end else DBLookupComboBox7.Visible:=false; if (Column.Field.FieldName = DBLookupComboBox8.DataField) then with DBLookupComboBox8 do begin Left := Rect.Left + DBGrid3.Left + 2; Top := Rect.Top + DBGrid3.Top + 2; // Width := 150;//Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; Visible := True; end else DBLookupComboBox8.Visible:=false; end end else begin DBLookupComboBox6.Visible:=false; DBLookupComboBox7.Visible:=false; DBLookupComboBox8.Visible:=false; end; end; procedure Tfpesadas.dsqlotesStateChange(Sender: TObject); begin if qlotes.State in [dsinsert,dsedit] then dbgrid3.Enabled:=true else begin DBLookupComboBox6.Visible:=false; DBLookupComboBox7.Visible:=false; DBLookupComboBox8.Visible:=false; dbgrid3.Enabled:=true; end; end; procedure Tfpesadas.dsqpesadasDataChange(Sender: TObject; Field: TField); begin if qpesadas.State in [dsbrowse] then begin if qpesadasidea.AsInteger<=0 then begin qorigenes2.Close; dsqorigenes.DataSet:=qorigenes2; comboorigen.keyfield:='codigo'; comboorigen.DataField:='idorigen'; qorigenes2.Open; end; if qpesadasidea.AsInteger>0 then begin qorigenes.Close; dsqorigenes.DataSet:=qorigenes; comboorigen.keyfield:='nombre'; comboorigen.DataField:='ORIGEN'; qorigenes.Open; end; qpedido.close; qpedido.prepare; qpedido.ParamByName('EMPRESA').AsInteger:=qpesadasidempresa.AsInteger; qpedido.ParamByName('IDPEDIDO').AsInteger:=qpesadasidpedido.AsInteger; qpedido.open; end; end; procedure Tfpesadas.dsqpesadasStateChange(Sender: TObject); begin if qpesadas.State in [dsedit,dsinsert] then begin btborrar.Enabled:=false; btaceptar.Caption:='Aceptar'; btcancelar.Enabled:=true; end; if qpesadas.State in [dsbrowse] then begin btborrar.Enabled:=true; btaceptar.caption:='Recalcular'; btcancelar.Enabled:=false; end; end; procedure Tfpesadas.Edit1Enter(Sender: TObject); begin edit1.Text:=''; end; procedure Tfpesadas.Edit1Exit(Sender: TObject); begin btbuscar.Click; end; procedure Tfpesadas.FormClose(Sender: TObject; var Action: TCloseAction); var lote,pesada:integer; begin lote:=qloteslote.AsInteger; if dmtr.qlotes.Active then dmtr.qlotes.Refresh; if dmtr.qlotes.Active then dmtr.qlotes.Locate('codigo',lote,[locaseinsensitive,lopartialkey]); if qpesadasidea.AsInteger=0 then begin pesada:=qpesadasid.AsInteger; if dmtr.qsalidas.Active then dmtr.qsalidas.Refresh; if dmtr.qsalidas.Active then dmtr.qsalidas.Locate('id',pesada,[locaseinsensitive,lopartialkey]); end else begin pesada:=qpesadasid.AsInteger; if dmtr.qea_pesadas.Active then dmtr.qea_pesadas.Refresh; if dmtr.qea_pesadas.Active then dmtr.qea_pesadas.Locate('id',pesada,[locaseinsensitive,lopartialkey]); end; qlistapesadas.close; qpesadas.close; qlotes.close; qenvases.close; qpalets.close; qmprimas.close; qorigenes.close; qorigenes.close; qalmacenes.close; end; procedure Tfpesadas.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; if (key='.') and (activecontrol is tedit) then begin key:=',' end; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tfpesadas.qlotesAfterPost(DataSet: TDataSet); begin qlotes.Refresh; end; procedure Tfpesadas.qlotesBeforePost(DataSet: TDataSet); begin if qlotes.State in [dsinsert,dsedit] then begin qloteside.Value:=qpesadasidempresa.AsInteger; qlotesidea.Value:=qpesadasid.AsInteger; qlotesidea2.Value:=qpesadasidea.AsInteger; qlotesdesc_envase.Value:=qenvasesdescripcion.AsString; qlotesdesc_formato.Value:=qformatosdescripcion.AsString; qlotesdesc_calibre.Value:=qcalidaddescripcion.AsString; end; end; procedure Tfpesadas.qpesadasBeforeDelete(DataSet: TDataSet); begin case dm.PedirConfirmacion('¿Confirma que desea borrar este ID?',true,true,false) of mrno:Abort; end; end; procedure TFpesadas.SetResolution(Width, Height: integer); var bi: BITMAPINFO; begin SendMessage(hWndC, WM_CAP_GET_VIDEOFORMAT, sizeof(bi), Cardinal(@bi)); bi.bmiHeader.biWidth:= Width; bi.bmiHeader.biHeight:= Height; if SendMessage(hWndC, WM_CAP_SET_VIDEOFORMAT, sizeof(bi), Cardinal(@bi)) <> 0 then begin SendMessage(hWndC, WM_CAP_DRIVER_DISCONNECT, 0, 0); SendMessage(hWndC, WM_CAP_DRIVER_CONNECT, 0, 0); end; end; end. ======================================== FICHERO: principal.pas ======================================== unit principal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Menus, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, Vcl.Tabs, Vcl.ComCtrls, Vcl.Mask, Vcl.DBCtrls, ZAbstractConnection, ZConnection, ZAbstractTable, Vcl.ExtDlgs, Vcl.Imaging.jpeg, frxClass, frxDBSet, frxExportPDF, frxBarcode, Vcl.Buttons, VCLTee.TeEngine, VCLTee.Series, VCLTee.TeeData, VCLTee.TeeProcs, VCLTee.Chart, VCLTee.DBChart, ShellApi, Vcl.OleCtrls, IdHTTP, mshtml, SHDocVw, wgssSTU_TLB, SignatureForm, Vcl.ToolWin, Vcl.ImgList, dateutils, Vcl.OleServer, ComObj, Excel2000, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdMessage, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdMessageClient, IdSMTPBase, IdSMTP, frxExportBaseDialog, VCLTee.TeeGDIPlus; type TBASE = class(TForm) PGeneral: TPanel; PDEmpleados: TPanel; PMenu: TPanel; BSalir: TButton; Panel2: TPanel; Panel1: TPanel; dsqtrabajadores: TDataSource; DBGrid1: TDBGrid; Label1: TLabel; tbuscar: TEdit; dstrabajadores: TDataSource; PageEmpleados: TPageControl; tabDatosGenerales: TTabSheet; TabJornales: TTabSheet; TabAnticipos: TTabSheet; tabPagos: TTabSheet; Panel3: TPanel; Panel5: TPanel; DBGrid2: TDBGrid; dsqjornales: TDataSource; qjornales: TZReadOnlyQuery; qempleados: TZReadOnlyQuery; qempleadosnombre: TWideStringField; qjornalesid: TIntegerField; qjornalesfecha: TDateField; qjornalesparcela: TWideStringField; qjornalesidt: TIntegerField; qjornalestrabajador: TWideStringField; qjornalestypework: TWideStringField; qjornalesarticulo: TWideStringField; qjornalesqhoras: TFloatField; qjornalesestado: TWideStringField; Panel6: TPanel; Panel7: TPanel; Panel8: TPanel; xtempleados: TZTable; xtempleadosNIF: TWideStringField; xtempleadosnombre: TWideStringField; xtempleadosactivo: TIntegerField; xtempleadosNOMBRECORTO: TWideStringField; xtempleadosAPELLIDOS: TWideStringField; xtempleadosDIRECCION: TWideStringField; xtempleadosPOBLACION: TWideStringField; xtempleadosPROVINCIA: TWideStringField; xtempleadosFECHANACIMIENTO: TDateField; xtempleadosPAISNAC: TWideStringField; xtempleadosNACIONALIDAD: TWideStringField; xtempleadosSEXO: TWideStringField; xtempleadosCBIBAN: TWideStringField; xtempleadosCBBANCO: TWideStringField; xtempleadosCBOFICINA: TWideStringField; xtempleadosCBDC: TWideStringField; xtempleadosCBCC: TWideStringField; xtempleadosTELEFONO1: TWideStringField; xtempleadosTELEFONO2: TWideStringField; xtempleadosTELEFONO3: TWideStringField; xtempleadosTELEFONO4: TWideStringField; xtempleadosNUMSEGSOCIAL: TWideStringField; xtempleadosIRPF: TFloatField; xtempleadosDESEMPLEO: TFloatField; xtempleadosFORMACION: TFloatField; xtempleadosOBSERVACIONES: TWideStringField; xtempleadosFECHAALTA: TDateField; xtempleadosFECHABAJA: TDateField; xtempleadosFIJO: TSmallintField; xtempleadosFIJODISCONTINUO: TSmallintField; xtempleadosTEMPORAL: TSmallintField; xtempleadosCONTINGENCIAS: TFloatField; xtempleadosempresa: TIntegerField; Label4: TLabel; DBEdit3: TDBEdit; Label8: TLabel; DBEdit7: TDBEdit; falta: TDateTimePicker; fbaja: TDateTimePicker; Label9: TLabel; Panel4: TPanel; Label19: TLabel; DBEdit16: TDBEdit; Label20: TLabel; Label21: TLabel; DBEdit18: TDBEdit; Label22: TLabel; DBEdit19: TDBEdit; Panel9: TPanel; Label12: TLabel; diagimagen: TOpenPictureDialog; tfechajornal: TDateTimePicker; lparcela: TDBLookupComboBox; ltrabajo: TDBLookupComboBox; ltipohora: TDBLookupComboBox; btinsertar: TButton; thoras: TEdit; tjornales: TZTable; dsjornales: TDataSource; tjornalesid: TIntegerField; tjornalesfecha: TDateField; tjornalesparcela: TWideStringField; tjornalesidt: TIntegerField; tjornalestrabajador: TWideStringField; tjornalestypework: TWideStringField; tjornalesarticulo: TWideStringField; tjornalesqhoras: TFloatField; qaux: TZReadOnlyQuery; Label28: TLabel; Label29: TLabel; Label26: TLabel; DBEdit28: TDBEdit; Label27: TLabel; Label31: TLabel; DBEdit34: TDBEdit; Label32: TLabel; DBEdit35: TDBEdit; Label33: TLabel; DBEdit36: TDBEdit; Label34: TLabel; DBEdit37: TDBEdit; Label35: TLabel; DBMemo1: TDBMemo; DBCheckBox1: TDBCheckBox; DBCheckBox2: TDBCheckBox; DBCheckBox3: TDBCheckBox; Label36: TLabel; DBEdit38: TDBEdit; Tanyo: TComboBox; TMES: TComboBox; TESTADO: TComboBox; Label37: TLabel; Label38: TLabel; Label39: TLabel; Panel12: TPanel; DBGrid3: TDBGrid; Panel11: TPanel; Panel10: TPanel; Label40: TLabel; Label41: TLabel; Label42: TLabel; Label43: TLabel; tanyo2: TComboBox; tmes2: TComboBox; testado2: TComboBox; bborrarjornales: TButton; bmodificarjornales: TButton; lprecio: TEdit; Label47: TLabel; Label48: TLabel; Label49: TLabel; Label50: TLabel; Label51: TLabel; Label52: TLabel; Label46: TLabel; Label10: TLabel; Button3: TButton; Button4: TButton; xtempleadosID: TSmallintField; qempleadosid: TSmallintField; tjornalesprecio: TFloatField; tjornalestotal: TFloatField; tjornalesestado: TWideStringField; qjornalesprecio: TFloatField; qjornalestotal: TFloatField; Panel13: TPanel; Label53: TLabel; baceptar: TButton; BtEmpleados: TBitBtn; Btjornales: TBitBtn; btexpediciones: TBitBtn; bttrabajos: TBitBtn; bttrazabilidad: TBitBtn; btempresa: TBitBtn; DBCheckBox4: TDBCheckBox; xtempleadosPAGARPORBANCO: TIntegerField; xtempleadosCP: TWideStringField; Button5: TButton; PDNominas: TPanel; PageNominas: TPageControl; Nominaspag1: TTabSheet; Panel18: TPanel; Panel19: TPanel; Panel21: TPanel; dsnominas: TDataSource; tnominas: TZTable; dslinnominas: TDataSource; tlinnominas: TZTable; tlinnominasIDN: TIntegerField; tlinnominasId: TIntegerField; tlinnominasFECHA: TDateField; tlinnominasANYO: TIntegerField; tlinnominasMES: TWideStringField; tlinnominasNIF: TWideStringField; tlinnominasNOMBRE: TWideStringField; tlinnominasDIRECCION: TWideStringField; tlinnominasCP: TWideStringField; tlinnominasPOBLACION: TWideStringField; tlinnominasHORAS: TFloatField; tlinnominasFECHAALTA: TDateField; tlinnominasDIASTRABAJADOS: TIntegerField; tlinnominasDIASMAXIMO: TIntegerField; tlinnominasDIASCALCULO: TIntegerField; tlinnominasTOTALBRUTO: TFloatField; tlinnominasIRPF: TFloatField; tlinnominasTOTALIRPF: TFloatField; tlinnominasDESEMPLEO: TFloatField; tlinnominasTOTALDESEMPLEO: TFloatField; tlinnominasFORMACION: TFloatField; tlinnominasTOTALFORMACION: TFloatField; tlinnominasCONTINGENCIAS: TFloatField; tlinnominasTOTALCONTINGENCIAS: TFloatField; tlinnominasTOTALNETO: TFloatField; tlinnominasANTICIPOS: TFloatField; tlinnominasTOTALAPAGAR: TFloatField; tlinnominasCUENTAPAGO: TWideStringField; tlinnominasFECHAPAGO: TDateField; tlinnominasESTADO: TWideStringField; tlinnominasSALARIOBASE: TFloatField; tlinnominasDIASLABORABLES: TIntegerField; dsqnominas: TDataSource; qnominas: TZReadOnlyQuery; DBEdit32: TDBEdit; DBEdit29: TDBEdit; DBEdit30: TDBEdit; DBEdit31: TDBEdit; DBEdit33: TDBEdit; qnominasID: TIntegerField; qnominasFECHA: TDateField; qnominasPERIODO: TIntegerField; qnominasNOMPERIODO: TWideStringField; qnominasANYO: TIntegerField; qnominasESTADO: TWideStringField; qlinnominas: TZReadOnlyQuery; dsqlinnominas: TDataSource; qlinnominasIDN: TIntegerField; qlinnominasId: TIntegerField; qlinnominasIDT: TIntegerField; qlinnominasANYO: TIntegerField; qlinnominasMES: TWideStringField; qlinnominasNIF: TWideStringField; qlinnominasNOMBRE: TWideStringField; qlinnominasDIRECCION: TWideStringField; qlinnominasCP: TWideStringField; qlinnominasPOBLACION: TWideStringField; qlinnominasHORAS: TFloatField; qlinnominasFECHAALTA: TDateField; qlinnominasDIASTRABAJADOS: TIntegerField; qlinnominasDIASMAXIMO: TIntegerField; qlinnominasDIASCALCULO: TIntegerField; qlinnominasTOTALBRUTO: TFloatField; qlinnominasIRPF: TFloatField; qlinnominasTOTALIRPF: TFloatField; qlinnominasDESEMPLEO: TFloatField; qlinnominasTOTALDESEMPLEO: TFloatField; qlinnominasFORMACION: TFloatField; qlinnominasTOTALFORMACION: TFloatField; qlinnominasCONTINGENCIAS: TFloatField; qlinnominasTOTALCONTINGENCIAS: TFloatField; qlinnominasTOTALNETO: TFloatField; qlinnominasANTICIPOS: TFloatField; qlinnominasTOTALAPAGAR: TFloatField; qlinnominasCUENTAPAGO: TWideStringField; qlinnominasFECHAPAGO: TDateField; qlinnominasESTADO: TWideStringField; qlinnominasSALARIOBASE: TFloatField; qlinnominasDIASLABORABLES: TIntegerField; qlinnominasCORRECTO: TIntegerField; tnominasID: TIntegerField; tnominasFECHA: TDateField; tnominasPERIODO: TIntegerField; tnominasNOMPERIODO: TWideStringField; tnominasANYO: TIntegerField; tnominasESTADO: TWideStringField; btproduccion: TBitBtn; PDProduccion: TPanel; baceptarempleados: TButton; bcancelarempleados: TButton; bcancelarjornal: TButton; Vaciar: TButton; Vaciar2: TButton; qjornalesorigen: TWideStringField; DBEdit39: TDBEdit; DBGrid4: TDBGrid; NominasPag2: TTabSheet; Shape1: TShape; Label65: TLabel; Label66: TLabel; Shape2: TShape; Label68: TLabel; Shape4: TShape; Label69: TLabel; Shape5: TShape; Shape3: TShape; Label67: TLabel; Label70: TLabel; Shape6: TShape; Label71: TLabel; Shape7: TShape; Label72: TLabel; Shape8: TShape; DBGrid5: TDBGrid; Panel16: TPanel; Shape9: TShape; Label76: TLabel; Label77: TLabel; Shape10: TShape; Label78: TLabel; Shape11: TShape; Label79: TLabel; Shape12: TShape; btAgenda: TBitBtn; PDAgenda: TPanel; calendarionotas: TMonthCalendar; DBCheckBox5: TDBCheckBox; Panel17: TPanel; DBGrid6: TDBGrid; Label80: TLabel; PDEmpresa: TPanel; PageDatosEmpresa: TPageControl; DatosGenerales: TTabSheet; ProductosAcabados: TTabSheet; TipoHora: TTabSheet; TipoTrabajo: TTabSheet; TrabajosAlmacen: TTabSheet; Campañas: TTabSheet; Nominaspag3: TTabSheet; Panel20: TPanel; Label106: TLabel; nomfechadesde: TDateTimePicker; nomfechahasta: TDateTimePicker; DBGrid7: TDBGrid; Panel22: TPanel; btvalorar: TButton; CheckBox1: TCheckBox; CheckBox2: TCheckBox; CheckBox3: TCheckBox; Panel23: TPanel; Label109: TLabel; Shape13: TShape; Label110: TLabel; Label111: TLabel; Shape14: TShape; Label112: TLabel; Shape15: TShape; Label113: TLabel; Shape16: TShape; DBEdit64: TDBEdit; xtempleadosREGIMEN_COT: TWideStringField; Label13: TLabel; DBListBox1: TDBListBox; PMateriasprimas: TTabSheet; Panel24: TPanel; Panel25: TPanel; Panel26: TPanel; DBGrid8: TDBGrid; Panel27: TPanel; Panel28: TPanel; PageControl1: TPageControl; TabSheet4: TTabSheet; bprmodificar: TButton; bprborrar: TButton; bpranadir: TButton; bpraceptar: TButton; bprcancelar: TButton; Label14: TLabel; DBEdit10: TDBEdit; Label15: TLabel; DBEdit11: TDBEdit; Label16: TLabel; DBEdit12: TDBEdit; Label17: TLabel; DBEdit13: TDBEdit; Label18: TLabel; DBEdit14: TDBEdit; Label24: TLabel; DBEdit15: TDBEdit; Label114: TLabel; DBEdit20: TDBEdit; Label115: TLabel; DBEdit21: TDBEdit; Label116: TLabel; DBEdit65: TDBEdit; Label117: TLabel; DBEdit66: TDBEdit; DBCheckBox6: TDBCheckBox; DBCheckBox7: TDBCheckBox; Label118: TLabel; Label119: TLabel; Label120: TLabel; Panel29: TPanel; DBGrid9: TDBGrid; Panel30: TPanel; Panel31: TPanel; Panel32: TPanel; Panel33: TPanel; PageControl3: TPageControl; TabSheet3: TTabSheet; Panel34: TPanel; DBGrid10: TDBGrid; Panel35: TPanel; Panel36: TPanel; Panel37: TPanel; Label124: TLabel; Label125: TLabel; bthmodificar: TButton; bthborrar: TButton; bthanadir: TButton; bthaceptar: TButton; bthcancelar: TButton; DBEdit69: TDBEdit; DBEdit70: TDBEdit; DBCheckBox9: TDBCheckBox; Panel38: TPanel; PageControl6: TPageControl; TabSheet6: TTabSheet; DBCheckBox10: TDBCheckBox; Label127: TLabel; DBEdit71: TDBEdit; Panel39: TPanel; DBGrid11: TDBGrid; Panel40: TPanel; Panel41: TPanel; Panel42: TPanel; Label129: TLabel; Label130: TLabel; bttmodificar: TButton; bttborrar: TButton; bttanadir: TButton; bttaceptar: TButton; bttcancelar: TButton; DBEdit72: TDBEdit; DBEdit74: TDBEdit; DBCheckBox11: TDBCheckBox; Panel43: TPanel; PageControl7: TPageControl; TabSheet7: TTabSheet; Panel44: TPanel; DBGrid12: TDBGrid; Panel45: TPanel; Panel46: TPanel; Panel47: TPanel; Label131: TLabel; Label132: TLabel; btamodificar: TButton; btaborrar: TButton; btaanadir: TButton; btaaceptar: TButton; btacancelar: TButton; DBEdit75: TDBEdit; DBCheckBox12: TDBCheckBox; Panel48: TPanel; PageControl8: TPageControl; TabSheet8: TTabSheet; DBLookupComboBox1: TDBLookupComboBox; Label133: TLabel; DBEdit76: TDBEdit; Label134: TLabel; DBLookupComboBox2: TDBLookupComboBox; Label135: TLabel; DBLookupComboBox3: TDBLookupComboBox; Panel14: TPanel; Panel49: TPanel; Panel50: TPanel; Pageproduccion: TPageControl; TabSheet1: TTabSheet; TabSheet5: TTabSheet; TabSheet9: TTabSheet; TabSheet10: TTabSheet; TabSheet11: TTabSheet; DBGrid13: TDBGrid; fprodesde: TDateTimePicker; Label56: TLabel; Label57: TLabel; DBGrid14: TDBGrid; dsqmesas: TDataSource; DBGrid15: TDBGrid; DBGrid16: TDBGrid; Timer1: TTimer; graficoproduccion: TDBChart; ChartDataSet1: TChartDataSet; Series1: TBarSeries; pproduccionmesa: TTabSheet; DBGrid17: TDBGrid; DBChart2: TDBChart; DBGrid18: TDBGrid; DBGrid19: TDBGrid; Series2: TLineSeries; Panel51: TPanel; Label59: TLabel; Shape17: TShape; Label60: TLabel; Label61: TLabel; Shape18: TShape; Label62: TLabel; Shape19: TShape; Label136: TLabel; Shape20: TShape; DBEdit77: TDBEdit; Label137: TLabel; DBEdit78: TDBEdit; Button7: TButton; DBCheckBox13: TDBCheckBox; DBCheckBox14: TDBCheckBox; DBCheckBox15: TDBCheckBox; DBCheckBox16: TDBCheckBox; Parcelas: TTabSheet; DBGrid20: TDBGrid; Panel52: TPanel; Panel53: TPanel; Panel54: TPanel; Label139: TLabel; Label140: TLabel; bccmodificar: TButton; bccborrar: TButton; bccanadir: TButton; bccaceptar: TButton; bcccancelar: TButton; DBEdit79: TDBEdit; DBEdit80: TDBEdit; DBCheckBox17: TDBCheckBox; Panel55: TPanel; PageControl2: TPageControl; TabSheet13: TTabSheet; TabSheet12: TTabSheet; btcontrolprodcerrar: TButton; Panel56: TPanel; Label141: TLabel; Label142: TLabel; DBEdit82: TDBEdit; Label143: TLabel; DBEdit83: TDBEdit; Label144: TLabel; DBEdit84: TDBEdit; Label145: TLabel; DBEdit85: TDBEdit; Label146: TLabel; Label147: TLabel; DBEdit86: TDBEdit; Label148: TLabel; DBEdit87: TDBEdit; Label151: TLabel; Label152: TLabel; DBEdit90: TDBEdit; Label153: TLabel; DBEdit91: TDBEdit; Label154: TLabel; DBEdit92: TDBEdit; Label155: TLabel; DBEdit93: TDBEdit; Label156: TLabel; DBEdit94: TDBEdit; Label157: TLabel; DBEdit95: TDBEdit; Button16: TButton; Label158: TLabel; DBEdit96: TDBEdit; Label159: TLabel; DBComboBox1: TDBComboBox; btcontrolproduccion: TButton; Panel57: TPanel; Panel60: TPanel; PageControl4: TPageControl; TabSheet14: TTabSheet; DBGrid23: TDBGrid; Panel58: TPanel; PageControl5: TPageControl; TabSheet15: TTabSheet; DBGrid22: TDBGrid; Panel61: TPanel; bcanadir: TButton; bcmodificar: TButton; bcborrar: TButton; bccancelar: TButton; bcaceptar: TButton; CheckBox4: TCheckBox; CheckBox5: TCheckBox; CheckBox6: TCheckBox; DBEdit101: TDBEdit; Label164: TLabel; Nominaspag5: TTabSheet; Panel62: TPanel; Label165: TLabel; Label166: TLabel; Label167: TLabel; nomlhdesde: TDateTimePicker; nomlhhasta: TDateTimePicker; Button10: TButton; DBGrid24: TDBGrid; DBGrid25: TDBGrid; DBGrid26: TDBGrid; CheckBox7: TCheckBox; CheckBox8: TCheckBox; ListaInformes: TComboBox; Nominaspag6: TTabSheet; Panel63: TPanel; Label168: TLabel; Label169: TLabel; Label170: TLabel; nomlttdesde: TDateTimePicker; nomltthasta: TDateTimePicker; Button9: TButton; CheckBox9: TCheckBox; CheckBox10: TCheckBox; listainformes2: TComboBox; DBGrid27: TDBGrid; DBGrid28: TDBGrid; DBGrid29: TDBGrid; COMBOLISTADOS: TComboBox; CheckBox11: TCheckBox; Button11: TButton; Nominaspag4: TTabSheet; Panel64: TPanel; Panel65: TPanel; Panel66: TPanel; Panel67: TPanel; DBGrid30: TDBGrid; DBGrid31: TDBGrid; Label172: TLabel; Label173: TLabel; pagnomfechahasta: TDateTimePicker; pagnomfechadesde: TDateTimePicker; Panel68: TPanel; Panel69: TPanel; TabSheet19: TTabSheet; Edit1: TEdit; fechaestacion: TDateTimePicker; Button14: TButton; PAGE2: TMemo; Panel70: TPanel; Shape21: TShape; Label174: TLabel; Label175: TLabel; Shape22: TShape; Label176: TLabel; Shape23: TShape; Label177: TLabel; Shape24: TShape; DBCheckBox19: TDBCheckBox; Button12: TButton; DBText1: TDBText; Label181: TLabel; Label182: TLabel; DBText2: TDBText; Label184: TLabel; DBText4: TDBText; Label185: TLabel; DBText5: TDBText; Label186: TLabel; DBText6: TDBText; Panel71: TPanel; Nominaspag7: TTabSheet; Button17: TButton; DBGrid32: TDBGrid; CheckBox12: TCheckBox; Panel73: TPanel; Panel74: TPanel; Panel75: TPanel; Panel72: TPanel; DBGrid33: TDBGrid; Panel76: TPanel; PDTrazabilidad: TPanel; PageControl10: TPageControl; TabSheet22: TTabSheet; Panel79: TPanel; DBGrid35: TDBGrid; Panel80: TPanel; PLDatos: TPanel; Panel83: TPanel; PageControl11: TPageControl; TabSheet23: TTabSheet; TabSheet24: TTabSheet; DBText3: TDBText; Label189: TLabel; Label190: TLabel; Label192: TLabel; dlotescodigo: TDBEdit; Panel86: TPanel; Panel87: TPanel; DBGrid38: TDBGrid; Entradas: TTabSheet; Almacenes: TTabSheet; Panel99: TPanel; Panel100: TPanel; Label194: TLabel; PageControl12: TPageControl; TabSheet26: TTabSheet; DBGrid45: TDBGrid; TabSheet27: TTabSheet; Panel101: TPanel; DBGrid46: TDBGrid; DBGrid47: TDBGrid; PDExpediciones: TPanel; PageControl13: TPageControl; TabSheet28: TTabSheet; PageControl14: TPageControl; TabSheet29: TTabSheet; DBGrid48: TDBGrid; Panel102: TPanel; DBGrid49: TDBGrid; TabSheet30: TTabSheet; Label197: TLabel; DBEdit104: TDBEdit; Label198: TLabel; DBEdit105: TDBEdit; Panel103: TPanel; Panel104: TPanel; Panel105: TPanel; DBGrid51: TDBGrid; Panel106: TPanel; Panel107: TPanel; DBGrid50: TDBGrid; Panel108: TPanel; DBGrid52: TDBGrid; PageControl15: TPageControl; TabSheet31: TTabSheet; TabSheet32: TTabSheet; TabSheet33: TTabSheet; TabSheet34: TTabSheet; DBCheckBox21: TDBCheckBox; DBCheckBox22: TDBCheckBox; almacen: TTabSheet; DBGrid53: TDBGrid; Panel109: TPanel; Panel110: TPanel; Label199: TLabel; Label200: TLabel; DBEdit106: TDBEdit; DBEdit107: TDBEdit; Panel111: TPanel; PageControl16: TPageControl; TabSheet36: TTabSheet; Panel112: TPanel; baanadir: TButton; bamodificar: TButton; baborrar: TButton; bacancelar: TButton; baaceptar: TButton; Label201: TLabel; DBEdit108: TDBEdit; Label203: TLabel; DBEdit110: TDBEdit; Label204: TLabel; DBEdit111: TDBEdit; Label205: TLabel; DBEdit112: TDBEdit; DBCheckBox23: TDBCheckBox; DBCheckBox24: TDBCheckBox; DBCheckBox25: TDBCheckBox; Label206: TLabel; DBEdit113: TDBEdit; DBGrid55: TDBGrid; DBCheckBox30: TDBCheckBox; Panel91: TPanel; Panel98: TPanel; Panel117: TPanel; DBGrid44: TDBGrid; Panel118: TPanel; Panel119: TPanel; Panel120: TPanel; Panel121: TPanel; DBGrid59: TDBGrid; DBGrid60: TDBGrid; Label222: TLabel; DBEdit125: TDBEdit; Label223: TLabel; DBEdit126: TDBEdit; Label224: TLabel; DBEdit127: TDBEdit; DBEdit128: TDBEdit; DBEdit129: TDBEdit; Label228: TLabel; DBEdit130: TDBEdit; Label229: TLabel; DBEdit131: TDBEdit; Label232: TLabel; DBEdit134: TDBEdit; DBEdit135: TDBEdit; DBEdit136: TDBEdit; Label237: TLabel; DBEdit137: TDBEdit; DBEdit138: TDBEdit; DBEdit139: TDBEdit; btactualizar: TButton; Panel122: TPanel; DBGrid21: TDBGrid; DBGrid61: TDBGrid; Panel123: TPanel; Panel124: TPanel; Panel125: TPanel; DBCheckBox31: TDBCheckBox; DBGrid63: TDBGrid; Button19: TButton; Panel81: TPanel; Panel84: TPanel; DBGrid36: TDBGrid; DBGrid37: TDBGrid; Panel85: TPanel; DBGrid54: TDBGrid; Panel126: TPanel; Button20: TButton; Label225: TLabel; Label226: TLabel; Label230: TLabel; DBEdit144: TDBEdit; DBEdit145: TDBEdit; Label244: TLabel; DBEdit146: TDBEdit; Label245: TLabel; DBEdit147: TDBEdit; Button24: TButton; Edit2: TEdit; Label240: TLabel; Label241: TLabel; DBEdit140: TDBEdit; DBEdit142: TDBEdit; Label242: TLabel; DBEdit148: TDBEdit; btcerrar: TButton; bticierre: TButton; ffechatraspaso: TDateTimePicker; Label246: TLabel; dbfechatraspaso: TDBEdit; Label248: TLabel; Label249: TLabel; Label250: TLabel; DBEdit149: TDBEdit; Label251: TLabel; DBEdit150: TDBEdit; DBEdit151: TDBEdit; Label252: TLabel; DBEdit152: TDBEdit; Label253: TLabel; Label247: TLabel; Label254: TLabel; Label238: TLabel; DBEdit154: TDBEdit; DBEdit155: TDBEdit; DBEdit156: TDBEdit; DBEdit157: TDBEdit; DBEdit158: TDBEdit; Label235: TLabel; DBEdit159: TDBEdit; DBEdit160: TDBEdit; Label231: TLabel; DBEdit161: TDBEdit; DBEdit162: TDBEdit; DBEdit163: TDBEdit; Label236: TLabel; DBEdit164: TDBEdit; DBEdit165: TDBEdit; DBEdit166: TDBEdit; Label218: TLabel; DBEdit132: TDBEdit; Label219: TLabel; DBEdit133: TDBEdit; Label220: TLabel; DBEdit141: TDBEdit; Label221: TLabel; DBEdit153: TDBEdit; Label227: TLabel; DBEdit167: TDBEdit; Label233: TLabel; DBEdit168: TDBEdit; Label234: TLabel; DBEdit169: TDBEdit; Label239: TLabel; DBEdit170: TDBEdit; Label255: TLabel; DBEdit171: TDBEdit; Label256: TLabel; DBEdit172: TDBEdit; Label257: TLabel; DBEdit173: TDBEdit; Label258: TLabel; DBEdit174: TDBEdit; Label259: TLabel; DBEdit175: TDBEdit; Label260: TLabel; DBEdit176: TDBEdit; Label261: TLabel; DBEdit177: TDBEdit; Label262: TLabel; DBEdit178: TDBEdit; lfecha: TDBEdit; DBLookupComboBox4: TDBLookupComboBox; DBLookupComboBox5: TDBLookupComboBox; DBEdit181: TDBEdit; Label193: TLabel; Label263: TLabel; Panel127: TPanel; Panel128: TPanel; Label264: TLabel; Label265: TLabel; tbuscarnominas: TEdit; DBGrid64: TDBGrid; Label267: TLabel; Label268: TLabel; chkTodos: TCheckBox; chkPendientes: TCheckBox; chkFirmados: TCheckBox; Menu: TMainMenu; M1: TMenuItem; DatosEmpresa1: TMenuItem; MateriasPrimas1: TMenuItem; Centrosdecoste1: TMenuItem; Almacenes1: TMenuItem; Campaas1: TMenuItem; Nominas1: TMenuItem; Gastos1: TMenuItem; Ventas1: TMenuItem; PedidosClientes1: TMenuItem; AlbaranesClientes1: TMenuItem; FacturasClientes1: TMenuItem; Maquinaria1: TMenuItem; CalendarioLaboral1: TMenuItem; Empleados1: TMenuItem; EnvasesAlmacen1: TMenuItem; iposdetrabajos1: TMenuItem; iposdehoras1: TMenuItem; rabajosdeAlmacen1: TMenuItem; Etiquetas1: TMenuItem; N4: TMenuItem; rabajodiario1: TMenuItem; Anticipos1: TMenuItem; CalculodeNominas1: TMenuItem; PagosRealizados1: TMenuItem; N5: TMenuItem; ListadoporHoras1: TMenuItem; Listadoportipodetrabajo1: TMenuItem; N6: TMenuItem; Partesdetrabajo1: TMenuItem; N7: TMenuItem; Salir1: TMenuItem; listameses: TComboBox; listaanyos: TComboBox; Label183: TLabel; Label55: TLabel; btactualizarempleadosnominas: TButton; Button25: TButton; Label63: TLabel; DBEdit179: TDBEdit; DBEdit182: TDBEdit; DBEdit183: TDBEdit; Label64: TLabel; Shape25: TShape; Shape26: TShape; DBEdit184: TDBEdit; Label88: TLabel; Label107: TLabel; Label108: TLabel; Label187: TLabel; DBEdit185: TDBEdit; Label266: TLabel; btprodaceptar: TButton; Panel129: TPanel; Button26: TButton; listaiconos: TImageList; Button27: TButton; Button18: TButton; Shape27: TShape; Label269: TLabel; Shape28: TShape; DBEdit186: TDBEdit; DBEdit187: TDBEdit; DBEdit188: TDBEdit; Label270: TLabel; Label271: TLabel; Label272: TLabel; Label273: TLabel; DBEdit189: TDBEdit; DBCheckBox34: TDBCheckBox; DBCheckBox35: TDBCheckBox; DBCheckBox36: TDBCheckBox; DBText7: TDBText; Panel130: TPanel; DBEdit191: TDBEdit; Label275: TLabel; Label276: TLabel; DBLookupComboBox6: TDBLookupComboBox; Label277: TLabel; Panel131: TPanel; DBGrid65: TDBGrid; Label191: TLabel; DBCheckBox37: TDBCheckBox; Label286: TLabel; DBLookupComboBox8: TDBLookupComboBox; Panel132: TPanel; bmpanadir: TButton; bmpmodificar: TButton; bmpborrar: TButton; bmpcancelar: TButton; bmpaceptar: TButton; Panel133: TPanel; Label121: TLabel; Label122: TLabel; Label126: TLabel; Label128: TLabel; Label123: TLabel; Label217: TLabel; DBEdit67: TDBEdit; DBEdit68: TDBEdit; DBImage3: TDBImage; DBEdit73: TDBEdit; DBCheckBox8: TDBCheckBox; DBMemo2: TDBMemo; DBCheckBox20: TDBCheckBox; DBEdit124: TDBEdit; DBCheckBox33: TDBCheckBox; DBCheckBox38: TDBCheckBox; Panelcompuestos: TPanel; DBGrid66: TDBGrid; bmpc_aceptar: TButton; bmpc_anyadir: TButton; bmpc_borrar: TButton; DBLookupComboBox9: TDBLookupComboBox; Label287: TLabel; DBLookupComboBox10: TDBLookupComboBox; Label288: TLabel; Label289: TLabel; DBMemo4: TDBMemo; Ppartestrabajo: TTabSheet; DBGrid67: TDBGrid; Panel134: TPanel; Panel135: TPanel; Panel136: TPanel; Panel138: TPanel; Panel139: TPanel; CheckBox13: TCheckBox; CheckBox14: TCheckBox; CheckBox15: TCheckBox; Button28: TButton; Button29: TButton; Panel140: TPanel; DBGrid68: TDBGrid; Label290: TLabel; DBEdit193: TDBEdit; Label291: TLabel; DBLookupComboBox11: TDBLookupComboBox; Edit4: TEdit; Panel141: TPanel; DBGrid62: TDBGrid; Panel142: TPanel; chktodasmateriasprimas: TCheckBox; Panel143: TPanel; chktodosproductos: TCheckBox; Panel144: TPanel; chktodashoras: TCheckBox; Panel145: TPanel; chktodostrabajos: TCheckBox; Panel146: TPanel; chktodostrabajosalmacen: TCheckBox; Panel147: TPanel; Panel148: TPanel; chktodoscentroscoste: TCheckBox; Panel151: TPanel; Panel152: TPanel; chktodosalmacenes: TCheckBox; DBCheckBox40: TDBCheckBox; Presupuestos1: TMenuItem; FacturasProforma1: TMenuItem; Notas1: TMenuItem; clientes1: TMenuItem; DBEdit194: TDBEdit; Produccin1: TMenuItem; N8: TMenuItem; N9: TMenuItem; PageControl18: TPageControl; TabSheet2: TTabSheet; TabSheet16: TTabSheet; DBGrid69: TDBGrid; Panel153: TPanel; DBGrid70: TDBGrid; Button21: TButton; tfirmanominas: TImage; listaiconos2: TImageList; tfirmaproduccion: TImage; Controlhorario1: TMenuItem; Panel137: TPanel; Panel154: TPanel; Panel59: TPanel; Label149: TLabel; Label150: TLabel; Label160: TLabel; Label161: TLabel; DBEdit88: TDBEdit; DBEdit89: TDBEdit; finicio: TDateTimePicker; ffin: TDateTimePicker; DBEdit97: TDBEdit; DBEdit98: TDBEdit; Panel155: TPanel; Panel113: TPanel; Panel114: TPanel; beanadir: TButton; bemodificar: TButton; beborrar: TButton; becancelar: TButton; beaceptar: TButton; ArticulosComponentes1: TMenuItem; Label207: TLabel; DBEdit114: TDBEdit; Label208: TLabel; DBEdit115: TDBEdit; Label209: TLabel; DBEdit116: TDBEdit; DBCheckBox18: TDBCheckBox; DBCheckBox26: TDBCheckBox; xtempleadoside: TIntegerField; xtempleadosIRPF2: TFloatField; xtempleadosDESEMPLEO2: TFloatField; xtempleadosFORMACION2: TFloatField; xtempleadosseleccionado: TIntegerField; xtempleadoscodart: TWideStringField; xtempleadosmostrar: TIntegerField; chktodosempleados: TCheckBox; Panel115: TPanel; PdatosJornales: TPanel; Panel149: TPanel; btJnuevo: TButton; btJborrar: TButton; btJmodificar: TButton; btJguardar: TButton; btJcancelar: TButton; btJimprimir: TButton; btJexcel: TButton; fechajornales: TDateTimePicker; ljcentro: TDBLookupComboBox; ljtrabajo: TDBLookupComboBox; ljhora: TDBLookupComboBox; edjprecio: TEdit; edjhoras: TEdit; Label211: TLabel; Label212: TLabel; Label213: TLabel; Label214: TLabel; Label215: TLabel; Label216: TLabel; TabSheet17: TTabSheet; Button8: TButton; Button22: TButton; Pagedatos: TPageControl; TabSheet18: TTabSheet; TabSheet20: TTabSheet; TabSheet35: TTabSheet; TabSheet37: TTabSheet; Panel150: TPanel; Label100: TLabel; Label101: TLabel; Label102: TLabel; Label103: TLabel; Label104: TLabel; Label81: TLabel; Label82: TLabel; Label83: TLabel; Label84: TLabel; Label85: TLabel; Label86: TLabel; Label87: TLabel; Label89: TLabel; Label90: TLabel; Label91: TLabel; Label92: TLabel; Label178: TLabel; EmpActiva: TDBCheckBox; DBEdit40: TDBEdit; DBEdit41: TDBEdit; DBEdit42: TDBEdit; DBEdit43: TDBEdit; DBEdit44: TDBEdit; DBEdit45: TDBEdit; DBEdit46: TDBEdit; DBEdit47: TDBEdit; DBEdit48: TDBEdit; DBEdit49: TDBEdit; DBEdit50: TDBEdit; DBEdit58: TDBEdit; DBEdit59: TDBEdit; DBEdit60: TDBEdit; DBEdit61: TDBEdit; DBEdit62: TDBEdit; DBEdit102: TDBEdit; Label296: TLabel; Label297: TLabel; Label298: TLabel; Label299: TLabel; DBCheckBox27: TDBCheckBox; DBCheckBox28: TDBCheckBox; DBCheckBox29: TDBCheckBox; DBCheckBox32: TDBCheckBox; DBCheckBox39: TDBCheckBox; DBEdit117: TDBEdit; DBEdit118: TDBEdit; DBEdit119: TDBEdit; DBCheckBox41: TDBCheckBox; tbuscarparcelas: TEdit; Proveedores1: TMenuItem; EntradasMateriales1: TMenuItem; Button30: TButton; DBLookupComboBox15: TDBLookupComboBox; Label300: TLabel; DBLookupComboBox16: TDBLookupComboBox; DBGrid57: TDBGrid; PageControl17: TPageControl; TabSheet38: TTabSheet; DBGrid58: TDBGrid; Panel156: TPanel; PageControl19: TPageControl; TabSheet39: TTabSheet; DBGrid71: TDBGrid; Panel157: TPanel; DBGrid72: TDBGrid; Button31: TButton; Button32: TButton; TabSheet40: TTabSheet; DBGrid73: TDBGrid; Panel158: TPanel; DBGrid74: TDBGrid; Button33: TButton; Button34: TButton; TabSheet41: TTabSheet; DBCheckBox42: TDBCheckBox; DBEdit81: TDBEdit; GruposFamilias1: TMenuItem; TiposdeImpuestos1: TMenuItem; Panel159: TPanel; Label301: TLabel; combocampanyas: TDBLookupComboBox; Panel78: TPanel; Label210: TLabel; tbuscarlotes: TEdit; SaveDialog1: TSaveDialog; CalibresCalidades1: TMenuItem; SociosProductores1: TMenuItem; Button15: TButton; Label188: TLabel; DBLookupComboBox17: TDBLookupComboBox; dsqsocios2: TDataSource; qsocios2: TZReadOnlyQuery; qsocios2id: TIntegerField; qsocios2ide: TIntegerField; Panel77: TPanel; Label302: TLabel; btLcancelar: TButton; btLmodificar: TButton; btlnuevo: TButton; btLguardar: TButton; Button35: TButton; btLImprimir: TButton; DBLookupComboBox18: TDBLookupComboBox; DBMemo3: TDBMemo; Label303: TLabel; dsqlotes: TDataSource; DBText16: TDBText; Paneldocumentos: TPanel; DialogLotes: TOpenDialog; Panel160: TPanel; btdimprimir: TButton; Label304: TLabel; btdborrar: TButton; btdnuevo: TButton; Panel161: TPanel; DBGrid34: TDBGrid; imgfoto: TImage; btdguardar: TButton; btdcancelar: TButton; dsdoclotes: TDataSource; btdmodificar: TButton; btdver: TButton; qsocios2pais: TWideStringField; informes: TfrxReport; informedb2: TfrxDBDataset; informedb3: TfrxDBDataset; informedb4: TfrxDBDataset; informedb5: TfrxDBDataset; informedb6: TfrxDBDataset; informedb7: TfrxDBDataset; Memo1: TMemo; btddescargar: TButton; Panel162: TPanel; Label280: TLabel; Label281: TLabel; Label282: TLabel; Label283: TLabel; Label284: TLabel; Label285: TLabel; DBText9: TDBText; DBText10: TDBText; DBText11: TDBText; DBText12: TDBText; DBText13: TDBText; DBText14: TDBText; DBText15: TDBText; Label292: TLabel; Label305: TLabel; DBText17: TDBText; Presentaciones1: TMenuItem; dsqparcelas2: TDataSource; qparcelas2: TZReadOnlyQuery; qparcelas2codpar: TWideStringField; qparcelas2empresa: TIntegerField; qparcelas2nombre: TWideStringField; qparcelas2propietario: TIntegerField; btVerdocumentos: TButton; Timer2: TTimer; DBLookupComboBox19: TDBLookupComboBox; Label306: TLabel; Panel82: TPanel; bteborrar: TButton; btAnuevo: TButton; btAguardar: TButton; bteModificar: TButton; btecancelar: TButton; Panel163: TPanel; limporteanticipo: TEdit; lopciones: TComboBox; lobservaciones: TEdit; fechaanticipo: TDateTimePicker; Label171: TLabel; Label138: TLabel; Label45: TLabel; Label44: TLabel; qparcelas2numero: TWideStringField; fechalote: TDateTimePicker; Listados1: TMenuItem; Entradassalidas: TMenuItem; Articulos1: TMenuItem; checktodos: TCheckBox; qempleadosseleccionado: TIntegerField; checktodos2: TCheckBox; bteimprimir: TButton; listaimpresion: TComboBox; dsqauxemp: TDataSource; qauxemp: TZReadOnlyQuery; qauxempid: TSmallintField; qauxempnif: TWideStringField; qauxempnombre: TWideStringField; qauxempdireccion: TWideStringField; qauxemppoblacion: TWideStringField; qauxempnumsegsocial: TWideStringField; qauxempfechaalta: TDateField; qauxempfechabaja: TDateField; gridplantillaext: TDBGrid; qauxempjorreales: TWideStringField; qauxempcausa: TWideStringField; qauxempd1: TWideStringField; qauxempd2: TWideStringField; qauxempd3: TWideStringField; qauxempd4: TWideStringField; qauxempd5: TWideStringField; qauxempd6: TWideStringField; qauxempd7: TWideStringField; qauxempd8: TWideStringField; qauxempd9: TWideStringField; qauxempd10: TWideStringField; qauxempd11: TWideStringField; qauxempd12: TWideStringField; qauxempd13: TWideStringField; qauxempd14: TWideStringField; qauxempd15: TWideStringField; qauxempd16: TWideStringField; qauxempd17: TWideStringField; qauxempd18: TWideStringField; qauxempd19: TWideStringField; qauxempd20: TWideStringField; qauxempd21: TWideStringField; qauxempd22: TWideStringField; qauxempd23: TWideStringField; qauxempd24: TWideStringField; qauxempd25: TWideStringField; qauxempd26: TWideStringField; qauxempd27: TWideStringField; qauxempd28: TWideStringField; qauxempd29: TWideStringField; qauxempd30: TWideStringField; qauxempd31: TWideStringField; gridplantillacomu: TDBGrid; Gruposdeempleados1: TMenuItem; qgrupostrabajadores: TZReadOnlyQuery; dsqgrupostrabajadores: TDataSource; listagrupos2: TDBLookupComboBox; dsqgrupostrabajadores2: TDataSource; qgrupostrabajadores2: TZReadOnlyQuery; qgrupostrabajadores2ide: TIntegerField; qgrupostrabajadores2id: TIntegerField; qgrupostrabajadores2descripcion: TWideStringField; qgrupostrabajadoreside: TIntegerField; qgrupostrabajadoresid: TIntegerField; qgrupostrabajadoresdescripcion: TWideStringField; listagrupos: TDBLookupComboBox; DBLookupComboBox12: TDBLookupComboBox; ltotalgrupo: TLabel; ltotalgrupo2: TLabel; ltotalgrupo3: TLabel; Panel15: TPanel; Panel167: TPanel; Panel168: TPanel; btatnuevo: TButton; btatborrar: TButton; btatmodificar: TButton; btatguardar: TButton; btatcancelar: TButton; btatimprimir: TButton; btatexcel: TButton; panticipos: TPanel; Label313: TLabel; Label318: TLabel; fechaanticipos: TDateTimePicker; edimporte: TEdit; edconcepto: TEdit; Label314: TLabel; Label315: TLabel; edformapago: TComboBox; listainformesanticipos: TComboBox; Formasdepago1: TMenuItem; Compras1: TMenuItem; Utilidades1: TMenuItem; RecalculoStocksdearticuloscomponentes1: TMenuItem; Comprobararticulosconstockbajo1: TMenuItem; N1: TMenuItem; EntradasEnvasados1: TMenuItem; Inventarios1: TMenuItem; ConfiguracinAlmacen1: TMenuItem; 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; Panel165: TPanel; Panel166: TPanel; Label73: TLabel; btedocborrar: TButton; btedocnuevo: TButton; btedocguardar: TButton; btedoccancelar: TButton; paneldocumentosempleados: TPanel; imageempleados: TImage; DBGrid75: TDBGrid; btedocver2: TButton; Memo2: TMemo; Button38: TButton; xtempleadosIMAGEN: TIntegerField; btedocver: TButton; OpenDialog1: TOpenDialog; Image2: TImage; Button1: TButton; temp_fotos: TZTable; dsempfotos: TDataSource; temp_fotoside: TIntegerField; temp_fotosidt: TIntegerField; temp_fotosimagen: TBlobField; qempleadoside: TIntegerField; Button2: TButton; Label74: TLabel; btedocmodificar: TButton; dsdocempleados: TDataSource; Button6: TButton; templeados: TZQuery; templeadoside: TIntegerField; templeadosID: TSmallintField; templeadosNIF: TWideStringField; templeadosnombre: TWideStringField; templeadosactivo: TIntegerField; templeadosNOMBRECORTO: TWideStringField; templeadosAPELLIDOS: TWideStringField; templeadosDIRECCION: TWideStringField; templeadosCP: TWideStringField; templeadosPOBLACION: TWideStringField; templeadosPROVINCIA: TWideStringField; templeadosFECHANACIMIENTO: TDateField; templeadosPAISNAC: TWideStringField; templeadosNACIONALIDAD: TWideStringField; templeadosSEXO: TWideStringField; templeadosCBIBAN: TWideStringField; templeadosCBBANCO: TWideStringField; templeadosCBOFICINA: TWideStringField; templeadosCBDC: TWideStringField; templeadosCBCC: TWideStringField; templeadosPAGARPORBANCO: TIntegerField; templeadosTELEFONO1: TWideStringField; templeadosTELEFONO2: TWideStringField; templeadosTELEFONO3: TWideStringField; templeadosTELEFONO4: TWideStringField; templeadosREGIMEN_COT: TWideStringField; templeadosNUMSEGSOCIAL: TWideStringField; templeadosIRPF: TFloatField; templeadosIRPF2: TFloatField; templeadosDESEMPLEO: TFloatField; templeadosDESEMPLEO2: TFloatField; templeadosFORMACION: TFloatField; templeadosFORMACION2: TFloatField; templeadosIMAGEN: TIntegerField; templeadosOBSERVACIONES: TWideStringField; templeadosFECHAALTA: TDateField; templeadosFECHABAJA: TDateField; templeadosFIJO: TSmallintField; templeadosFIJODISCONTINUO: TSmallintField; templeadosTEMPORAL: TSmallintField; templeadosCONTINGENCIAS: TFloatField; templeadosempresa: TIntegerField; templeadosseleccionado: TIntegerField; templeadoscodart: TWideStringField; templeadosmostrar: TIntegerField; Label23: TLabel; DBEdit26: TDBEdit; Label75: TLabel; Label307: TLabel; DBEdit120: TDBEdit; Label308: TLabel; ControldeProduccindeAlmacen1: TMenuItem; frxPDFExport1: TfrxPDFExport; Label309: TLabel; DBLookupComboBox13: TDBLookupComboBox; DBText8: TDBText; qauxemptelefono1: TWideStringField; qsocios2nombre: TWideStringField; Balancedeventas1: TMenuItem; Puestosdetrabajo1: TMenuItem; Regmenesdecotizacin1: TMenuItem; DatosEmpleados1: TMenuItem; Empleados2: TMenuItem; N2: TMenuItem; Facturacin1: TMenuItem; CuentasBancarias1: TMenuItem; qarticulocomision: TZReadOnlyQuery; dsqarticulocomision: TDataSource; dsqarticulotransporte: TDataSource; qarticulotransporte: TZReadOnlyQuery; dsempresa: TDataSource; Panel169: TPanel; Label105: TLabel; Label162: TLabel; Label163: TLabel; Label196: TLabel; Label202: TLabel; Label274: TLabel; DBEdit100: TDBEdit; DBEdit63: TDBEdit; DBEdit99: TDBEdit; DBEdit103: TDBEdit; DBEdit109: TDBEdit; DBEdit190: TDBEdit; DBCheckBox43: TDBCheckBox; Panel170: TPanel; Label93: TLabel; Label94: TLabel; combocomision: TDBLookupComboBox; combotransporte: TDBLookupComboBox; DBText18: TDBText; DBText19: TDBText; Panel116: TPanel; Panel171: TPanel; Label195: TLabel; BTSNCANCELAR: TButton; BTSNMODIFICAR: TButton; BTSNBORRAR: TButton; btSNnuevo: TButton; btSNguardar: TButton; DBGrid56: TDBGrid; qarticulocomisionidempresa: TIntegerField; qarticulocomisionid: TIntegerField; qarticulocomisioncodigo: TWideStringField; qarticulocomisiondescripcion: TWideStringField; qarticulocomisionfamilia: TIntegerField; qarticulocomisionprovhab: TIntegerField; qarticulocomisiontipoiva: TIntegerField; qarticulocomisionpreciocoste: TFloatField; qarticulocomisionmargen: TFloatField; qarticulocomisionbeneficio: TFloatField; qarticulocomisionpvp: TFloatField; qarticulocomisionstock: TFloatField; qarticulocomisionult_preciocompra: TFloatField; qarticulocomisionfacturable: TIntegerField; qarticulocomisionobservaciones: TWideStringField; qarticulocomisionimagen: TBlobField; qarticulocomisionactivo: TIntegerField; qarticulocomisionvalor_almacen: TFloatField; qarticulocomisionstock_minimo: TFloatField; qarticulocomisionavisar_stock: TIntegerField; qarticulocomisioncontrolar_traza: TIntegerField; qarticulocomisionpeso: TFloatField; qarticulocomisiondescripcion_doc: TWideStringField; qarticulocomisioninventariable: TIntegerField; qarticulocomisionactualizar_stock: TIntegerField; qarticulotransporteidempresa: TIntegerField; qarticulotransporteid: TIntegerField; qarticulotransportecodigo: TWideStringField; qarticulotransportedescripcion: TWideStringField; qarticulotransportefamilia: TIntegerField; qarticulotransporteprovhab: TIntegerField; qarticulotransportetipoiva: TIntegerField; qarticulotransportepreciocoste: TFloatField; qarticulotransportemargen: TFloatField; qarticulotransportebeneficio: TFloatField; qarticulotransportepvp: TFloatField; qarticulotransportestock: TFloatField; qarticulotransporteult_preciocompra: TFloatField; qarticulotransportefacturable: TIntegerField; qarticulotransporteobservaciones: TWideStringField; qarticulotransporteimagen: TBlobField; qarticulotransporteactivo: TIntegerField; qarticulotransportevalor_almacen: TFloatField; qarticulotransportestock_minimo: TFloatField; qarticulotransporteavisar_stock: TIntegerField; qarticulotransportecontrolar_traza: TIntegerField; qarticulotransportepeso: TFloatField; qarticulotransportedescripcion_doc: TWideStringField; qarticulotransporteinventariable: TIntegerField; qarticulotransporteactualizar_stock: TIntegerField; gcrcheck: TDBCheckBox; IdSSLIOHandlerSocketOpenSSL1: TIdSSLIOHandlerSocketOpenSSL; Button13: TButton; Label95: TLabel; DBEdit51: TDBEdit; Label96: TLabel; combootros: TDBLookupComboBox; DBText20: TDBText; dsqarticulosotros: TDataSource; qarticulosotros: TZReadOnlyQuery; IntegerField1: TIntegerField; IntegerField2: TIntegerField; WideStringField1: TWideStringField; WideStringField2: TWideStringField; IntegerField3: TIntegerField; IntegerField4: TIntegerField; IntegerField5: TIntegerField; FloatField1: TFloatField; FloatField2: TFloatField; FloatField3: TFloatField; FloatField4: TFloatField; FloatField5: TFloatField; FloatField6: TFloatField; IntegerField6: TIntegerField; WideStringField3: TWideStringField; BlobField1: TBlobField; IntegerField7: TIntegerField; FloatField7: TFloatField; FloatField8: TFloatField; IntegerField8: TIntegerField; IntegerField9: TIntegerField; FloatField9: TFloatField; WideStringField4: TWideStringField; IntegerField10: TIntegerField; IntegerField11: TIntegerField; Button23: TButton; Button36: TButton; DBCheckBox44: TDBCheckBox; qempresa: TZReadOnlyQuery; qempresaid: TIntegerField; qempresacif: TWideStringField; qempresanombre: TWideStringField; qempresadireccion: TWideStringField; qempresacodpost: TWideStringField; qempresapoblacion: TWideStringField; qempresaprovincia: TWideStringField; qempresaemail: TWideStringField; qempresatelefono1: TWideStringField; qempresatelefono2: TWideStringField; qempresacontacto: TWideStringField; qempresacontingenciacomfij: TFloatField; qempresasalariobasedia: TFloatField; qempresacontingenciasdia: TFloatField; qempresairpf: TFloatField; qempresadesempleo: TFloatField; qempresaformacion: TFloatField; qempresacontingencias: TFloatField; qempresairpf2: TFloatField; qempresadesempleo2: TFloatField; qempresaformacion2: TFloatField; qempresacontingencias2: TFloatField; qempresacc_iban: TWideStringField; qempresacc_entidad: TWideStringField; qempresacc_oficina: TWideStringField; qempresacc_dc: TWideStringField; qempresacc_cc: TWideStringField; qempresaajusteentrada: TIntegerField; qempresaajustesalida: TIntegerField; qempresaporcbloqueo: TIntegerField; qempresaactive: TIntegerField; qempresault_envio: TIntegerField; qempresaregistro_sanitario: TWideStringField; qempresacoste_kg_gen: TFloatField; qempresaporc_segsocial: TFloatField; qempresaprecio_venta_desperdicios: TFloatField; qempresavercodtrazabilidad: TIntegerField; qempresacodcomision: TWideStringField; qempresacodtransporte: TWideStringField; qempresacc_bic: TWideStringField; qempresacodotros: TWideStringField; qempresaavisarstock: TIntegerField; qaux2: TZReadOnlyQuery; Formatosdeimpresin1: TMenuItem; DBEdit52: TDBEdit; Panel88: TPanel; Label97: TLabel; DBEdit53: TDBEdit; Label98: TLabel; DBEdit54: TDBEdit; Label179: TLabel; DBEdit56: TDBEdit; Label180: TLabel; DBEdit57: TDBEdit; Label243: TLabel; DBEdit121: TDBEdit; Label293: TLabel; DBEdit122: TDBEdit; Label294: TLabel; DBEdit123: TDBEdit; Label295: TLabel; DBEdit143: TDBEdit; Label310: TLabel; Controldecalidad1: TMenuItem; Expediciones1: TMenuItem; Vidacomercial1: TMenuItem; Controladoresdecalidad1: TMenuItem; Controldeutensilios1: TMenuItem; Materiaprima1: TMenuItem; DBGrid39: TDBGrid; Panel89: TPanel; Panel90: TPanel; DBLookupComboBox14: TDBLookupComboBox; Label311: TLabel; Label312: TLabel; Label316: TLabel; Edit3: TEdit; Edit5: TEdit; Button37: TButton; dscontrolqpartesdiarios: TDataSource; Label319: TLabel; DBEdit195: TDBEdit; Label320: TLabel; DBEdit196: TDBEdit; Label321: TLabel; DBEdit197: TDBEdit; Regularizarmaterialauxiliar1: TMenuItem; qaux3: TZReadOnlyQuery; qregularizar: TZQuery; Label99: TLabel; DBEdit55: TDBEdit; Label317: TLabel; Label322: TLabel; DBEdit180: TDBEdit; Label323: TLabel; DBEdit198: TDBEdit; Label324: TLabel; Button39: TButton; DBImage1: TDBImage; Label325: TLabel; Button40: TButton; Button41: TButton; Button42: TButton; OpenPictureDialog1: TOpenPictureDialog; imgfotoe: TImage; Label326: TLabel; DBEdit199: TDBEdit; Label327: TLabel; DBEdit200: TDBEdit; Label328: TLabel; DBEdit201: TDBEdit; Label329: TLabel; Consumosdemateriales1: TMenuItem; ratamientosAbonados1: TMenuItem; ratamientos1: TMenuItem; N3: TMenuItem; tratamientosBase1: TMenuItem; AbonadosBase1: TMenuItem; Plagasyenfermedades1: TMenuItem; Materiasactivas1: TMenuItem; Librosdecampo1: TMenuItem; Consumosygastos1: TMenuItem; Consumosygastos2: TMenuItem; Label330: TLabel; combofamilias: TDBLookupComboBox; qfamilias: TZReadOnlyQuery; qfamiliasidempresa: TIntegerField; qfamiliasid: TIntegerField; qfamiliasdescripcion: TWideStringField; dsqfamilias: TDataSource; OpenDialog2: TOpenDialog; ConectarconSistemPin1: TMenuItem; informedb: TfrxDBDataset; INFEMPRESA: TfrxDBDataset; DBCheckBox45: TDBCheckBox; DBEdit202: TDBEdit; N10: TMenuItem; Utensilios1: TMenuItem; Controlcmarasfrigorificas1: TMenuItem; Bsculas1: TMenuItem; Controldebsculas1: TMenuItem; aquillas1: TMenuItem; DBCheckBox46: TDBCheckBox; DBCheckBox47: TDBCheckBox; DBCheckBox48: TDBCheckBox; Button43: TButton; Button44: TButton; dsqalmacenes: TDataSource; Panel92: TPanel; DBGrid40: TDBGrid; Button45: TButton; Button46: TButton; DBGrid41: TDBGrid; Label278: TLabel; DBEdit192: TDBEdit; Button47: TButton; Button48: TButton; qtipohora: TZReadOnlyQuery; tjornalesempresa: TIntegerField; qtipohoracodart: TWideStringField; qtipohoraprecio: TFloatField; qtipohoradescrip: TWideStringField; Panel93: TPanel; Label279: TLabel; Label331: TLabel; Label332: TLabel; cdesde: TDateTimePicker; chasta: TDateTimePicker; Button49: TButton; Button50: TButton; Button51: TButton; dsqgastosparcela: TDataSource; qgastosparcela: TZReadOnlyQuery; qgastosparcelaparcela: TWideStringField; qgastosparcelaCONCEPTO: TWideStringField; qgastosparcelacantidad: TFloatField; qgastosparcelatotal: TFloatField; qgastosparceladescripcion: TWideStringField; DBGrid42: TDBGrid; Panel94: TPanel; Panel95: TPanel; Label58: TLabel; Label333: TLabel; Label334: TLabel; qproduccionmesas: TZReadOnlyQuery; qproduccionmesasmesa: TWideStringField; qproduccionproducto: TZReadOnlyQuery; qproduccionmatprima: TZReadOnlyQuery; qproduccionproductoproducto: TWideStringField; qproduccionmatprimamateria_prima: TWideStringField; dsmesas: TDataSource; dsproductos: TDataSource; dsmatprima: TDataSource; comboprodmesas: TDBLookupComboBox; comboprodmprimas: TDBLookupComboBox; comboprodproducto: TDBLookupComboBox; Button52: TButton; DBEdit203: TDBEdit; Label335: TLabel; Label336: TLabel; DBEdit204: TDBEdit; Label337: TLabel; DBEdit205: TDBEdit; Label338: TLabel; DBEdit206: TDBEdit; Label339: TLabel; DBEdit207: TDBEdit; qparcelas2tiene_gg: TIntegerField; qparcelas2sello_gg: TWideStringField; qparcelas2tiene_dop: TIntegerField; qparcelas2sello_dop: TWideStringField; qparcelas2tiene_igp: TIntegerField; qparcelas2sello_igp: TWideStringField; qparcelas2tiene_ifs: TIntegerField; qparcelas2sello_ifs: TWideStringField; qparcelas2tiene_brc: TIntegerField; qparcelas2sello_brc: TWideStringField; DBLookupComboBox7: TDBLookupComboBox; qlotesdia: TZReadOnlyQuery; dsqlotesdia: TDataSource; qlotesdiaidempresa: TIntegerField; qlotesdiacodigo: TIntegerField; qlotesdiaPARCELA: TWideStringField; qlotesdiaPRODUCTOR: TWideStringField; qlotesdiaMPRIMA: TWideStringField; qcostesrestosdia: TZReadOnlyQuery; qcostesrestosdiafecha: TDateField; qcostesrestosdiafechalote: TDateField; qcostesrestosdialote: TIntegerField; qcostesrestosdiabultos: TFloatField; qcostesrestosdiapeso_mprima: TFloatField; qcostesrestosdiacosto_mprima: TFloatField; qcostesrestosdiacostecosechar: TFloatField; qcostesrestosdiacostetotal: TFloatField; Button53: TButton; DBEdit208: TDBEdit; DBEdit209: TDBEdit; DBEdit210: TDBEdit; DBEdit211: TDBEdit; Label340: TLabel; Label341: TLabel; DBEdit212: TDBEdit; DBEdit213: TDBEdit; DBEdit214: TDBEdit; DBEdit215: TDBEdit; Label342: TLabel; Label343: TLabel; DBEdit216: TDBEdit; Label344: TLabel; Estadodestocks1: TMenuItem; Label345: TLabel; lnobservaciones: TEdit; tjornalesobservaciones: TWideStringField; EPIS1: TMenuItem; Button54: TButton; qempleadosnif: TWideStringField; qasistencia: TZQuery; dsqasistencia: TDataSource; gridasistencia: TDBGrid; qasistenciaide: TIntegerField; qasistenciaidt: TIntegerField; qasistenciaanyo: TIntegerField; qasistenciames: TWideStringField; qasistencianif: TWideStringField; qasistencianombre: TWideStringField; qasistenciad1: TWideStringField; qasistenciad2: TWideStringField; qasistenciad3: TWideStringField; qasistenciad4: TWideStringField; qasistenciad5: TWideStringField; qasistenciad6: TWideStringField; qasistenciad7: TWideStringField; qasistenciad8: TWideStringField; qasistenciad9: TWideStringField; qasistenciad10: TWideStringField; qasistenciad11: TWideStringField; qasistenciad12: TWideStringField; qasistenciad13: TWideStringField; qasistenciad14: TWideStringField; qasistenciad15: TWideStringField; qasistenciad16: TWideStringField; qasistenciad17: TWideStringField; qasistenciad18: TWideStringField; qasistenciad19: TWideStringField; qasistenciad20: TWideStringField; qasistenciad21: TWideStringField; qasistenciad22: TWideStringField; qasistenciad23: TWideStringField; qasistenciad24: TWideStringField; qasistenciad25: TWideStringField; qasistenciad26: TWideStringField; qasistenciad27: TWideStringField; qasistenciad28: TWideStringField; qasistenciad29: TWideStringField; qasistenciad30: TWideStringField; qasistenciad31: TWideStringField; qasistenciafechaalta: TDateField; qasistenciafechabaja: TDateField; qasistencianombre2: TWideStringField; Label346: TLabel; Label347: TLabel; Label348: TLabel; hdesde: TComboBox; hhasta: TComboBox; Button55: TButton; Memo3: TMemo; Label349: TLabel; DBEdit217: TDBEdit; N11: TMenuItem; Boquillas1: TMenuItem; Maquinria1: TMenuItem; CondicionesMeteorolgicas1: TMenuItem; TabSheet21: TTabSheet; Panel96: TPanel; Button57: TButton; DBGrid43: TDBGrid; qlistadoporgrupo: TZReadOnlyQuery; qlistadoporgrupofecha: TDateField; qlistadoporgrupoparcela: TWideStringField; qlistadoporgrupotypework: TWideStringField; qlistadoporgrupototalhoras: TFloatField; qlistadoporgrupoprecio: TFloatField; qlistadoporgrupototal: TFloatField; qlistadoporgrupogrupo: TWideStringField; dsqlistadoporgrupo: TDataSource; Label350: TLabel; Label351: TLabel; vfechadesdelg: TDateTimePicker; vfechahastalg: TDateTimePicker; Button58: TButton; tbjornadas: TTabSheet; Panel97: TPanel; Label352: TLabel; Label353: TLabel; Button56: TButton; vdesdejornadas: TDateTimePicker; vhastajornadas: TDateTimePicker; Button59: TButton; DBGrid76: TDBGrid; dsqasistir: TDataSource; qticados: TZQuery; dsqticados: TDataSource; qticadosidt: TIntegerField; qticadosfecha: TDateField; qticadosnombre: TWideStringField; qticadosnif: TWideStringField; qticadoside: TIntegerField; qasistir: TZQuery; qasistiride: TIntegerField; qasistiridt: TIntegerField; qasistiranyo: TIntegerField; qasistirmes: TWideStringField; qasistirnif: TWideStringField; qasistirnombre: TWideStringField; qasistird1: TWideStringField; qasistird2: TWideStringField; qasistird3: TWideStringField; qasistird4: TWideStringField; qasistird5: TWideStringField; qasistird6: TWideStringField; qasistird7: TWideStringField; qasistird8: TWideStringField; qasistird9: TWideStringField; qasistird10: TWideStringField; qasistird11: TWideStringField; qasistird12: TWideStringField; qasistird13: TWideStringField; qasistird14: TWideStringField; qasistird15: TWideStringField; qasistird16: TWideStringField; qasistird17: TWideStringField; qasistird18: TWideStringField; qasistird19: TWideStringField; qasistird20: TWideStringField; qasistird21: TWideStringField; qasistird22: TWideStringField; qasistird23: TWideStringField; qasistird24: TWideStringField; qasistird25: TWideStringField; qasistird26: TWideStringField; qasistird27: TWideStringField; qasistird28: TWideStringField; qasistird29: TWideStringField; qasistird30: TWideStringField; qasistird31: TWideStringField; qasistirfechaalta: TDateField; qasistirfechabaja: TDateField; qasistirnombre2: TWideStringField; Envasadoscampovariedad1: TMenuItem; Consumosdefitosanitarios1: TMenuItem; Consumosabonos1: TMenuItem; Stockdealmacen1: TMenuItem; procedure BSalirClick(Sender: TObject); procedure PEmpleadosClick(Sender: TObject); procedure qempleadosBeforeOpen(DataSet: TDataSet); procedure ZReadOnlyQuery1BeforeOpen(DataSet: TDataSet); procedure fbajaCloseUp(Sender: TObject); procedure dsqtrabajadoresDataChange(Sender: TObject; Field: TField); procedure btinsertarClick(Sender: TObject); procedure TanyoChange(Sender: TObject); procedure TMESChange(Sender: TObject); procedure TESTADOChange(Sender: TObject); procedure DBGrid3CellClick(Column: TColumn); procedure dstrabajadoresStateChange(Sender: TObject); procedure Button3Click(Sender: TObject); procedure faltaCloseUp(Sender: TObject); procedure DBMemo1Exit(Sender: TObject); procedure Button4Click(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure bmodificarjornalesClick(Sender: TObject); procedure bborrarjornalesClick(Sender: TObject); procedure DBGrid2CellClick(Column: TColumn); procedure baceptarClick(Sender: TObject); procedure BtEmpleadosClick(Sender: TObject); procedure Button5Click(Sender: TObject); procedure lprecioEnter(Sender: TObject); procedure FormShow(Sender: TObject); procedure BtjornalesClick(Sender: TObject); procedure DBGrid4DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure btproduccionClick(Sender: TObject); procedure baceptarempleadosClick(Sender: TObject); procedure bcancelarempleadosClick(Sender: TObject); procedure bcancelarjornalClick(Sender: TObject); procedure dsqtipohoraDataChange(Sender: TObject; Field: TField); procedure Vaciar2Click(Sender: TObject); procedure VaciarClick(Sender: TObject); procedure DBGrid4CellClick(Column: TColumn); procedure DBGrid2DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBGrid5CellClick(Column: TColumn); procedure DBGrid5DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure calendarionotasClick(Sender: TObject); procedure btAgendaClick(Sender: TObject); procedure btempresaClick(Sender: TObject); procedure btJimprimirClick(Sender: TObject); procedure btvalorarClick(Sender: TObject); procedure tmes2Change(Sender: TObject); procedure DBGrid3DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBEdit8Exit(Sender: TObject); procedure DBEdit27Exit(Sender: TObject); procedure bpranadirClick(Sender: TObject); procedure bprcancelarClick(Sender: TObject); procedure bpraceptarClick(Sender: TObject); procedure bprmodificarClick(Sender: TObject); procedure bprborrarClick(Sender: TObject); procedure bmpanadirClick(Sender: TObject); procedure bmpmodificarClick(Sender: TObject); procedure bmpborrarClick(Sender: TObject); procedure bmpcancelarClick(Sender: TObject); procedure bmpaceptarClick(Sender: TObject); procedure bthanadirClick(Sender: TObject); procedure bthmodificarClick(Sender: TObject); procedure bthborrarClick(Sender: TObject); procedure bthcancelarClick(Sender: TObject); procedure bthaceptarClick(Sender: TObject); procedure tbuscarChange(Sender: TObject); procedure ltipohoraExit(Sender: TObject); procedure bttanadirClick(Sender: TObject); procedure bttmodificarClick(Sender: TObject); procedure bttborrarClick(Sender: TObject); procedure bttcancelarClick(Sender: TObject); procedure bttaceptarClick(Sender: TObject); procedure btaanadirClick(Sender: TObject); procedure btamodificarClick(Sender: TObject); procedure btacancelarClick(Sender: TObject); procedure btaaceptarClick(Sender: TObject); procedure btaborrarClick(Sender: TObject); procedure fprohastaChange(Sender: TObject); procedure dsqmesasDataChange(Sender: TObject; Field: TField); procedure Timer1Timer(Sender: TObject); procedure fprodesdeChange(Sender: TObject); procedure DBGrid19DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBGrid19DblClick(Sender: TObject); procedure Button7Click(Sender: TObject); procedure DBCheckBox16MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure DBCheckBox15MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure DBCheckBox14MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure DBCheckBox13MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure PageproduccionChange(Sender: TObject); procedure btcontrolprodcerrarClick(Sender: TObject); procedure Button16Click(Sender: TObject); procedure Button15Click(Sender: TObject); procedure btcontrolproduccionClick(Sender: TObject); procedure bccanadirClick(Sender: TObject); procedure bccmodificarClick(Sender: TObject); procedure bccborrarClick(Sender: TObject); procedure finicioCloseUp(Sender: TObject); procedure ffinCloseUp(Sender: TObject); procedure bcanadirClick(Sender: TObject); procedure bcmodificarClick(Sender: TObject); procedure bcborrarClick(Sender: TObject); procedure bccancelarClick(Sender: TObject); procedure bcaceptarClick(Sender: TObject); procedure bccaceptarClick(Sender: TObject); procedure bcccancelarClick(Sender: TObject); procedure beanadirClick(Sender: TObject); procedure bemodificarClick(Sender: TObject); procedure beborrarClick(Sender: TObject); procedure becancelarClick(Sender: TObject); procedure beaceptarClick(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure nomlhdesdeChange(Sender: TObject); procedure DBGrid26DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBGrid26CellClick(Column: TColumn); procedure DBGrid25DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBGrid25CellClick(Column: TColumn); procedure CheckBox7Click(Sender: TObject); procedure CheckBox8Click(Sender: TObject); procedure Button10Click(Sender: TObject); procedure Button9Click(Sender: TObject); procedure nomlttdesdeChange(Sender: TObject); procedure DBGrid29CellClick(Column: TColumn); procedure DBGrid29DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure CheckBox9Click(Sender: TObject); procedure CheckBox10Click(Sender: TObject); procedure DBGrid28CellClick(Column: TColumn); procedure DBGrid28DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure CheckBox11Click(Sender: TObject); procedure DBGrid7CellClick(Column: TColumn); procedure DBGrid7DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure Button11Click(Sender: TObject); procedure Button14Click(Sender: TObject); procedure Button12Click(Sender: TObject); procedure BTLaceptarClick(Sender: TObject); procedure pagnomfechahastaChange(Sender: TObject); procedure pagnomfechadesdeChange(Sender: TObject); procedure Panel71Click(Sender: TObject); procedure Nominaspag4Enter(Sender: TObject); procedure Button17Click(Sender: TObject); procedure PageNominasChange(Sender: TObject); procedure nomltthastaChange(Sender: TObject); procedure CheckBox12Click(Sender: TObject); procedure Button18Click(Sender: TObject); procedure bttrazabilidadClick(Sender: TObject); procedure BTLNuevoClick(Sender: TObject); procedure BTLcancelarClick(Sender: TObject); procedure dlotesfcaducidadExit(Sender: TObject); procedure dlotescodigoExit(Sender: TObject); procedure dlotesftrabajoExit(Sender: TObject); procedure dlotesfechaetiquetaExit(Sender: TObject); procedure BTLModificarClick(Sender: TObject); procedure btexpedicionesClick(Sender: TObject); procedure PageDatosEmpresaChange(Sender: TObject); procedure baanadirClick(Sender: TObject); procedure bamodificarClick(Sender: TObject); procedure baborrarClick(Sender: TObject); procedure bacancelarClick(Sender: TObject); procedure baaceptarClick(Sender: TObject); procedure bteaanadirClick(Sender: TObject); procedure bteamodificarClick(Sender: TObject); procedure bteaborrarClick(Sender: TObject); procedure bteacancelarClick(Sender: TObject); procedure bteaaceptarClick(Sender: TObject); procedure btactualizarClick(Sender: TObject); procedure Button19Click(Sender: TObject); procedure btJexcelClick(Sender: TObject); procedure Button21Click(Sender: TObject); procedure Button20Click(Sender: TObject); procedure btactualizarempleadosnominasClick(Sender: TObject); procedure Button24Click(Sender: TObject); procedure DBGrid44DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure btcerrarClick(Sender: TObject); procedure bticierreClick(Sender: TObject); procedure DBGrid60DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure bteimprimirClick(Sender: TObject); procedure DBGrid32DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBGrid32CellClick(Column: TColumn); procedure listaanyosChange(Sender: TObject); procedure listamesesChange(Sender: TObject); procedure Button25Click(Sender: TObject); procedure DBGrid33DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBEdit145Exit(Sender: TObject); procedure PageproduccionEnter(Sender: TObject); procedure btprodaceptarClick(Sender: TObject); procedure Button26Click(Sender: TObject); procedure Button27Click(Sender: TObject); procedure DBGrid59DblClick(Sender: TObject); procedure DBLookupComboBox7CloseUp(Sender: TObject); procedure DBGrid60DblClick(Sender: TObject); procedure Button23Click(Sender: TObject); procedure DBGrid68DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure Button28Click(Sender: TObject); procedure bmpc_anyadirClick(Sender: TObject); procedure bmpc_aceptarClick(Sender: TObject); procedure bmpc_borrarClick(Sender: TObject); procedure DBGrid21Exit(Sender: TObject); procedure DBGrid38DblClick(Sender: TObject); procedure DBGrid36DblClick(Sender: TObject); procedure DBGrid55DblClick(Sender: TObject); procedure chktodosproductosClick(Sender: TObject); procedure chktodasmateriasprimasClick(Sender: TObject); procedure chktodashorasClick(Sender: TObject); procedure chktodostrabajosClick(Sender: TObject); procedure chktodostrabajosalmacenClick(Sender: TObject); procedure chktodoscentroscosteClick(Sender: TObject); procedure chktodosalmacenesClick(Sender: TObject); procedure chktodosenvasesalmacenClick(Sender: TObject); procedure Clientes1Click(Sender: TObject); procedure EnvasesAlmacen1Click(Sender: TObject); procedure PedidosClientes1Click(Sender: TObject); procedure Salir1Click(Sender: TObject); procedure Button29Click(Sender: TObject); procedure DBGrid68DblClick(Sender: TObject); procedure DBGrid33DblClick(Sender: TObject); procedure Controlhorario1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ArticulosComponentes1Click(Sender: TObject); procedure DBEdit116Enter(Sender: TObject); procedure tbuscarlotesChange(Sender: TObject); procedure tbuscarnominasChange(Sender: TObject); procedure chktodosempleadosClick(Sender: TObject); procedure Button8Click(Sender: TObject); procedure Button22Click(Sender: TObject); procedure PageDatosEmpresaEnter(Sender: TObject); procedure btSNnuevoClick(Sender: TObject); procedure BTSNBORRARClick(Sender: TObject); procedure BTSNMODIFICARClick(Sender: TObject); procedure btSNguardarClick(Sender: TObject); procedure BTSNCANCELARClick(Sender: TObject); procedure DBGrid46DblClick(Sender: TObject); procedure DBGrid69DblClick(Sender: TObject); procedure tbuscarparcelasChange(Sender: TObject); procedure Proveedores1Click(Sender: TObject); procedure EntradasMateriales1Click(Sender: TObject); procedure Button30Click(Sender: TObject); procedure TiposdeImpuestos1Click(Sender: TObject); procedure GruposFamilias1Click(Sender: TObject); procedure CalibresCalidades1Click(Sender: TObject); procedure SociosProductores1Click(Sender: TObject); procedure btPnuevoClick(Sender: TObject); procedure btMmodificarClick(Sender: TObject); procedure btLguardarClick(Sender: TObject); procedure btPcancelarClick(Sender: TObject); procedure btLImprimirClick(Sender: TObject); procedure Button35Click(Sender: TObject); procedure dsqlotesStateChange(Sender: TObject); procedure btdnuevoClick(Sender: TObject); procedure dsdoclotesStateChange(Sender: TObject); procedure btdguardarClick(Sender: TObject); procedure dsdoclotesDataChange(Sender: TObject; Field: TField); procedure btdverClick(Sender: TObject); procedure btdmodificarClick(Sender: TObject); procedure btdborrarClick(Sender: TObject); procedure btdcancelarClick(Sender: TObject); procedure imgfotoClick(Sender: TObject); procedure DBLookupComboBox18Exit(Sender: TObject); procedure btddescargarClick(Sender: TObject); procedure Presentaciones1Click(Sender: TObject); procedure dsqsocios2DataChange(Sender: TObject; Field: TField); procedure btVerdocumentosClick(Sender: TObject); procedure Timer2Timer(Sender: TObject); procedure MateriasPrimas1Click(Sender: TObject); procedure btEnuevoClick(Sender: TObject); procedure bteborrarClick(Sender: TObject); procedure bteModificarClick(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure fechaloteCloseUp(Sender: TObject); procedure fechaloteEnter(Sender: TObject); procedure checktodosClick(Sender: TObject); procedure DBGrid64DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBGrid64CellClick(Column: TColumn); procedure btJnuevoClick(Sender: TObject); procedure btJguardarClick(Sender: TObject); procedure ljhoraCloseUp(Sender: TObject); procedure btJborrarClick(Sender: TObject); procedure btJmodificarClick(Sender: TObject); procedure btJcancelarClick(Sender: TObject); procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBGrid1CellClick(Column: TColumn); procedure checktodos2Click(Sender: TObject); procedure Gruposdeempleados1Click(Sender: TObject); procedure DBEdit9Exit(Sender: TObject); procedure listagrupos2CloseUp(Sender: TObject); procedure AlbaranesClientes1Click(Sender: TObject); procedure DBGrid1TitleClick(Column: TColumn); procedure DBGrid64TitleClick(Column: TColumn); procedure DBLookupComboBox12CloseUp(Sender: TObject); procedure FacturasClientes1Click(Sender: TObject); procedure qempleadosAfterOpen(DataSet: TDataSet); procedure btatnuevoClick(Sender: TObject); procedure btatmodificarClick(Sender: TObject); procedure btatguardarClick(Sender: TObject); procedure btatborrarClick(Sender: TObject); procedure btatcancelarClick(Sender: TObject); procedure btatexcelClick(Sender: TObject); procedure btatimprimirClick(Sender: TObject); procedure EntradassalidasClick(Sender: TObject); procedure DBGrid5TitleClick(Column: TColumn); procedure DBGrid4TitleClick(Column: TColumn); procedure Formasdepago1Click(Sender: TObject); procedure Articulos1Click(Sender: TObject); procedure Compras1Click(Sender: TObject); procedure RecalculoStocksdearticuloscomponentes1Click(Sender: TObject); procedure Comprobararticulosconstockbajo1Click(Sender: TObject); procedure EntradasEnvasados1Click(Sender: TObject); procedure Inventarios1Click(Sender: TObject); procedure ConfiguracinAlmacen1Click(Sender: TObject); procedure btedocnuevoClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure btedocverClick(Sender: TObject); procedure btedocmodificarClick(Sender: TObject); procedure btedocborrarClick(Sender: TObject); procedure btedocguardarClick(Sender: TObject); procedure btedoccancelarClick(Sender: TObject); procedure dsdocempleadosDataChange(Sender: TObject; Field: TField); procedure dsdocempleadosStateChange(Sender: TObject); procedure Button6Click(Sender: TObject); procedure TabJornalesEnter(Sender: TObject); procedure DBGrid8TitleClick(Column: TColumn); procedure ControldeProduccindeAlmacen1Click(Sender: TObject); procedure Balancedeventas1Click(Sender: TObject); procedure Puestosdetrabajo1Click(Sender: TObject); procedure Regmenesdecotizacin1Click(Sender: TObject); procedure Empleados2Click(Sender: TObject); procedure CuentasBancarias1Click(Sender: TObject); procedure dsempresaStateChange(Sender: TObject); procedure DBGrid56DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBGrid56CellClick(Column: TColumn); procedure Button13Click(Sender: TObject); procedure Button36Click(Sender: TObject); procedure Formatosdeimpresin1Click(Sender: TObject); procedure Regularizarmaterialauxiliar1Click(Sender: TObject); procedure Expediciones1Click(Sender: TObject); procedure Button42Click(Sender: TObject); procedure Button41Click(Sender: TObject); procedure Button40Click(Sender: TObject); procedure Consumosdemateriales1Click(Sender: TObject); procedure Materiaprima1Click(Sender: TObject); procedure Vidacomercial1Click(Sender: TObject); procedure tratamientosBase1Click(Sender: TObject); procedure ratamientos1Click(Sender: TObject); procedure AbonadosBase1Click(Sender: TObject); procedure Consumosygastos2Click(Sender: TObject); procedure ConectarconSistemPin1Click(Sender: TObject); procedure Utensilios1Click(Sender: TObject); procedure Controldeutensilios1Click(Sender: TObject); procedure Bsculas1Click(Sender: TObject); procedure Controldebsculas1Click(Sender: TObject); procedure Controlcmarasfrigorificas1Click(Sender: TObject); procedure aquillas1Click(Sender: TObject); procedure Controladoresdecalidad1Click(Sender: TObject); procedure Button43Click(Sender: TObject); procedure Button44Click(Sender: TObject); procedure dsqalmacenesDataChange(Sender: TObject; Field: TField); procedure Button45Click(Sender: TObject); procedure DBGrid41DblClick(Sender: TObject); procedure Button47Click(Sender: TObject); procedure Button48Click(Sender: TObject); procedure Button49Click(Sender: TObject); procedure PageControl2Change(Sender: TObject); procedure Button50Click(Sender: TObject); procedure Button51Click(Sender: TObject); procedure Button52Click(Sender: TObject); procedure comboprodmesasCloseUp(Sender: TObject); procedure comboprodmprimasCloseUp(Sender: TObject); procedure comboprodproductoCloseUp(Sender: TObject); procedure dsqparcelas2DataChange(Sender: TObject; Field: TField); procedure Button53Click(Sender: TObject); procedure Librosdecampo1Click(Sender: TObject); procedure Estadodestocks1Click(Sender: TObject); procedure EPIS1Click(Sender: TObject); procedure Button54Click(Sender: TObject); procedure hdesdeCloseUp(Sender: TObject); procedure hhastaCloseUp(Sender: TObject); procedure Button55Click(Sender: TObject); procedure Boquillas1Click(Sender: TObject); procedure Maquinria1Click(Sender: TObject); procedure CondicionesMeteorolgicas1Click(Sender: TObject); procedure Campaas1Click(Sender: TObject); procedure TabSheet21Enter(Sender: TObject); procedure Button58Click(Sender: TObject); procedure Button57Click(Sender: TObject); procedure Button59Click(Sender: TObject); procedure tbjornadasEnter(Sender: TObject); procedure Button56Click(Sender: TObject); procedure Consumosdefitosanitarios1Click(Sender: TObject); procedure Stockdealmacen1Click(Sender: TObject); private { Private declarations } public { Public declarations } procedure AppMessage(var Msg: Tmsg; var Handled: Boolean); procedure ExportaraExcel(FileNameXLS, SheetName: String; DBGrid: TDBGrid; ProgressBarXls: TProgressBar = nil); procedure MostrarPesadas(const idPesada: string); end; var BASE: TBASE; filtrotrabajadores, todostrabajadores, tlimitado, filtrolotes, filtroparcelas: string; vtactivo: Integer; const rojo = $00AAAAFF; amarillo = $00B9FFFF; verde = $00C7FBAA; azul = $00FFFFBB; function borrarficheros(carpeta: string): Boolean; implementation uses datos, datostrazabilidad2, datosestadisticas, datosproduccion, datosnominas, fechacierre, pesadas, fclientes, fenvases_almacen, fentradas, fpedidos, fticados, fproveedores, tipos_impuestos, gruposfamilias, calibrescalidad, fproductores, farticulo, farticulos, fpresentaciones, fgenericas, fgrupos_trabajadores, falbaranes, ffacturas, fimpresionmovimientos, formaspago, fimpresionarticuloscomponentes, fimpresionentradas, frecalculostock, fcontrolminimos, fcontrolstock, fconfiguracionalmacen, fcontrolproduccion, fbalanceventas, puestos_trabajo, regimen_cotizacion, empleados, cuentasbancarias, fformularios, fcc_expediciones, fimpresionconsumos, fcc_materiasprimas, fcc_vidacomercial, fconsumos, ftratamientosbase, ftratamientos, fproductosfitosanitarios, fconfirmar, fImportarPresenciaPin, futensilios, fcc_utensilios, fbasculas, fcc_basculas, fcc_camaras, ftaquillas, fcc_controlproducto, fcostesrestos, fcuadernos, fconsumosfito, fepis, fboquillas, fvehiculos, fmeteorologia, fusuarios, fstockalmacen, fconsumosfitoparcelas; {$R *.dfm} function borrarficheros(carpeta: string): Boolean; var SearchRec: TSearchRec; begin try if FindFirst(carpeta + '*.*', faAnyFile, SearchRec) = 0 then repeat Deletefile(carpeta + SearchRec.name); until (FindNext(SearchRec) <> 0); FindClose(SearchRec); result := true; except result := false; end; end; Function CantidadEnLetra(curCantidad: Currency; MonNal: Integer): String; var i: Integer; Cantidad, Centimos: Currency; BloqueCero, NumeroBloques, Digito: Byte; PrimerDigito, SegundoDigito, TercerDigito: Byte; Resultado, Temp, strCentimos, Bloque: String; Unidades: Array [0 .. 28] of String; Decenas: Array [0 .. 9] of String; Centenas: Array [0 .. 9] of String; begin Unidades[0] := 'UN'; Unidades[1] := 'DOS'; Unidades[2] := 'TRES'; Unidades[3] := 'CUATRO'; Unidades[4] := 'CINCO'; Unidades[5] := 'SEIS'; Unidades[6] := 'SIETE'; Unidades[7] := 'OCHO'; Unidades[8] := 'NUEVE'; Unidades[9] := 'DIEZ'; Unidades[10] := 'ONCE'; Unidades[11] := 'DOCE'; Unidades[12] := 'TRECE'; Unidades[13] := 'CATORCE'; Unidades[14] := 'QUINCE'; Unidades[15] := 'DIECISEIS'; Unidades[16] := 'DIECISIETE'; Unidades[17] := 'DIECIOCHO'; Unidades[18] := 'DIECINUEVE'; Unidades[19] := 'VEINTE'; Unidades[20] := 'VEINTIUNO'; Unidades[21] := 'VEINTIDOS'; Unidades[22] := 'VEINTITRES'; Unidades[23] := 'VEINTICUATRO'; Unidades[24] := 'VEINTICINCO'; Unidades[25] := 'VEINTISEIS'; Unidades[26] := 'VEINTISIETE'; Unidades[27] := 'VEINTIOCHO'; Unidades[28] := 'VEINTINUEVE'; Decenas[0] := 'DIEZ'; Decenas[1] := 'VEINTE'; Decenas[2] := 'TREINTA'; Decenas[3] := 'CUARENTA'; Decenas[4] := 'CINCUENTA'; Decenas[5] := 'SESENTA'; Decenas[6] := 'SETENTA'; Decenas[7] := 'OCHENTA'; Decenas[8] := 'NOVENTA'; Decenas[9] := 'CIEN'; Centenas[0] := 'CIENTO'; Centenas[1] := 'DOSCIENTOS'; Centenas[2] := 'TRESCIENTOS'; Centenas[3] := 'CUATROCIENTOS'; Centenas[4] := 'QUINIENTOS'; Centenas[5] := 'SEISCIENTOS'; Centenas[6] := 'SETECIENTOS'; Centenas[7] := 'OCHOCIENTOS'; Centenas[8] := 'NOVECIENTOS'; Cantidad := Trunc(curCantidad); Centimos := (curCantidad - Cantidad) * 100; NumeroBloques := 1; Repeat PrimerDigito := 0; SegundoDigito := 0; TercerDigito := 0; Bloque := ''; BloqueCero := 0; For i := 1 To 3 do begin Digito := Round(Cantidad) Mod 10; If Digito <> 0 Then begin Case i of 1: begin if NumeroBloques = 2 then Bloque := '' else Bloque := ' ' + Unidades[Digito - 1]; PrimerDigito := Digito; end; // case 1 2: begin If Digito <= 2 Then begin Bloque := ' ' + Unidades[(Digito * 10 + PrimerDigito - 1)]; end Else begin If PrimerDigito <> 0 then Temp := ' Y' else Temp := ''; Bloque := ' ' + Decenas[Digito - 1] + Temp + Bloque; End; // if SegundoDigito := Digito; end; // case 2 3: begin If (Digito = 1) and (PrimerDigito = 0) and (SegundoDigito = 0) then Temp := 'CIEN' else Temp := Centenas[Digito - 1]; Bloque := ' ' + Temp + Bloque; TercerDigito := Digito; end; // case 3 End; // case end else begin BloqueCero := BloqueCero + 1; End; // If Digito <>0 Cantidad := Int(Cantidad / 10); If Cantidad = 0 Then begin Break; End; // If Cantidad=0 end; // for Case NumeroBloques of 1: Resultado := Bloque; 2: begin if BloqueCero = 3 then Temp := 'MIL' else Temp := ' MIL'; Resultado := Bloque + Temp + Resultado; end; // case 2 3: begin If (PrimerDigito = 1) and (SegundoDigito = 0) and (TercerDigito = 0) then Temp := ' MILLON' else Temp := ' MILLONES'; Resultado := Bloque + Temp + Resultado; end; // case 3 End; // case NumeroBloques := NumeroBloques + 1; Until Cantidad = 0; // repeat case MonNal of 0: begin If curCantidad > 1 then Temp := ' CENTIMOS ***' else Temp := ' CENTIMO ***'; CantidadEnLetra := Resultado + Temp; end; 1: begin If curCantidad > 1 then Temp := ' EUROS ' else Temp := ' EURO '; if Centimos = 0 then strCentimos := '' else strCentimos := 'CON ' + CantidadEnLetra(Centimos, 0); CantidadEnLetra := '***' + Resultado + Temp + strCentimos + '***'; end; 2: begin If curCantidad > 1 then Temp := ' DOLARS ' else Temp := ' DOLAR '; if Centimos = 0 then strCentimos := '' else strCentimos := 'CON ' + CantidadEnLetra(Centimos, 0); CantidadEnLetra := '***' + Resultado + Temp + strCentimos; end; end; End; Function strFormatDecimal(strNum: String): String; // FUNCIÓN PARA AGREGAR UNA COMA Y EVITAR EL ERROR DE EXCEPCION begin if (AnsiPos('.', strNum) <> 0) then strNum := Copy(strNum, 0, AnsiPos('.', strNum) - 1) + ',' + Copy(strNum, AnsiPos('.', strNum) + 1, Length(strNum) - AnsiPos('.', strNum)); if strNum = '' then strNum := '0'; strFormatDecimal := strNum; end; 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; function ObtenerWeb(webIP: string): string; var obtenerHTTP: TidHTTP; web: TStringList; begin web := TStringList.Create; obtenerHTTP := TidHTTP.Create(nil); try web.Text := obtenerHTTP.Get(webIP); except on e: exception do begin obtenerHTTP.Free; end; end; ObtenerWeb := web.Text; end; function GetHTML2(WebBrowser: TWebBrowser): string; begin result := (WebBrowser.Document AS IHTMLDocument3).documentElement.outerHTML; end; procedure TBASE.Expediciones1Click(Sender: TObject); begin cc_expediciones := Tcc_expediciones.Create(nil); try cc_expediciones.ShowModal; finally cc_expediciones.Free; end; end; procedure TBASE.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 TBASE.FacturasClientes1Click(Sender: TObject); begin facturas := Tfacturas.Create(nil); try facturas.ShowModal(); finally facturas.Free; end; end; procedure TBASE.bamodificarClick(Sender: TObject); begin dm.talmacenes.edit; DBEdit107.SetFocus; baanadir.Enabled := false; bamodificar.Enabled := false; baborrar.Enabled := false; bacancelar.Enabled := true; baaceptar.Enabled := true; end; procedure TBASE.bborrarjornalesClick(Sender: TObject); begin tjornales.Locate('id', qjornalesid.AsString, [locaseinsensitive]); tjornales.Delete; qjornales.Refresh; qjornales.First; end; procedure TBASE.bmodificarjornalesClick(Sender: TObject); begin tfechajornal.Date := qjornalesfecha.AsDateTime; ltrabajo.KeyValue := qjornalestypework.AsString; lparcela.KeyValue := qjornalesparcela.AsString; ltipohora.KeyValue := qjornalesarticulo.AsString; thoras.Text := qjornalesqhoras.AsString; // qtrabajos.Locate('id',qjornalestypework.AsString,[loCaseInsensitive]); // ltrabajo.Refresh; bmodificarjornales.Enabled := false; bcancelarjornal.Enabled := true; btinsertar.Enabled := false; bborrarjornales.Enabled := false; baceptar.Enabled := true; tfechajornal.Enabled := true; lparcela.Enabled := true; ltrabajo.Enabled := true; ltipohora.Enabled := true; thoras.Enabled := true; lprecio.Enabled := true; if qjornalesestado.AsString <> 'P' then begin tjornales.Locate('id', qjornalesid.AsString, [locaseinsensitive]); tjornales.edit; tfechajornal.SetFocus; end else begin tjornales.edit; bcancelarjornal.Click; showmessage('IMPOSIBLE MODIFICAR REGISTRO'); end; end; procedure TBASE.bmpaceptarClick(Sender: TObject); var id: string; begin id := dm.tmateriasprimasid.AsString; Panel133.Enabled := false; dm.tmateriasprimasgenerico.Value := dm.qmprimascompuestasdescripcion.AsString; dm.tmateriasprimas.post; dm.qmateriasprimas.Refresh; dm.qmateriasprimas.Locate('id', id, [locaseinsensitive, lopartialkey]); bmpanadir.Enabled := true; bmpmodificar.Enabled := true; bmpborrar.Enabled := true; bmpcancelar.Enabled := false; bmpaceptar.Enabled := false; end; procedure TBASE.bmpanadirClick(Sender: TObject); begin Panel133.Enabled := true; dm.tmateriasprimas.Append; DBEdit67.SetFocus; bmpanadir.Enabled := false; bmpmodificar.Enabled := false; bmpborrar.Enabled := false; bmpcancelar.Enabled := true; bmpaceptar.Enabled := true; end; procedure TBASE.bmpborrarClick(Sender: TObject); begin dm.tmateriasprimas.Delete; dm.qmateriasprimas.Refresh; end; procedure TBASE.bmpcancelarClick(Sender: TObject); begin Panel133.Enabled := false; dm.tmateriasprimas.cancel; dm.qmateriasprimas.Refresh; bmpanadir.Enabled := true; bmpmodificar.Enabled := true; bmpborrar.Enabled := true; bmpcancelar.Enabled := false; bmpaceptar.Enabled := false; end; procedure TBASE.bmpc_aceptarClick(Sender: TObject); begin dm.qmprimascompuestas.Append; dm.qmprimascompuestasidempresa.Value := dm.qmateriasprimas2idempresa.AsInteger; dm.qmprimascompuestasidmp.Value := dm.qmateriasprimasid.AsString; dm.qmprimascompuestasidmpc.Value := dm.qmateriasprimas2id.AsString; dm.qmprimascompuestasvariedad.Value := dm.qmateriasprimas2variedad.AsString; dm.qmprimascompuestasdescripcion.Value := dm.qmateriasprimas2descripcion.AsString; dm.qmprimascompuestasporcentaje.Value := StrToInt(Edit4.Text); dm.qmprimascompuestas.post; DBLookupComboBox11.Visible := false; Edit4.Visible := false; bmpc_aceptar.Enabled := false; bmpc_anyadir.Enabled := true; end; procedure TBASE.bmpc_anyadirClick(Sender: TObject); begin DBLookupComboBox11.Visible := true; Edit4.Visible := true; bmpc_aceptar.Enabled := true; bmpc_anyadir.Enabled := false; end; procedure TBASE.bmpc_borrarClick(Sender: TObject); begin dm.qmprimascompuestas.Delete; end; procedure TBASE.bmpmodificarClick(Sender: TObject); begin Panel133.Enabled := true; dm.tmateriasprimas.edit; DBEdit67.SetFocus; bmpanadir.Enabled := false; bmpmodificar.Enabled := false; bmpborrar.Enabled := false; bmpcancelar.Enabled := true; bmpaceptar.Enabled := true; end; procedure TBASE.Boquillas1Click(Sender: TObject); begin boquillas := Tboquillas.Create(nil); try boquillas.ShowModal; finally boquillas.Free; end; end; procedure TBASE.BSalirClick(Sender: TObject); begin ExitProcess(0); end; procedure TBASE.Bsculas1Click(Sender: TObject); begin basculas := Tbasculas.Create(nil); try basculas.ShowModal; finally basculas.Free; end; end; procedure TBASE.btaaceptarClick(Sender: TObject); begin dm.ttrabajosalmacen.post; dm.qtrabajosalmacen.Refresh; dm.qtrabajosalmacen.First; btaanadir.Enabled := true; btamodificar.Enabled := true; btaborrar.Enabled := true; btacancelar.Enabled := false; btaaceptar.Enabled := false; end; procedure TBASE.btaanadirClick(Sender: TObject); begin dm.ttrabajosalmacen.Append; DBEdit76.SetFocus; btaanadir.Enabled := false; btamodificar.Enabled := false; btaborrar.Enabled := false; btacancelar.Enabled := true; btaaceptar.Enabled := true; end; procedure TBASE.btaborrarClick(Sender: TObject); begin dm.ttrabajosalmacen.Delete; dm.qtrabajosalmacen.Refresh; dm.qtrabajosalmacen.First end; procedure TBASE.btacancelarClick(Sender: TObject); begin dm.ttrabajosalmacen.cancel; dm.qtrabajosalmacen.Refresh; btaanadir.Enabled := true; btamodificar.Enabled := true; btaborrar.Enabled := true; btacancelar.Enabled := false; btaaceptar.Enabled := false; end; procedure TBASE.btAgendaClick(Sender: TObject); var anyo, mes, dia: word; vanyo, vmes, vdia, vmessig, vfecha: string; begin dm.DBagrigest.Disconnect; dm.tcalendario_laboral.Open; calendarionotas.Date := Date; calendarionotas.endDate := Date; Timer1.Enabled := false; decodedate(Date, anyo, mes, dia); vanyo := floattostr(anyo); vmes := floattostr(mes); vmessig := floattostr(mes + 1); if Length(vmes) = 1 then vmes := '0' + vmes; if Length(vmessig) = 1 then vmessig := '0' + vmessig; if Length(vdia) = 1 then vdia := '0' + vdia; vmes := floattostr(mes); vmessig := floattostr(mes + 1); vdia := floattostr(dia); dm.tempresa.Open; vfecha := floattostr(anyo) + '-' + vmes + '-' + vdia; dm.tcalendario_laboral.Refresh; dm.tcalendario_laboral.Locate('fecha', vfecha, [locaseinsensitive]); PDAgenda.align := alclient; PDAgenda.Visible := true; PDNominas.Visible := not PDAgenda.Visible; PDEmpleados.Visible := not PDAgenda.Visible; PDProduccion.Visible := not PDAgenda.Visible; PDTrazabilidad.Visible := not PDAgenda.Visible; PDEmpresa.Visible := not PDAgenda.Visible; PDExpediciones.Visible := not PDAgenda.Visible; dm.tnotas.Open; dm.qaux1.Close; dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add ('select count(*) from calendario_laboral where festivo=0 and fecha>=' + '''' + vanyo + '-' + vmes + '-01' + '''' + 'and fecha<' + '''' + vanyo + '-' + vmessig + '-01' + ''''); dm.qaux1.Open; Label80.Caption := 'Dias laborables del mes: ' + dm.qaux1.Fields[0].AsString; end; procedure TBASE.btAguardarClick(Sender: TObject); begin if dm.dsanticipos.State = dsedit then begin dm.tanticiposfecha.Value := fechaanticipo.Date; if lopciones.ItemIndex = 0 then begin dm.tanticiposimporte.Value := strtofloat(limporteanticipo.Text); dm.tanticipospenalizacion.Value := 0; dm.tanticiposindemnizacion.Value := 0; end; if lopciones.ItemIndex = 1 then begin dm.tanticiposimporte.Value := 0; dm.tanticipospenalizacion.Value := 0; dm.tanticiposindemnizacion.Value := strtofloat(limporteanticipo.Text); end; if lopciones.ItemIndex = 2 then begin dm.tanticiposimporte.Value := 0; dm.tanticipospenalizacion.Value := strtofloat(limporteanticipo.Text); dm.tanticiposindemnizacion.Value := 0; end; dm.tanticiposobservaciones.Value := lobservaciones.Text; dm.tanticiposestado.Value := 'C'; dm.tanticipos.post; dm.qanticipos.Refresh; dm.qanticipos.First; end; if dm.dsanticipos.State = dsinsert then begin qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('select max(id)+1 from anticipos'); qaux.Open; dm.tanticiposid.Value := qaux.Fields[0].AsInteger; dm.tanticiposfecha.Value := fechaanticipo.Date; dm.tanticiposidt.Value := qempleadosid.AsInteger; dm.tanticipostrabajador.Value := qempleadosnombre.AsString; if lopciones.ItemIndex = 0 then begin dm.tanticiposimporte.Value := strtofloat(limporteanticipo.Text); dm.tanticipospenalizacion.Value := 0; dm.tanticiposindemnizacion.Value := 0; end; if lopciones.ItemIndex = 1 then begin dm.tanticiposimporte.Value := 0; dm.tanticipospenalizacion.Value := 0; dm.tanticiposindemnizacion.Value := strtofloat(limporteanticipo.Text); end; if lopciones.ItemIndex = 2 then begin dm.tanticiposimporte.Value := 0; dm.tanticipospenalizacion.Value := strtofloat(limporteanticipo.Text); dm.tanticiposindemnizacion.Value := 0; end; dm.tanticiposobservaciones.Value := Uppercase(lobservaciones.Text); dm.tanticiposestado.Value := 'C'; dm.tanticipos.post; dm.qanticipos.Refresh; dm.qanticipos.First; end; end; procedure TBASE.btamodificarClick(Sender: TObject); begin dm.ttrabajosalmacen.edit; DBEdit76.SetFocus; btaanadir.Enabled := false; btamodificar.Enabled := false; btaborrar.Enabled := false; btacancelar.Enabled := true; btaaceptar.Enabled := true; end; procedure TBASE.btEnuevoClick(Sender: TObject); begin dm.tanticipos.Open; dm.tanticipos.Append; fechaanticipo.SetFocus; end; procedure TBASE.BtEmpleadosClick(Sender: TObject); // var idt,filtrojornales, filtroanticipos: String; // ianyo,imes,idia:word; begin dm.DBagrigest.Disconnect; fempleados := Tfempleados.Create(nil); try fempleados.ShowModal(); finally fempleados.Free; end; { timer1.Enabled:=false; pdempleados.Align:=alclient; pdempleados.Visible:=true; pdnominas.Visible:=not pdempleados.Visible; pdproduccion.Visible:=not pdempleados.Visible; pdagenda.Visible:=not pdempleados.Visible; pdempresa.Visible:=not pdempleados.Visible; pdtrazabilidad.Visible:=not pdempleados.Visible; pdexpediciones.Visible:=not pdempleados.Visible; decodedate(date,ianyo,imes,idia); tmes.ItemIndex:=imes; tanyo.ItemIndex:=ianyo-2015+1; tmes2.ItemIndex:=imes; tanyo2.ItemIndex:=ianyo-2015+1; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=0'); qaux.ExecSQL; qempleados.close; qempleados.Open; listagrupos2.KeyValue:=0; idt:=qempleadosid.asstring; if idt<>'' then filtrojornales:='where idt='+idt+' and ' else filtrojornales:='where '; if tanyo.ItemIndex<>0 then filtrojornales:=filtrojornales+' year(fecha)='+tanyo.Text ; if tmes.itemindex<>0 then filtrojornales:=filtrojornales+' and month(fecha)='+inttostr(tmes.itemindex); if testado.itemindex<>0 then filtrojornales:=filtrojornales+' and estado='+testado.text; filtrojornales:=filtrojornales+' order by fecha desc'; qjornales.Close; qjornales.SQL.Clear; qjornales.SQL.Add('select * from trabajo_diario '+filtrojornales); qjornales.Open; if idt<>'' then filtroanticipos:='where idt='+idt+' and ' else filtroanticipos:='where '; if tanyo2.ItemIndex<>0 then filtroanticipos:=filtroanticipos+' year(fecha)='+tanyo2.Text ; if tmes2.itemindex<>0 then filtroanticipos:=filtroanticipos+' and month(fecha)='+inttostr(tmes2.itemindex); if testado2.itemindex<>0 then filtroanticipos:=filtroanticipos+' and estado='+testado2.text; filtroanticipos:=filtroanticipos+' order by fecha desc'; dm.qanticipos.Close; dm.qanticipos.SQL.Clear; dm.qanticipos.SQL.Add('select * from anticipos '+filtroanticipos); dm.qanticipos.Open; qempleados.Open; templeados.Open; templeados.locate('id',idt,[locaseinsensitive]); pageempleados.ActivePageIndex:=0; //tgrupo.ItemIndex:=0; vtactivo:=0; dm.qparcelas.open; dm.qtrabajos.open; dm.qtipohoras.open; falta.Date:=date; fbaja.Date:=date; tjornales.Open; dm.tanticipos.Open; qgrupostrabajadores.Close; qgrupostrabajadores.open;; qgrupostrabajadores2.Close; qgrupostrabajadores2.open; } end; procedure TBASE.btempresaClick(Sender: TObject); begin Timer1.Enabled := false; PDEmpresa.align := alclient; PDEmpresa.Visible := true; PDEmpleados.Visible := not PDEmpresa.Visible; PDNominas.Visible := not PDEmpresa.Visible; PDProduccion.Visible := not PDEmpresa.Visible; PDAgenda.Visible := not PDEmpresa.Visible; PDTrazabilidad.Visible := not PDEmpresa.Visible; PDExpediciones.Visible := not PDEmpresa.Visible; dm.DBagrigest.Disconnect; { dm.tempresa.close; dm.qproductos.close; dm.tproductos.close; dm.tmateriasprimas.close; dm.qmateriasprimas.close; dm.ttipohoras.close; dm.qtipohoras.close; dm.ttipotrabajo.close; dm.qtrabajos.close; dm.qtrabajosalmacen.close; dm.ttrabajosalmacen.close; dm.qcampanyas.close; dm.qlincampanyas.close; dm.qseries.close; qarticulocomision.close; qarticulotransporte.close; qarticulosotros.Close; } dm.tempresa.Open; dm.qproductos.Open; dm.tproductos.Open; dm.tmateriasprimas.Open; dm.qmateriasprimas.Open; dm.ttipohoras.Open; dm.qtipohoras.Open; dm.ttipotrabajo.Open; dm.qtrabajos.Open; dm.qtrabajosalmacen.Open; dm.ttrabajosalmacen.Open; dm.qcampanyas.Open; dm.qlincampanyas.Open; dm.qseries.Open; qfamilias.Open; qarticulocomision.Open; qarticulotransporte.Open; qarticulosotros.Open; PageDatosEmpresa.ActivePageIndex := 0; Pagedatos.ActivePageIndex := 0; end; procedure TBASE.bthaceptarClick(Sender: TObject); begin dm.ttipohoras.post; dm.qtipohoras.Refresh; bthanadir.Enabled := true; bthmodificar.Enabled := true; bthborrar.Enabled := true; bthcancelar.Enabled := false; bthaceptar.Enabled := false; end; procedure TBASE.bthanadirClick(Sender: TObject); begin dm.ttipohoras.Append; DBEdit69.SetFocus; bthanadir.Enabled := false; bthmodificar.Enabled := false; bthborrar.Enabled := false; bthcancelar.Enabled := true; bthaceptar.Enabled := true; end; procedure TBASE.bthborrarClick(Sender: TObject); begin dm.ttipohoras.Delete; dm.ttipohoras.Refresh; end; procedure TBASE.bthcancelarClick(Sender: TObject); begin dm.ttipohoras.cancel; dm.qtipohoras.Refresh; bthanadir.Enabled := true; bthmodificar.Enabled := true; bthborrar.Enabled := true; bthcancelar.Enabled := false; bthaceptar.Enabled := false; end; procedure TBASE.bthmodificarClick(Sender: TObject); begin dm.ttipohoras.edit; DBEdit69.SetFocus; bthanadir.Enabled := false; bthmodificar.Enabled := false; bthborrar.Enabled := false; bthcancelar.Enabled := true; bthaceptar.Enabled := true; end; procedure TBASE.bticierreClick(Sender: TObject); var anyo, mes, dia: word; fecha: string; id: Integer; begin decodedate(dmproduccion.qpartesdiariosfecha_traspaso.AsDateTime, anyo, mes, dia); fecha := inttostr(anyo) + '-' + inttostr(mes) + '-' + inttostr(dia); id := dmproduccion.qpartesdiariosid.AsInteger; dmproduccion.qactualizar.SQL.Clear; dmproduccion.qactualizar.SQL.Add ('update almacenes_partesdiarios set estado=0 where id=' + dmproduccion.qpartesdiariosid.AsString); dmproduccion.qactualizar.ExecSQL; dmproduccion.qpartesdiarios.Refresh; dmproduccion.qpartesdiarios.Locate('id', id, [locaseinsensitive]); end; procedure TBASE.btinsertarClick(Sender: TObject); begin bmodificarjornales.Enabled := false; bcancelarjornal.Enabled := true; bborrarjornales.Enabled := false; btinsertar.Enabled := false; baceptar.Enabled := true; tfechajornal.Enabled := true; lparcela.Enabled := true; ltrabajo.Enabled := true; ltipohora.Enabled := true; thoras.Enabled := true; lprecio.Enabled := true; tfechajornal.SetFocus; tjornales.Append; end; procedure TBASE.BtjornalesClick(Sender: TObject); var anyo, mes, dia: word; filtro, fdesde, fhasta: string; begin dm.DBagrigest.Disconnect; fechajornales.Date := Date; fechaanticipos.Date := Date; Timer1.Enabled := false; filtro := ''; decodedate(Date, anyo, mes, dia); PDNominas.align := alclient; PDNominas.Visible := true; PDEmpleados.Visible := not PDNominas.Visible; PDProduccion.Visible := not PDNominas.Visible; PDAgenda.Visible := not PDNominas.Visible; PDTrazabilidad.Visible := not PDNominas.Visible; PDEmpresa.Visible := not PDNominas.Visible; PDExpediciones.Visible := not PDNominas.Visible; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=0'); qaux.ExecSQL; PageNominas.ActivePageIndex := 0; if tlimitado = '1' then begin PageNominas.ActivePageIndex := 6; Nominaspag1.tabVisible := false; NominasPag2.tabVisible := false; Nominaspag3.tabVisible := false; Nominaspag4.tabVisible := false; Nominaspag5.tabVisible := false; Nominaspag6.tabVisible := false; end; nomfechahasta.Date := Date; nomfechadesde.Date := strtodate('01/' + floattostr(mes) + '/' + floattostr(anyo)); listaanyos.ItemIndex := anyo - 2014; listameses.ItemIndex := mes; nomlhhasta.Date := Date; nomlhdesde.Date := strtodate('01/' + floattostr(mes) + '/' + floattostr(anyo)); nomltthasta.Date := Date; nomlttdesde.Date := strtodate('01/' + floattostr(mes) + '/' + floattostr(anyo)); // nomantfechahasta.Date:=date; // nomantfechadesde.Date:=strtodate('01/'+floattostr(mes)+'/'+floattostr(anyo)); pagnomfechahasta.Date := Date; pagnomfechadesde.Date := strtodate('01/' + floattostr(mes) + '/' + floattostr(anyo)); decodedate(nomfechadesde.Date, anyo, mes, dia); fdesde := floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia); filtro := ' where fecha>=' + '''' + fdesde + ''''; decodedate(nomfechahasta.Date, anyo, mes, dia); fhasta := floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia); filtro := filtro + ' and fecha<=' + '''' + fhasta + ''''; filtro := filtro + ' order by trabajador asc,fecha desc'; { dm.qnominasdetalle.Close; dm.qnominasdetalle.SQL.Clear; dm.qnominasdetalle.SQL.Add('select * from trabajo_diario '+filtro); dm.qnominasdetalle.Open; dm.qanticiposdetalle.Close; dm.qanticiposdetalle.SQL.Clear; dm.qanticiposdetalle.SQL.Add('select * from anticipos '+filtro); dm.qanticiposdetalle.Open; } dm.tempresa.Open; qempleados.Open; dm.qtipohoras2.Open; dm.qtrabajadores2.Open; dm.qlistadohoras.Open; tjornales.Open; dm.tanticipos.Open; btactualizarempleadosnominas.Click; qgrupostrabajadores2.Close; qgrupostrabajadores2.Open; end; procedure TBASE.BTLcancelarClick(Sender: TObject); begin dmtr.qlotes.cancel; dmtr.qlotes.Refresh; dmtr.qlotes.First; if dmtr.qlotes.State in [dsinsert, dsedit] then begin btlnuevo.Visible := false; btLmodificar.Visible := false; btLguardar.Visible := true; btLcancelar.Visible := true; end else begin btlnuevo.Visible := true; btLmodificar.Visible := true; btLguardar.Visible := false; btLcancelar.Visible := false; end; end; procedure TBASE.BTLModificarClick(Sender: TObject); var tcodigo: string; begin // dmtr.qlotes.First; tcodigo := dmtr.qlotescodigo.AsString; tcodigo := inttostr(StrToInt(tcodigo)); dmtr.qlotes.edit; dlotescodigo.SetFocus; dlotescodigo.Text := tcodigo; if dmtr.qlotes.State in [dsinsert, dsedit] then begin btlnuevo.Visible := false; btLmodificar.Visible := false; btLguardar.Visible := true; btLcancelar.Visible := true; end else begin btlnuevo.Visible := true; btLmodificar.Visible := true; btLguardar.Visible := false; btLcancelar.Visible := false; end; end; procedure TBASE.BTLNuevoClick(Sender: TObject); var tcodigo: string; begin dmtr.qlotes.First; // tcodigo:=dmtr.qlotescodigo.AsString; // tcodigo:=inttostr(strtoint(tcodigo)+1); dmtr.qaux.SQL.Clear; dmtr.qaux.SQL.Add('select max(codigo)+1 from lotes'); dmtr.qaux.Open; tcodigo := dmtr.qaux.Fields[0].AsString; dmtr.qlotes.Append; dlotescodigo.SetFocus; dlotescodigo.Text := tcodigo; if dmtr.qlotes.State in [dsinsert, dsedit] then begin btlnuevo.Visible := false; btLmodificar.Visible := false; btLguardar.Visible := true; btLcancelar.Visible := true; end else begin btlnuevo.Visible := true; btLmodificar.Visible := true; btLguardar.Visible := false; btLcancelar.Visible := false; end; end; procedure TBASE.btproduccionClick(Sender: TObject); var anyo, mes, dia: word; fdesde, fhasta, vmes, vdia: string; begin dm.DBagrigest.Disconnect; dm.tempresa.Open; PDProduccion.align := alclient; PDProduccion.Visible := true; PDEmpleados.Visible := not PDProduccion.Visible; PDNominas.Visible := not PDProduccion.Visible; PDAgenda.Visible := not PDProduccion.Visible; PDEmpresa.Visible := not PDProduccion.Visible; PDTrazabilidad.Visible := not PDProduccion.Visible; PDExpediciones.Visible := not PDProduccion.Visible; fprodesde.Date := Date; { fprohasta.Date := Date; decodedate(fprohasta.Date, anyo, mes, dia); vmes := inttostr(mes); vdia := inttostr(dia); fhasta := floattostr(anyo) + '-' + vmes + '-' + vdia; } Pageproduccion.ActivePageIndex := 9; DBGrid44.SetFocus; end; procedure TBASE.BTSNBORRARClick(Sender: TObject); begin dm.qseries.Delete; dm.qseries.Refresh; end; procedure TBASE.BTSNCANCELARClick(Sender: TObject); begin dm.qseries.cancel; end; procedure TBASE.btSNguardarClick(Sender: TObject); begin dm.qseries.post; dm.qseries.Refresh; dm.qseries.MasterSource := dm.dsempresa; end; procedure TBASE.BTSNMODIFICARClick(Sender: TObject); begin dm.qseries.edit; DBGrid56.SetFocus; end; procedure TBASE.btSNnuevoClick(Sender: TObject); begin dm.qseries.MasterSource := nil; dm.qseries.Append; dm.qserieside.Value := dm.tempresaid.AsInteger; DBGrid56.SetFocus; end; procedure TBASE.bpraceptarClick(Sender: TObject); var producto: string; begin producto := dm.tproductoscodigo.AsString; dm.tproductos.post; dm.tproductos.Refresh; dm.qproductos.Refresh; dm.qproductos.Locate('codigo', producto, [locaseinsensitive]); bpranadir.Enabled := true; bprmodificar.Enabled := true; bprborrar.Enabled := true; bprcancelar.Enabled := false; bpraceptar.Enabled := false; end; procedure TBASE.bpranadirClick(Sender: TObject); begin qaux.SQL.Clear; qaux.SQL.Add('select max(id)+1 from productos '); qaux.Open; dm.tproductos.Append; dm.tproductoside.AsInteger := dm.tempresaid.AsInteger; dm.tproductosid.AsInteger := qaux.Fields[0].AsInteger; dm.tproductoscodigo.AsString := qaux.Fields[0].AsString; DBEdit10.SetFocus; bpranadir.Enabled := false; bprmodificar.Enabled := false; bprborrar.Enabled := false; bprcancelar.Enabled := true; bpraceptar.Enabled := true; end; procedure TBASE.bprborrarClick(Sender: TObject); begin dm.tproductos.Delete; dm.qproductos.Refresh; end; procedure TBASE.bprcancelarClick(Sender: TObject); begin dm.tproductos.cancel; dm.qproductos.Refresh; bpranadir.Enabled := true; bprmodificar.Enabled := true; bprborrar.Enabled := true; bprcancelar.Enabled := false; bpraceptar.Enabled := false; end; procedure TBASE.bprmodificarClick(Sender: TObject); begin dm.tproductos.edit; DBEdit10.SetFocus; bpranadir.Enabled := false; bprmodificar.Enabled := false; bprborrar.Enabled := false; bprcancelar.Enabled := true; bpraceptar.Enabled := true; end; procedure TBASE.bttaceptarClick(Sender: TObject); var codigo: string; begin dm.ttipotrabajo.post; codigo := dm.ttipotrabajoid.AsString; dm.qtrabajos.Refresh; dm.qtrabajos.Locate('id', codigo, [locaseinsensitive, lopartialkey]); bttanadir.Enabled := true; bttmodificar.Enabled := true; bttborrar.Enabled := true; bttcancelar.Enabled := false; bttaceptar.Enabled := false; end; procedure TBASE.bttanadirClick(Sender: TObject); begin dm.ttipotrabajo.Append; DBEdit72.SetFocus; bttanadir.Enabled := false; bttmodificar.Enabled := false; bttborrar.Enabled := false; bttcancelar.Enabled := true; bttaceptar.Enabled := true; end; procedure TBASE.bttborrarClick(Sender: TObject); begin dm.ttipotrabajo.Delete; dm.qtrabajos.Refresh; dm.qtrabajos.First end; procedure TBASE.bttcancelarClick(Sender: TObject); begin dm.ttipotrabajo.cancel; dm.ttipotrabajo.Refresh; bttanadir.Enabled := true; bttmodificar.Enabled := true; bttborrar.Enabled := true; bttcancelar.Enabled := false; bttaceptar.Enabled := false; end; procedure TBASE.btexpedicionesClick(Sender: TObject); var anyo, mes, dia: word; fdesde, fhasta, vmes, vdia: string; begin dm.DBagrigest.Disconnect; dm.tempresa.Open; PDExpediciones.align := alclient; PDExpediciones.Visible := true; PDProduccion.Visible := not PDExpediciones.Visible; PDEmpleados.Visible := not PDExpediciones.Visible; PDNominas.Visible := not PDExpediciones.Visible; PDAgenda.Visible := not PDExpediciones.Visible; PDEmpresa.Visible := not PDExpediciones.Visible; PDTrazabilidad.Visible := not PDExpediciones.Visible; end; procedure TBASE.bttmodificarClick(Sender: TObject); begin dm.ttipotrabajo.edit; DBEdit72.SetFocus; bttanadir.Enabled := false; bttmodificar.Enabled := false; bttborrar.Enabled := false; bttcancelar.Enabled := true; bttaceptar.Enabled := true; end; procedure TBASE.bttrazabilidadClick(Sender: TObject); begin dm.DBagrigest.Disconnect; qempresa.Open; dmestadisticas.qcampanyas.Open; dm.qcampanyas.Open; PDTrazabilidad.align := alclient; PDTrazabilidad.Visible := true; PDProduccion.Visible := not PDTrazabilidad.Visible; PDEmpleados.Visible := not PDTrazabilidad.Visible; PDNominas.Visible := not PDTrazabilidad.Visible; PDAgenda.Visible := not PDTrazabilidad.Visible; PDEmpresa.Visible := not PDTrazabilidad.Visible; PDExpediciones.Visible := not PDTrazabilidad.Visible; if qempresavercodtrazabilidad.AsInteger = 0 then begin Label209.Visible := false; DBEdit116.Visible := false; end else begin Label209.Visible := true; DBEdit116.Visible := true; end; dm.tempresa.Open; dm.qmateriasprimas2.Close; dm.qparcelas.Close; dmtr.qcampanyas.Close; dmtr.qlotes.Close; dmtr.qtiposgenerador.Close; dmtr.qea_pesadas.Close; dmtr.qsalidas.Close; dm.qmateriasprimas2.Open; dm.qparcelas.Open; dmtr.qcampanyas.Open; dmtr.qlotes.Open; dmtr.qtiposgenerador.Open; dmtr.qea_pesadas.Open; dmtr.qsalidas.Open; qsocios2.Close; qsocios2.Open; // dmtr.documentos.close; // dmtr.documentos.Filter:='id=-1'; // dmtr.documentos.Open; end; procedure TBASE.btcerrarClick(Sender: TObject); var anyo, mes, dia: word; fecha, fechainicial, fechafinal: string; cajas, restocajas: Integer; pesosalidas, restopeso: real; begin decodedate(BASE.ffechatraspaso.Date, anyo, mes, dia); fecha := inttostr(dia) + '/' + inttostr(mes) + '/' + inttostr(anyo); dmproduccion.qpartesdiarios.edit; dmproduccion.qpartesdiariosfecha_traspaso.Value := strtodate(fecha); dmproduccion.qpartesdiariosestado.Value := 1; dmproduccion.qpartesdiarios.post; decodedate(dmproduccion.qpartesdiariosfecha_traspaso.AsDateTime, anyo, mes, dia); fechafinal := inttostr(anyo) + '-' + inttostr(mes) + '-' + inttostr(dia); decodedate(dmproduccion.qpartesdiariosfecha.AsDateTime, anyo, mes, dia); fechainicial := inttostr(anyo) + '-' + inttostr(mes) + '-' + inttostr(dia); dmproduccion.qactualizar.SQL.Clear; dmproduccion.qactualizar.SQL.Add ('select count(id) from almacenes_partesdiarios where idempresa=' + dmproduccion.qpartesdiariosidempresa.AsString + ' and almacen=' + dmproduccion.qpartesdiariosalmacen.AsString + ' and fecha=' + '''' + fechafinal + ''''); dmproduccion.qactualizar.Open; if dmproduccion.qactualizar.Fields[0].AsInteger = 0 then begin dmproduccion.qactualizar.SQL.Clear; dmproduccion.qactualizar.SQL.Add ('insert into almacenes_partesdiarios (idempresa,fecha,almacen,nombre_almacen,cajas_apertura,peso_apertura,coste_apertura) values (' + dmproduccion.qpartesdiariosidempresa.AsString + ',' + '''' + fechafinal + '''' + ',' + dmproduccion.qpartesdiariosalmacen.AsString + ',' + '''' + dmproduccion.qpartesdiariosnombre_almacen.AsString + '''' + ',' + dmproduccion.qpartesdiarioscajas_cierre.AsString + ',' + stringreplace(dmproduccion.qpartesdiariospeso_cierre.AsString, ',', '.', [rfReplaceAll]) + ',' + stringreplace (dmproduccion.qpartesdiarioscoste_cierre.AsString, ',', '.', [rfReplaceAll]) + ')'); dmproduccion.qactualizar.ExecSQL; end else begin dmproduccion.qactualizar.SQL.Clear; dmproduccion.qactualizar.SQL.Add ('update almacenes_partesdiarios set cajas_apertura=' + dmproduccion.qpartesdiarioscajas_cierre.AsString + ',peso_apertura=' + stringreplace(dmproduccion.qpartesdiariospeso_cierre.AsString, ',', '.', [rfReplaceAll]) + ',coste_apertura=' + stringreplace(dmproduccion.qpartesdiarioscoste_cierre.AsString, ',', '.', [rfReplaceAll]) + ' where idempresa=' + dmproduccion.qpartesdiariosidempresa.AsString + ' and fecha=' + '''' + fechafinal + '''' + ' and almacen=' + dmproduccion.qpartesdiariosalmacen.AsString); dmproduccion.qactualizar.ExecSQL; end; dmproduccion.qpartesdiarios.Refresh; end; procedure TBASE.btcontrolprodcerrarClick(Sender: TObject); var anyo, mes, dia: word; fdesde, fhasta: string; begin decodedate(fprodesde.Date, anyo, mes, dia); fdesde := inttostr(anyo) + '-' + inttostr(mes) + '-' + inttostr(dia); // decodedate(fprohasta.Date, anyo, mes, dia); // fhasta := inttostr(anyo) + '-' + inttostr(mes) + '-' + inttostr(dia); qaux.SQL.Clear; qaux.SQL.Add('select * from control_produccion where fecha=' + '''' + fdesde + ''''); qaux.Open; if qaux.RecordCount > 0 then begin qaux.SQL.Clear; qaux.SQL.Add('delete from control_produccion where fecha=' + '''' + fdesde + ''''); qaux.ExecSQL; end; qaux.SQL.Clear; qaux.SQL.Add ('select fecha,materia_prima,producto,pesadas from vista_produccion where fecha=' + '''' + fdesde + ''''); qaux.Open; if qaux.RecordCount > 1 then begin while not qaux.Eof do begin dm.qcontrolproduccion.Append; dm.qcontrolproduccion.Fields[1].Value := qaux.Fields[0].AsString; dm.qcontrolproduccion.Fields[2].Value := qaux.Fields[1].AsString; dm.qcontrolproduccion.Fields[3].Value := qaux.Fields[2].AsString; dm.qcontrolproduccion.Fields[4].Value := qaux.Fields[3].AsString; dm.qcontrolproduccion.post; qaux.Next; end; end; if qaux.RecordCount = 1 then begin dm.qcontrolproduccion.Append; dm.qcontrolproduccion.Fields[1].Value := qaux.Fields[0].AsString; dm.qcontrolproduccion.Fields[2].Value := qaux.Fields[1].AsString; dm.qcontrolproduccion.Fields[3].Value := qaux.Fields[2].AsString; dm.qcontrolproduccion.Fields[4].Value := qaux.Fields[3].AsString; dm.qcontrolproduccion.post; end; dm.qcontrolproduccion.Close; dm.qcontrolproduccion.Prepare; dm.qcontrolproduccion.ParamByName('fecha').AsDate:=fprodesde.Date; dm.qcontrolproduccion.Open; end; procedure TBASE.Button10Click(Sender: TObject); begin informedb.DataSource := dm.dsqlistadohoras; informes.Report.Clear; if ListaInformes.ItemIndex = 0 then informes.LoadFromFile('c:\agrigest\informes\listadohorasvalorado.fr3'); if ListaInformes.ItemIndex = 1 then informes.LoadFromFile('c:\agrigest\informes\listadohoras.fr3'); informes.Variables.Variables['TITULO'] := QUOTEDSTR('LISTADO DE HORAS DESDE EL ' + datetostr(nomlhdesde.Date) + ' HASTA EL ' + datetostr(nomlhhasta.Date)); informes.ShowReport(); end; procedure TBASE.Button11Click(Sender: TObject); var formaspago: string; begin formaspago := ''; if CheckBox4.Checked then formaspago := '-PAGO EN MANO'; if CheckBox5.Checked then formaspago := formaspago + '-PAGO POR BANCO'; if CheckBox6.Checked then formaspago := formaspago + '-OTROS'; formaspago := formaspago + '-'; dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add('select * from prenominas where correcto=1'); dm.qaux1.Open; if dm.qaux1.RecordCount > 0 then begin dm.qnominas.Open; dm.qnominas.Append; dm.qnominasidempresa.Value := 1; dm.qnominasnomempresa.Value := dm.tempresanombre.AsString; dm.qnominasFECHA.Value := Date; dm.qnominasfechainicio.Value := nomfechadesde.Date; dm.qnominasFECHAFIN.Value := nomfechahasta.Date; dm.qnominasPERIODO.Value := dm.qaux1.Fields[3].AsInteger; dm.qnominasNOMPERIODO.Value := 'Periodo desde el ' + datetostr(nomfechadesde.Date) + ' hasta el ' + datetostr(nomfechahasta.Date); dm.qnominasANYO.Value := dm.qaux1.Fields[2].AsInteger; dm.qnominasFORMAPAGO.Value := formaspago; if CheckBox6.Checked then dm.qnominasACTIVO.Value := 0 else dm.qnominasACTIVO.Value := 1; dm.qnominas.post; if dm.qaux1.RecordCount = 1 then begin dm.tnominasdetalle.Open; dm.tnominasdetalle.Append; dm.tnominasdetalle.Fields[1].Value := dm.qnominasID.AsInteger; dm.tnominasdetalle.Fields[2].Value := dm.tempresaid.AsInteger; dm.tnominasdetalle.Fields[3].Value := dm.qaux1.Fields[1].AsInteger; dm.tnominasdetalle.Fields[4].Value := dm.qaux1.Fields[2].AsInteger; dm.tnominasdetalle.Fields[5].Value := dm.qaux1.Fields[3].AsInteger; dm.tnominasdetalle.Fields[6].Value := dm.qaux1.Fields[4].AsString; dm.tnominasdetalle.Fields[7].Value := dm.qaux1.Fields[5].AsString; dm.tnominasdetalle.Fields[8].Value := dm.qaux1.Fields[6].AsString; dm.tnominasdetalle.Fields[9].Value := dm.qaux1.Fields[7].AsString; dm.tnominasdetalle.Fields[10].Value := dm.qaux1.Fields[8].AsString; dm.tnominasdetalle.Fields[11].Value := dm.qaux1.Fields[9].AsFloat; dm.tnominasdetalle.Fields[12].Value := dm.qaux1.Fields[10].AsDateTime; dm.tnominasdetalle.Fields[13].Value := dm.qaux1.Fields[11].AsDateTime; dm.tnominasdetalle.Fields[14].Value := dm.qaux1.Fields[12].AsInteger; dm.tnominasdetalle.Fields[15].Value := dm.qaux1.Fields[13].AsInteger; dm.tnominasdetalle.Fields[16].Value := dm.qaux1.Fields[14].AsInteger; dm.tnominasdetalle.Fields[17].Value := dm.qaux1.Fields[15].AsFloat; dm.tnominasdetalle.Fields[18].Value := dm.qaux1.Fields[16].AsFloat; dm.tnominasdetalle.Fields[19].Value := dm.qaux1.Fields[17].AsFloat; dm.tnominasdetalle.Fields[20].Value := dm.qaux1.Fields[18].AsFloat; dm.tnominasdetalle.Fields[21].Value := dm.qaux1.Fields[19].AsFloat; dm.tnominasdetalle.Fields[22].Value := dm.qaux1.Fields[20].AsFloat; dm.tnominasdetalle.Fields[23].Value := dm.qaux1.Fields[21].AsFloat; dm.tnominasdetalle.Fields[24].Value := dm.qaux1.Fields[22].AsFloat; dm.tnominasdetalle.Fields[25].Value := dm.qaux1.Fields[23].AsFloat; dm.tnominasdetalle.Fields[26].Value := dm.qaux1.Fields[24].AsFloat; dm.tnominasdetalle.Fields[27].Value := dm.qaux1.Fields[25].AsFloat; dm.tnominasdetalle.Fields[28].Value := dm.qaux1.Fields[26].AsFloat; dm.tnominasdetalle.Fields[29].Value := dm.qaux1.Fields[27].AsFloat; dm.tnominasdetalle.Fields[30].Value := dm.qaux1.Fields[28].AsFloat; dm.tnominasdetalle.Fields[31].Value := dm.qaux1.Fields[29].AsString; dm.tnominasdetalle.Fields[32].Value := dm.qaux1.Fields[30].AsDateTime; dm.tnominasdetalle.Fields[33].Value := dm.qaux1.Fields[31].AsString; dm.tnominasdetalle.Fields[34].Value := dm.qaux1.Fields[32].AsFloat; dm.tnominasdetalle.Fields[35].Value := dm.qaux1.Fields[33].AsInteger; dm.tnominasdetalle.Fields[36].Value := dm.qaux1.Fields[34].AsDateTime; dm.tnominasdetalle.Fields[37].Value := dm.qaux1.Fields[35].AsDateTime; dm.tnominasdetalle.Fields[38].Value := dm.qaux1.Fields[36].AsInteger; dm.tnominasdetalle.post; dm.qaux3.Close; dm.qaux3.SQL.Clear; dm.qaux3.SQL.Add('update trabajo_diario set estado=' + '''' + 'P' + '''' + ',control=-' + dm.tnominasdetalle.Fields[0].AsString + ' where control=' + dm.qaux1.Fields[0].AsString); dm.qaux3.ExecSQL; dm.qaux3.Close; dm.qaux3.SQL.Clear; dm.qaux3.SQL.Add('delete from prenominas where id=' + dm.qaux1.Fields[0] .AsString); dm.qaux3.ExecSQL; dm.qnominas.Refresh; dm.tprenominas.Refresh; end; if dm.qaux1.RecordCount > 1 then begin dm.tnominasdetalle.Open; while not dm.qaux1.Eof do begin dm.tnominasdetalle.Append; dm.tnominasdetalle.Fields[1].Value := dm.qnominasID.AsInteger; dm.tnominasdetalle.Fields[2].Value := dm.tempresaid.AsInteger; dm.tnominasdetalle.Fields[3].Value := dm.qaux1.Fields[1].AsInteger; dm.tnominasdetalle.Fields[4].Value := dm.qaux1.Fields[2].AsInteger; dm.tnominasdetalle.Fields[5].Value := dm.qaux1.Fields[3].AsInteger; dm.tnominasdetalle.Fields[6].Value := dm.qaux1.Fields[4].AsString; dm.tnominasdetalle.Fields[7].Value := dm.qaux1.Fields[5].AsString; dm.tnominasdetalle.Fields[8].Value := dm.qaux1.Fields[6].AsString; dm.tnominasdetalle.Fields[9].Value := dm.qaux1.Fields[7].AsString; dm.tnominasdetalle.Fields[10].Value := dm.qaux1.Fields[8].AsString; dm.tnominasdetalle.Fields[11].Value := dm.qaux1.Fields[9].AsFloat; dm.tnominasdetalle.Fields[12].Value := dm.qaux1.Fields[10].AsDateTime; dm.tnominasdetalle.Fields[13].Value := dm.qaux1.Fields[11].AsDateTime; dm.tnominasdetalle.Fields[14].Value := dm.qaux1.Fields[12].AsInteger; dm.tnominasdetalle.Fields[15].Value := dm.qaux1.Fields[13].AsInteger; dm.tnominasdetalle.Fields[16].Value := dm.qaux1.Fields[14].AsInteger; dm.tnominasdetalle.Fields[17].Value := dm.qaux1.Fields[15].AsFloat; dm.tnominasdetalle.Fields[18].Value := dm.qaux1.Fields[16].AsFloat; dm.tnominasdetalle.Fields[19].Value := dm.qaux1.Fields[17].AsFloat; dm.tnominasdetalle.Fields[20].Value := dm.qaux1.Fields[18].AsFloat; dm.tnominasdetalle.Fields[21].Value := dm.qaux1.Fields[19].AsFloat; dm.tnominasdetalle.Fields[22].Value := dm.qaux1.Fields[20].AsFloat; dm.tnominasdetalle.Fields[23].Value := dm.qaux1.Fields[21].AsFloat; dm.tnominasdetalle.Fields[24].Value := dm.qaux1.Fields[22].AsFloat; dm.tnominasdetalle.Fields[25].Value := dm.qaux1.Fields[23].AsFloat; dm.tnominasdetalle.Fields[26].Value := dm.qaux1.Fields[24].AsFloat; dm.tnominasdetalle.Fields[27].Value := dm.qaux1.Fields[25].AsFloat; dm.tnominasdetalle.Fields[28].Value := dm.qaux1.Fields[26].AsFloat; dm.tnominasdetalle.Fields[29].Value := dm.qaux1.Fields[27].AsFloat; dm.tnominasdetalle.Fields[30].Value := dm.qaux1.Fields[28].AsFloat; dm.tnominasdetalle.Fields[31].Value := dm.qaux1.Fields[29].AsString; dm.tnominasdetalle.Fields[32].Value := dm.qaux1.Fields[30].AsDateTime; dm.tnominasdetalle.Fields[33].Value := dm.qaux1.Fields[31].AsString; dm.tnominasdetalle.Fields[34].Value := dm.qaux1.Fields[32].AsFloat; dm.tnominasdetalle.Fields[35].Value := dm.qaux1.Fields[33].AsInteger; dm.tnominasdetalle.Fields[36].Value := dm.qaux1.Fields[34].AsDateTime; dm.tnominasdetalle.Fields[37].Value := dm.qaux1.Fields[35].AsDateTime; dm.tnominasdetalle.Fields[38].Value := dm.qaux1.Fields[36].AsInteger; dm.tnominasdetalle.post; dm.qaux3.Close; dm.qaux3.SQL.Clear; dm.qaux3.SQL.Add('update trabajo_diario set estado=' + '''' + 'P' + '''' + ',control=-' + dm.tnominasdetalle.Fields[0].AsString + ' where control=' + dm.qaux1.Fields[0].AsString); dm.qaux3.ExecSQL; dm.qaux3.Close; dm.qaux3.SQL.Clear; dm.qaux3.SQL.Add('delete from prenominas where id=' + dm.qaux1.Fields[0] .AsString); dm.qaux3.ExecSQL; dm.tprenominas.Refresh; dm.qaux1.Next; end; end; end else showmessage('DEBE SELECCIONAR AL MENOS UNA LINEA'); dm.qnominas.Close; dm.tnominasdetalle.Close; end; procedure TBASE.Button12Click(Sender: TObject); begin dm.tnominasdetalle.Delete; dm.qnominas.Refresh; // dm.qnominas.Last; end; procedure TBASE.Button13Click(Sender: TObject); begin dm.talmacenes.Close; dm.qalmacenes.Close; dmestadisticas.qcontenido.Close; dmestadisticas.qproduccion_almacen.Close; dm.talmacenes.Open; dm.qalmacenes.Open; dmestadisticas.qcontenido.Open; dmestadisticas.qproduccion_almacen.Open; end; procedure TBASE.bteimprimirClick(Sender: TObject); var archivo: string; begin { if not dmtr.qsalidas_sd.active then dmtr.qsalidas_sd.open else dmtr.qsalidas_sd.refresh; if not dmtr.qsalidas_ds.active then dmtr.qsalidas_ds.Open else dmtr.qsalidas_ds.refresh; if not dmtr.qinfentradas.active then dmtr.qinfentradas.Open else dmtr.qinfentradas.refresh; informedb.Datasource:=dmtr.dsqinfentradas;//dmestadisticas.dsqproduccionimpresion; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\loteentradas.fr3'); informes.Variables.Variables['TITULO']:=QUOTEDSTR('Entradas del LOTE: '+dmtr.qlotescodigo.asstring+' Trazabilidad: '+dmtr.qlotestrazabilidad.asstring); informes.Variables.Variables['FECHA1']:=QUOTEDSTR('F.Cosecha'); informes.Variables.Variables['FECHA2']:=QUOTEDSTR('F.Trabajo'); informes.ShowReport(); informes.Clear; informedb.Datasource:=dmtr.dsqsalidas_sd;//dmestadisticas.dsqproduccionimpresion; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\loteentradas.fr3'); informes.Variables.Variables['TITULO']:=QUOTEDSTR('Envasados del LOTE: '+dmtr.qlotescodigo.asstring+' Trazabilidad: '+dmtr.qlotestrazabilidad.asstring); informes.Variables.Variables['FECHA1']:=QUOTEDSTR('F.Elav.'); informes.Variables.Variables['FECHA2']:=QUOTEDSTR('F.Remani.'); informes.ShowReport(); informes.Clear; informedb.Datasource:=dmtr.dsqsalidas_ds;//dmestadisticas.dsqproduccionimpresion; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\loteentradas.fr3'); informes.Variables.Variables['TITULO']:=QUOTEDSTR('Desechos del LOTE: '+dmtr.qlotescodigo.asstring+' Trazabilidad: '+dmtr.qlotestrazabilidad.asstring); informes.Variables.Variables['FECHA1']:=QUOTEDSTR('F.Elav.'); informes.Variables.Variables['FECHA2']:=QUOTEDSTR('F.Remani.'); informes.ShowReport(); informes.Clear } case listaimpresion.ItemIndex of 1: begin dm.qinftrabajadores.Close; dm.qinftrabajadores.SQL.Clear; dm.qinftrabajadores.SQL.Add ('select * from trabajadores where seleccionado=1'); dm.qinftrabajadores.Open; informedb.DataSource := dm.dsqinftrabajadores; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\tarjeta2.fr3'); informes.ShowReport(); end; 0: begin dm.qinftrabajadores.Close; dm.qinftrabajadores.SQL.Clear; dm.qinftrabajadores.SQL.Add('select * from trabajadores where id=' + qempleadosid.AsString); dm.qinftrabajadores.Open; informedb.DataSource := dm.dsqinftrabajadores; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\FICHAEMPLEADO.fr3'); informes.ShowReport(); end; 2: begin qauxemp.Close; qauxemp.Open; if qauxemp.RecordCount = 0 then showmessage('¡¡¡ DEBE SELECCIONAR AL MENOS UN EMPLEADO ¡¡¡') else begin informedb.DataSource := dsqauxemp; informes.Report.Clear; informes.LoadFromFile ('c:\agrigest\informes\plantillapartetrabajo.fr3'); informes.Variables.Variables['v_cuadrilla'] := QUOTEDSTR(qgrupostrabajadores2descripcion.AsString); informes.Variables.Variables['v_trabajadores'] := QUOTEDSTR(inttostr(qempleados.RecordCount)); informes.ShowReport(); qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=0'); qaux.ExecSQL; qempleados.Close; qempleados.Open; checktodos2.Checked := false; end; end; 3: begin qauxemp.Close; qauxemp.Open; if qauxemp.RecordCount = 0 then showmessage('¡¡¡ DEBE SELECCIONAR AL MENOS UN EMPLEADO ¡¡¡') else begin informedb.DataSource := dsqauxemp; informes.Report.Clear; informes.LoadFromFile ('c:\agrigest\informes\plantillapartesemanal.fr3'); informes.Variables.Variables['v_cuadrilla'] := QUOTEDSTR(qgrupostrabajadores2descripcion.AsString); informes.Variables.Variables['v_trabajadores'] := QUOTEDSTR(inttostr(qempleados.RecordCount)); informes.ShowReport(); qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=0'); qaux.ExecSQL; qempleados.Close; qempleados.Open; checktodos2.Checked := false; end; end; 4: begin qauxemp.Close; qauxemp.Open; if qauxemp.RecordCount = 0 then showmessage('¡¡¡ DEBE SELECCIONAR AL MENOS UN EMPLEADO ¡¡¡') else begin informedb.DataSource := dsqauxemp; informes.Report.Clear; informes.LoadFromFile ('c:\agrigest\informes\plantillapartealmacen.fr3'); informes.Variables.Variables['v_cuadrilla'] := QUOTEDSTR(qgrupostrabajadores2descripcion.AsString); informes.Variables.Variables['v_trabajadores'] := QUOTEDSTR(inttostr(qempleados.RecordCount)); informes.ShowReport(); qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=0'); qaux.ExecSQL; qempleados.Close; qempleados.Open; checktodos2.Checked := false; end; end; 5: begin qauxemp.Close; qauxemp.Open; if qauxemp.RecordCount = 0 then showmessage('¡¡¡ DEBE SELECCIONAR AL MENOS UN EMPLEADO ¡¡¡') else begin informedb.DataSource := dsqauxemp; informes.Report.Clear; informes.LoadFromFile ('c:\agrigest\informes\plantillacontratacion.fr3'); informes.ShowReport(); qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=0'); qaux.ExecSQL; qempleados.Close; qempleados.Open; checktodos2.Checked := false; end; end; 6: begin qauxemp.Close; qauxemp.Open; SaveDialog1.FileName := 'PLANTILLA EXTINCION.xls'; SaveDialog1.Execute(); archivo := SaveDialog1.FileName; try ExportaraExcel(archivo, 'PLANTILLA EXTINCION', gridplantillaext); finally showmessage('Los datos han sido exportados correctamente a ' + archivo); end; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=0'); qaux.ExecSQL; qempleados.Close; qempleados.Open; checktodos2.Checked := false; end; 7: begin qauxemp.Close; qauxemp.Open; SaveDialog1.FileName := 'PLANTILLA COMUNICACION.xls'; SaveDialog1.Execute(); archivo := SaveDialog1.FileName; try ExportaraExcel(archivo, 'PLANTILLA COMUNICACION', gridplantillacomu); finally showmessage('Los datos han sido exportados correctamente a ' + archivo); end; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=0'); qaux.ExecSQL; qempleados.Close; qempleados.Open; checktodos2.Checked := false; end; end; end; procedure TBASE.btactualizarClick(Sender: TObject); var anyo, mes, dia: word; fecha, fecha2, almacen, empresa, ventrancajas, ventrankg, vkilosremanipulados, ventrancajasremanipuladas, vcostocosechar, vkiloscosechados, vtipotrabajo, vkilosrecibidos, vkilostraspasados,vcajasdesperdicios,vkilosdesperdicios: string; vcostocosecharrecibidos, vcostecierre,vcostocosechartraspasados, vcostesinmt, vcostemanipulacion: string; horas, costo,vrecargoss: string; vfecha: tdatetime; id, valmacen, vempresa: Integer; c_cosechar: real; begin decodedate(dmproduccion.qpartesdiariosfecha.AsDateTime, anyo, mes, dia); fecha := '''' + inttostr(anyo) + '-' + inttostr(mes) + '-' + inttostr(dia) + ''''; almacen := dmproduccion.qpartesdiariosalmacen.AsString; empresa := dmproduccion.qpartesdiariosidempresa.AsString; valmacen := dmproduccion.qpartesdiariosalmacen.AsInteger; vempresa := dmproduccion.qpartesdiariosidempresa.AsInteger; vfecha := dmproduccion.qpartesdiariosfecha.AsDateTime; qaux.SQL.Clear; qaux.SQL.Add('select porc_segsocial from empresa where id=' + empresa); qaux.Open; vrecargoss:='1.'+qaux.Fields[0].AsString; qaux.SQL.Clear; qaux.SQL.Add('select tipo_trabajo from almacenes where id=' + almacen + ' and idempresa=' + empresa); qaux.Open; vtipotrabajo := '''' + qaux.Fields[0].AsString + ''''; /// envases que entran /// qaux.SQL.Clear; qaux.SQL.Add('select sum(num_envases) from v_ea_pesadaslotes where iddestino=' + almacen + ' and fechatrabajo=' + fecha + ' and es_entrada=1 and remanipulado=0 and mprima_p in (select id from materias_primas where desechos=0)'); qaux.Open; ventrancajas := qaux.Fields[0].AsString; if ventrancajas = '' then ventrancajas := '0'; /// kilos netos que entran qaux.SQL.Clear; qaux.SQL.Add('select sum(peso_neto) from v_ea_pesadaslotes where iddestino=' + almacen + ' and fechatrabajo=' + fecha + ' and es_entrada=1 and remanipulado=0 and mprima_p in (select id from materias_primas where desechos=0)'); qaux.Open; ventrankg := qaux.Fields[0].AsString; if ventrankg = '' then ventrankg := '0'; ventrankg := stringreplace(ventrankg, ',', '.', [rfReplaceAll, rfIgnoreCase]); /// kilos netos y envases que entran remanipulados qaux.SQL.Clear; qaux.SQL.Add ('select sum(peso_neto),sum(num_envases) from v_ea_pesadaslotes where iddestino=' + almacen + ' and fechatrabajo=' + fecha + ' and remanipulado=1'); qaux.Open; vkilosremanipulados := qaux.Fields[0].AsString; if vkilosremanipulados = '' then vkilosremanipulados := '0'; vkilosremanipulados := stringreplace(vkilosremanipulados, ',', '.', [rfReplaceAll, rfIgnoreCase]); ventrancajasremanipuladas := qaux.Fields[1].AsString; if ventrancajasremanipuladas = '' then ventrancajasremanipuladas := '0'; { /// envases que entran remanipulados qaux.SQL.Clear; qaux.SQL.Add('select sum(num_envases) from v_ea_pesadaslotes where iddestino='+almacen+' and fechatrabajo='+fecha+' and remanipulado=1'); qaux.open; ventrancajasremanipuladas:=qaux.Fields[0].AsString; if ventrancajasremanipuladas='' then ventrancajasremanipuladas:='0'; } dmproduccion.qentran.Close; dmproduccion.qentran.Prepare; dmproduccion.qentran.ParamByName('ALMACEN').AsInteger := valmacen; dmproduccion.qentran.ParamByName('FECHA').AsDate := vfecha; dmproduccion.qentran.Open; qaux.SQL.Clear; qaux.SQL.Add('update almacenes_partesdiarios a set entran_cajas_remani=' + ventrancajasremanipuladas + ',kilos_remanipulacion=' + vkilosremanipulados + ',entran_kg=' + ventrankg + ',entran_cajas=' + ventrancajas + ' where almacen=' + almacen + ' and a.fecha=' + fecha); qaux.ExecSQL; /// coste de cosechar kilos en camara qaux2.SQL.Clear; qaux2.SQL.Add ('select distinct(fecha) from ea_pesadas where idea>0 and iddestino=' + almacen + ' and fechatrabajo=' + fecha + ''); qaux2.Open; if qaux2.RecordCount > 0 then begin while not qaux2.Eof do begin decodedate(qaux2.Fields[0].AsDateTime, anyo, mes, dia); fecha2 := '''' + inttostr(anyo) + '-' + inttostr(mes) + '-' + inttostr(dia) + ''''; qaux.SQL.Clear; qaux.SQL.Add('select kiloscosechados from v_cosechadia where empresa=' + empresa + ' and fecha=' + fecha2 + ' and tipotrabajo=' + vtipotrabajo); qaux.Open; vkiloscosechados := qaux.Fields[0].AsString; if vkiloscosechados = '' then vkiloscosechados := '0'; vkiloscosechados := stringreplace(vkiloscosechados, ',', '.', [rfReplaceAll, rfIgnoreCase]); if vkiloscosechados <> '0' then begin qaux.SQL.Clear; qaux.SQL.Add ('select (total*'+vrecargoss+')/' + vkiloscosechados + ' from v_trabajosdia where empresa=' + empresa + ' and fecha=' + fecha2 + ' and tipotrabajo=' + vtipotrabajo); qaux.Open; vcostocosechar := qaux.Fields[0].AsString; end else vcostocosechar := '0'; if vcostocosechar = '' then vcostocosechar := '0'; vcostocosechar := stringreplace(vcostocosechar, ',', '.', [rfReplaceAll, rfIgnoreCase]); qaux.SQL.Clear; qaux.SQL.Add('update ea_pesadas as ea set ea.id_palet2=' + '''' + 'FACTURANDO' + '''' + ',ea.costo_cosechar=ea.peso_neto*' + vcostocosechar + ' WHERE ea.iddestino=' + almacen + ' and ea.fecha=' + fecha2 + ' and ea.fechatrabajo=' + fecha); qaux.ExecSQL; qaux.SQL.Clear; qaux.SQL.Add('update ea_pesadas as ea set ea.id_palet2=' + '''' + 'FACTURANDO' + '''' + ',ea.costo_cosechar=0 WHERE ea.iddestino=' + almacen + ' and ea.fecha=' + fecha2 + ' and ea.fechatrabajo=' + fecha + ' and ea.tipo_trabajo=' + '''' + ''''); qaux.ExecSQL; qaux2.Next; end; qaux.SQL.Clear; qaux.SQL.Add ('select sum(costo_cosechar) from v_ea_pesadaslotes where iddestino=' + almacen + ' and fechatrabajo=' + fecha + ' and remanipulado=1'); qaux.Open; if qaux.Fields[0].AsString <> '0' then c_cosechar := c_cosechar + qaux.Fields[0].AsFloat else c_cosechar := 0; qaux.SQL.Clear; qaux.SQL.Add ('select sum(costetotal) from v_costesrestosdia where fecha=(select fecha from almacenes_partesdiarios where fecha=' + fecha + ' and idempresa=' + empresa + ' and almacen=' + almacen + ' limit 1) and ide=' + empresa + ' and idalmacen=' + almacen); qaux.Open; if qaux.Fields[0].AsString <> '0' then c_cosechar := c_cosechar + qaux.Fields[0].AsFloat; qaux.SQL.Clear; qaux.SQL.Add ('select sum(costetotal) from v_costesrestosdia where fecha=' + fecha + ' and ide=' + empresa + ' and idalmacen=' + almacen ); qaux.Open; if qaux.Fields[0].AsString <> '0' then c_cosechar := c_cosechar - qaux.Fields[0].AsFloat; vcostecierre:= floattostr(qaux.fields[0].asfloat); vcostocosechar := floattostr(c_cosechar); if vcostocosechar = '' then vcostocosechar := '0'; vcostocosechar := stringreplace(vcostocosechar, ',', '.', [rfReplaceAll, rfIgnoreCase]); if vcostecierre = '' then vcostecierre := '0'; vcostecierre := stringreplace(vcostecierre, ',', '.', [rfReplaceAll, rfIgnoreCase]); qaux.SQL.Clear; qaux.SQL.Add('update almacenes_partesdiarios a set coste_cierre='+vcostecierre+',coste_corte_remanipu=' + vcostocosechar +' where almacen=' + almacen + ' and a.fecha=' + fecha); qaux.ExecSQL; end; /// envases,envases de venta, kilos y kilos venta,kilos producidos que salen dmproduccion.qsalen.Close; dmproduccion.qsalen.Prepare; dmproduccion.qsalen.ParamByName('ALMACEN').AsInteger := valmacen; dmproduccion.qsalen.ParamByName('FECHA').AsDate := vfecha; dmproduccion.qsalen.ParamByName('ALMACEN2').AsInteger := valmacen; dmproduccion.qsalen.ParamByName('FECHA2').AsDate := vfecha; dmproduccion.qsalen.Open; dmproduccion.qdesperdicios.Close; dmproduccion.qdesperdicios.Prepare; dmproduccion.qdesperdicios.ParamByName('ALMACEN').AsInteger := valmacen; dmproduccion.qdesperdicios.ParamByName('FECHA').AsDate := vfecha; dmproduccion.qdesperdicios.Open; dmproduccion.qactualizar.SQL.Clear; dmproduccion.qactualizar.SQL.Add ('update almacenes_partesdiarios a set salen_cajas=' + dmproduccion.qsalennum_envases.AsString + ',salen_cajas_venta=' + dmproduccion.qsalennum_envases.AsString + ',salen_kg=' + stringreplace(dmproduccion.qsalenpeso_neto.AsString, ',', '.', [rfReplaceAll, rfIgnoreCase]) + ',kg_producidos_venta=' + stringreplace(dmproduccion.qsalenpeso_neto_venta.AsString, ',', '.', [rfReplaceAll, rfIgnoreCase]) + ',kg_producidos=' + stringreplace(dmproduccion.qsalenpeso_neto.AsString, ',', '.', [rfReplaceAll, rfIgnoreCase])); // dmproduccion.qactualizar.SQL.Add('update almacenes_partesdiarios a set salen_cajas=(select sum(num_envases) from v_ea_pesadaslotes where idorigen='+almacen+' and (fecha=a.fecha) and idea=0 and mprima_p in (select id from materias_primas where desechos=0))'); dmproduccion.qactualizar.SQL.Add(' where almacen=' + almacen + ' and a.fecha=' + fecha); dmproduccion.qactualizar.ExecSQL; /// kilos que salen revisar // dmproduccion.qactualizar.SQL.Clear; // dmproduccion.qactualizar.SQL.Add('update almacenes_partesdiarios a set salen_kg=(select sum(peso_neto) from v_ea_pesadaslotes where idorigen='+almacen+' and (fecha=a.fecha) and idea=0 and mprima_p in (select id from materias_primas where desechos=0))'); // dmproduccion.qactualizar.SQL.Add(' where almacen='+almacen+' and a.fecha='+fecha); // dmproduccion.qactualizar.ExecSQL; { /// envases que salen venta revisar dmproduccion.qactualizar.SQL.Clear; dmproduccion.qactualizar.SQL.Add('update almacenes_partesdiarios a set salen_cajas_venta=(select sum(num_envases) from v_ea_pesadaslotes where idorigen='+almacen+' and (fecha=a.fecha) and idea=0 and mprima_p in (select id from materias_primas where desechos=0))'); dmproduccion.qactualizar.SQL.Add(' where almacen='+almacen+' and a.fecha='+fecha); dmproduccion.qactualizar.ExecSQL; } /// kilos producidos venta revisar // dmproduccion.qactualizar.SQL.Clear; // dmproduccion.qactualizar.SQL.Add('update almacenes_partesdiarios a set kg_producidos_venta=(select sum(peso_neto_teorico) from v_ea_pesadaslotes where idorigen='+almacen+' and (fecha=a.fecha) and idea=0 and mprima_p in (select id from materias_primas where desechos=0))'); // dmproduccion.qactualizar.SQL.Add(' where almacen='+almacen+' and a.fecha='+fecha); // dmproduccion.qactualizar.ExecSQL; /// kilos producidos revisar // dmproduccion.qactualizar.SQL.Clear; // dmproduccion.qactualizar.SQL.Add('update almacenes_partesdiarios a set kg_producidos=(select sum(peso_neto) from v_ea_pesadaslotes where idorigen='+almacen+' and (fecha=a.fecha) and idea=0 and mprima_p in (select id from materias_primas where desechos=0))'); // dmproduccion.qactualizar.SQL.Add(' where almacen='+almacen+' and a.fecha='+fecha); // dmproduccion.qactualizar.ExecSQL; /// kilos y envases de desperdicios vcajasdesperdicios:=stringreplace(dmproduccion.qdesperdiciosnum_envases.AsString, ',', '.', [rfReplaceAll, rfIgnoreCase]); vkilosdesperdicios:=stringreplace(dmproduccion.qdesperdiciospeso_neto.AsString, ',', '.', [rfReplaceAll, rfIgnoreCase]); if vcajasdesperdicios='' then vcajasdesperdicios:='0'; if vkilosdesperdicios='' then vkilosdesperdicios:='0'; dmproduccion.qactualizar.SQL.Clear; dmproduccion.qactualizar.SQL.Add ('update almacenes_partesdiarios a set salen_envases_desp=' + vcajasdesperdicios + ',kg_desperdicios=' +vkilosdesperdicios); // dmproduccion.qactualizar.SQL.Add('update almacenes_partesdiarios a set kg_desperdicios=(select sum(peso_neto) from v_ea_pesadaslotes where idorigen='+almacen+' and (fecha=a.fecha or fechatrabajo=a.fecha) and idea=0 and mprima_p in (select id from materias_primas where desechos=1))'); dmproduccion.qactualizar.SQL.Add(' where almacen=' + almacen + ' and a.fecha=' + fecha); dmproduccion.qactualizar.ExecSQL; /// envases desperdicios revisar // dmproduccion.qactualizar.SQL.Clear; // dmproduccion.qactualizar.SQL.Add('update almacenes_partesdiarios a set salen_envases_desp=(select sum(num_envases) from v_ea_pesadaslotes where idorigen='+almacen+' and fecha=a.fecha and idea=0 and mprima_p in (select id from materias_primas where desechos=1))'); // dmproduccion.qactualizar.SQL.Add(' where almacen='+almacen+' and a.fecha='+fecha); // dmproduccion.qactualizar.ExecSQL; // costo materia prima dmproduccion.qactualizar.SQL.Clear; dmproduccion.qactualizar.SQL.Add ('update almacenes_partesdiarios a set costo_kg_mprima=(select sum(costo_sinmt) from v_ea_pesadaslotes where iddestino=' + almacen + ' and fechatrabajo=a.fecha and idea>0 and remanipulado=0) where a.almacen=' + almacen + ' and a.fecha=' + fecha); dmproduccion.qactualizar.ExecSQL; // costo materia prima remanipulada dmproduccion.qactualizar.SQL.Clear; dmproduccion.qactualizar.SQL.Add ('update almacenes_partesdiarios a set costo_kg_mprima_remanip=(select sum(costo_sinmt) from v_ea_pesadaslotes where iddestino=' + almacen + ' and fechatrabajo=a.fecha and remanipulado=1) where a.almacen=' + almacen + ' and a.fecha=' + fecha); dmproduccion.qactualizar.ExecSQL; /// costo generadores dmproduccion.qactualizar.SQL.Clear; dmproduccion.qactualizar.SQL.Add ('update almacenes_partesdiarios a set costo_gen_camara=(select sum(gen_caja*num_envases)*(select coste_kg_gen from empresa where id=' + dmproduccion.qpartesdiariosidempresa.AsString + ') from ea_pesadas where iddestino=' + almacen + ' and fechatrabajo=a.fecha and idea<>0) where almacen=' + almacen + ' and a.fecha=' + fecha); dmproduccion.qactualizar.ExecSQL; /// costo camara { qaux.sql.clear; qaux.sql.add('update ea_pesadas set id_palet2='+''''+'TRIGGER_OFF'+''''+',costo_camara=peso_neto*0.002*dias_camara where dias_camara>0 and fechatrabajo='+fecha+' and iddestino='+almacen); qaux.execsql; } dmproduccion.qactualizar.SQL.Clear; dmproduccion.qactualizar.SQL.Add ('update almacenes_partesdiarios a set costo_acumulado=(select sum(costo_camara) from v_ea_pesadaslotes where iddestino=' + almacen + ' and fechatrabajo=a.fecha ) where almacen=' + almacen + ' and a.fecha=' + fecha); // and idea<>0 dmproduccion.qactualizar.ExecSQL; /// horas de campo realizadas en el dia en comentario porque no se muestra /// costo de los jornales en el campo dmproduccion.qactualizar.SQL.Clear; dmproduccion.qactualizar.SQL.Add ('update almacenes_partesdiarios a set costo_jornales_campo=(select sum(costo_cosechar) from v_ea_pesadaslotes where iddestino=' + almacen + ' and fechatrabajo=a.fecha and remanipulado=0) where almacen=' + almacen + ' and a.fecha=' + fecha); dmproduccion.qactualizar.ExecSQL; /// horas y costo de manipulacion del dia qaux.SQL.Clear; qaux.SQL.Add('select sum(horas),sum(total) from v_trabajosdia where empresa=' + empresa + ' and fecha=' + fecha + ' and tipotrabajo in (select id from tipo_trabajo where almacen_trabajo=' + almacen + ' and coste_elavoracion_almacen=1)'); qaux.Open; if qaux.Fields[0].AsString = '' then begin horas := '0'; costo := '0'; end else begin horas := stringreplace(qaux.Fields[0].AsString, ',', '.', [rfReplaceAll, rfIgnoreCase]); costo := stringreplace(qaux.Fields[1].AsString, ',', '.', [rfReplaceAll, rfIgnoreCase]); end; dmproduccion.qactualizar.SQL.Clear; dmproduccion.qactualizar.SQL.Add ('update almacenes_partesdiarios a set horas_jornales=' + horas + ',costo_jornales=' + costo + ' where almacen=' + almacen + ' and a.fecha=' + fecha); dmproduccion.qactualizar.ExecSQL; /// costo de manipulacion /// costo de limpieza qaux.SQL.Clear; qaux.SQL.Add('select sum(horas),sum(total) from v_trabajosdia where empresa=' + empresa + ' and fecha=' + fecha + ' and tipotrabajo in (select id from tipo_trabajo where almacen_trabajo=' + almacen + ' and elavoracion_produccion=1)'); qaux.Open; if qaux.Fields[0].AsString = '' then begin horas := '0'; costo := '0'; end else begin horas := stringreplace(qaux.Fields[0].AsString, ',', '.', [rfReplaceAll, rfIgnoreCase]); costo := stringreplace(qaux.Fields[1].AsString, ',', '.', [rfReplaceAll, rfIgnoreCase]); end; dmproduccion.qactualizar.SQL.Clear; dmproduccion.qactualizar.SQL.Add ('update almacenes_partesdiarios a set coste_limpieza=' + costo + ' where almacen=' + almacen + ' and a.fecha=' + fecha); dmproduccion.qactualizar.ExecSQL; /// /// costo de envasado qaux.SQL.Clear; qaux.SQL.Add('select sum(horas),sum(total) from v_trabajosdia where empresa=' + empresa + ' and fecha=' + fecha + ' and tipotrabajo in (select id from tipo_trabajo where almacen_trabajo=' + almacen + ' and envasado_produccion=1)'); qaux.Open; if qaux.Fields[0].AsString = '' then begin horas := '0'; costo := '0'; end else begin horas := stringreplace(qaux.Fields[0].AsString, ',', '.', [rfReplaceAll, rfIgnoreCase]); costo := stringreplace(qaux.Fields[1].AsString, ',', '.', [rfReplaceAll, rfIgnoreCase]); end; dmproduccion.qactualizar.SQL.Clear; dmproduccion.qactualizar.SQL.Add ('update almacenes_partesdiarios a set coste_envasado=' + costo + ' where almacen=' + almacen + ' and a.fecha=' + fecha); dmproduccion.qactualizar.ExecSQL; /// costo de apoyo qaux.SQL.Clear; qaux.SQL.Add('select sum(horas),sum(total) from v_trabajosdia where empresa=' + empresa + ' and fecha=' + fecha + ' and tipotrabajo in (select id from tipo_trabajo where almacen_trabajo=' + almacen + ' and logistica_produccion=1)'); qaux.Open; if qaux.Fields[0].AsString = '' then begin horas := '0'; costo := '0'; end else begin horas := stringreplace(qaux.Fields[0].AsString, ',', '.', [rfReplaceAll, rfIgnoreCase]); costo := stringreplace(qaux.Fields[1].AsString, ',', '.', [rfReplaceAll, rfIgnoreCase]); end; dmproduccion.qactualizar.SQL.Clear; dmproduccion.qactualizar.SQL.Add ('update almacenes_partesdiarios a set coste_apoyo=' + costo + ' where almacen=' + almacen + ' and a.fecha=' + fecha); dmproduccion.qactualizar.ExecSQL; /// costo de los materiales recuperados dmproduccion.qactualizar.SQL.Clear; dmproduccion.qactualizar.SQL.Add ('update almacenes_partesdiarios a set coste_env_rec=(select sum(precio) from ea_materiales where recuperado=-1 and (ide,idea,idea2) in '); dmproduccion.qactualizar.SQL.Add ('(select idempresa,id,idea from ea_pesadas where idempresa=' + empresa + ' and fechatrabajo=' + fecha + ' and iddestino=' + almacen); dmproduccion.qactualizar.SQL.Add(')) where a.idempresa=' + empresa + ' and almacen=' + almacen + ' and a.fecha=' + fecha); { dmproduccion.qactualizar.SQL.Add ('update almacenes_partesdiarios a set coste_env_rec=(select sum(costo_materiales) FROM ea_pesadas ea '); // v_ea_pesadaslotes ea '); dmproduccion.qactualizar.SQL.Add(' WHERE ea.idempresa=' + empresa + ' and ea.iddestino=' + almacen + ' and ea.recuperar_envases=1 and ea.fechatrabajo=' + fecha); dmproduccion.qactualizar.SQL.Add(') where a.idempresa=' + empresa + ' and a.almacen=' + almacen + ' and a.fecha=' + fecha); } dmproduccion.qactualizar.ExecSQL; /// costo de los materiales empleados dmproduccion.qactualizar.SQL.Clear; dmproduccion.qactualizar.SQL.Add ('update almacenes_partesdiarios a set costo_materiales=(select sum(precio) from ea_materiales where (ide,idea,idea2) in '); dmproduccion.qactualizar.SQL.Add ('(select idempresa,id,idea from ea_pesadas where idempresa=' + empresa + ' and fechatrabajo=' + fecha + ' and idea<>0 and iddestino=' + almacen); dmproduccion.qactualizar.SQL.Add(' union '); dmproduccion.qactualizar.SQL.Add (' select idempresa,id,idea from ea_pesadas where idempresa=' + empresa + ' and fecha=' + fecha + ' and idea=0 and idorigen=' + almacen + ')'); dmproduccion.qactualizar.SQL.Add(') where a.idempresa=' + empresa + ' and almacen=' + almacen + ' and a.fecha=' + fecha); dmproduccion.qactualizar.ExecSQL; id := dmproduccion.qpartesdiariosid.AsInteger; dmproduccion.qpartesdiarios.Refresh; // Refresh; dmproduccion.qpartesdiarios.Locate('id', id, [locaseinsensitive, lopartialkey]); /// costo sin materiales de los palets elaborados vcostesinmt := dmproduccion.qpartesdiarioscostekgfinal_sinmt.AsString; if vcostesinmt = '' then vcostesinmt := '0'; vcostesinmt := stringreplace(vcostesinmt, ',', '.', [rfReplaceAll, rfIgnoreCase]); vcostemanipulacion := floattostr(dmproduccion.qpartesdiariostotal_costes_jornales.AsFloat / dmproduccion.qpartesdiarioskg_producidos_venta.AsFloat); if vcostemanipulacion = '' then vcostemanipulacion := '0'; vcostemanipulacion := stringreplace(vcostemanipulacion, ',', '.', [rfReplaceAll, rfIgnoreCase]); qaux.SQL.Clear; qaux.SQL.Add('update ea_pesadas as ea set ea.coste_manipulacion=' + vcostemanipulacion + '*peso_neto,ea.id_palet2=' + '''' + 'ACTUALIZANDO' + '''' + ',temperatura=' + vcostesinmt + ' WHERE ea.fecha=' + fecha + ' and idea<=0 and idorigen=' + almacen); /// le he quitado +coste_manipulacion qaux.ExecSQL; end; procedure TBASE.Articulos1Click(Sender: TObject); begin infarticulos := Tinfarticulos.Create(nil); try infarticulos.ShowModal(); finally infarticulos.Free; end; end; procedure TBASE.ArticulosComponentes1Click(Sender: TObject); begin articulos := Tarticulos.Create(nil); try articulos.ShowModal(); finally articulos.Free; end; end; procedure TBASE.baaceptarClick(Sender: TObject); begin dm.talmacenes.post; // dm.qalmacenes.refresh; baanadir.Enabled := true; bamodificar.Enabled := true; baborrar.Enabled := true; bacancelar.Enabled := false; baaceptar.Enabled := false; end; procedure TBASE.baanadirClick(Sender: TObject); begin dm.qalmacenes.Close; dm.talmacenes.Append; DBEdit107.SetFocus; baanadir.Enabled := false; bamodificar.Enabled := false; baborrar.Enabled := false; bacancelar.Enabled := true; baaceptar.Enabled := true; end; procedure TBASE.BTLaceptarClick(Sender: TObject); begin // dbedit116.setfocus; dmtr.qlotes.post; dmtr.qlotes.Refresh; if dmtr.qlotes.State in [dsinsert, dsedit] then begin btlnuevo.Visible := false; btLmodificar.Visible := false; btLguardar.Visible := true; btLcancelar.Visible := true; end else begin btlnuevo.Visible := true; btLmodificar.Visible := true; btLguardar.Visible := false; btLcancelar.Visible := false; end; btlnuevo.SetFocus; end; procedure TBASE.Button14Click(Sender: TObject); var estacion: string; dia, mes, anyo: word; dia2, mes2, anyo2: real; Document: IHtmlDocument2; begin decodedate(fechaestacion.Date, anyo, mes, dia); estacion := Edit1.Text; // PAGE.Navigate( 'https://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID='+estacion+'&day='+floattostr(dia)+'&month='+floattostr(mes)+'&year='+floattostr(anyo)+'&graphspan=day&format=1'); // document:=page.Document as ihtmldocument2; // PAGE.Text := ObtenerWeb('http://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID=IMONFORT8&day=3&month=2&year=2017&graphspan=day&format=1'); PAGE2.Lines.Add(Trim(Document.body.innertext)) end; procedure TBASE.Button15Click(Sender: TObject); var url: array [0 .. 255] of WideChar; Cadena, X, Y: string; begin X := dm.qparcelasx.AsString; Y := dm.qparcelasy.AsString; stringreplace(X, '.', ',', [rfReplaceAll]); stringreplace(Y, ',', '.', [rfReplaceAll]); Cadena := 'https://www.google.es/maps/place/' + X + ',' + Y; stringtowidechar(Cadena, url, 256); ShellExecute(Handle, 'open', 'iexplore.exe', url, nil, SW_NORMAL); end; procedure TBASE.Button16Click(Sender: TObject); var url: array [0 .. 255] of WideChar; Cadena: string; begin Cadena := 'http://sigpac.mapa.es/fega/visor/?provincia=' + dm.qparcelassigpac_prov.AsString + '&municipio=' + dm.qparcelassigpac_muni.AsString + '&AGREGADO=' + dm.qparcelassigpac_agre.AsString + '&zona=' + dm.qparcelassigpac_zona.AsString + '&poligono=' + dm.qparcelassigpac_poli.AsString + '&parcela=' + dm.qparcelassigpac_pacr.AsString + '&recinto=' + dm.qparcelassigpac_recinto.AsString; stringtowidechar(Cadena, url, 256); ShellExecute(Handle, 'open', 'iexplore.exe', url, nil, SW_NORMAL); end; procedure TBASE.Button17Click(Sender: TObject); var anyo, mes, dia, hora, minutos, segundos, milisegundos: word; txanyo, txmes, txdia, txhora, txminutos, txsegundos, txnumlineas, txcantidadtotal, txlinea, txcuenta, txdireccion2: string; txnombre, txdireccion, txtotalapagar, txnif, txbic: string; linea: real; F: TextFile; begin decodedate(Date(), anyo, mes, dia); decodetime(Date(), hora, minutos, segundos, milisegundos); txanyo := floattostr(anyo); txmes := floattostr(mes); txdia := floattostr(dia); txhora := floattostr(hora); txminutos := floattostr(minutos); txsegundos := floattostr(segundos); txnumlineas := dm.qnominascant_lineas.AsString; txcantidadtotal := FormatFloat(',0.00', dm.qnominasIMPORTETOTAL.AsFloat); txcantidadtotal := stringreplace(txcantidadtotal, '.', '', [rfReplaceAll]); txcantidadtotal := stringreplace(txcantidadtotal, ',', '.', [rfReplaceAll]); txnif := dm.tempresacif.AsString; txcuenta := dm.tempresacc_iban.AsString + dm.tempresacc_entidad.AsString + dm.tempresacc_oficina.AsString + dm.tempresacc_dc.AsString + dm.tempresacc_cc.AsString; txnombre := dm.tempresanombre.AsString; txnombre := stringreplace(txnombre, 'Ñ', 'N', [rfReplaceAll]); txnombre := stringreplace(txnombre, '/', '?', [rfReplaceAll]); txnombre := stringreplace(txnombre, 'º', '?', [rfReplaceAll]); txbic := dm.tempresacc_bic.AsString; txdireccion := dm.tempresadireccion.AsString; txdireccion2 := dm.tempresacodpost.AsString + ' ' + dm.tempresapoblacion.AsString + ' . .'; txdireccion := stringreplace(txdireccion, '/', '?', [rfReplaceAll]); txdireccion := stringreplace(txdireccion, 'º', '?', [rfReplaceAll]); txdireccion := stringreplace(txdireccion, 'Ñ', 'N', [rfReplaceAll]); txdireccion2 := stringreplace(txdireccion2, '/', '?', [rfReplaceAll]); txdireccion2 := stringreplace(txdireccion2, 'º', '?', [rfReplaceAll]); txdireccion2 := stringreplace(txdireccion2, 'Ñ', 'N', [rfReplaceAll]); if Length(txmes) = 1 then txmes := '0' + txmes; if Length(txdia) = 1 then txdia := '0' + txdia; if Length(txhora) = 1 then txhora := '0' + txhora; if Length(txminutos) = 1 then txminutos := '0' + txminutos; if Length(txsegundos) = 1 then txsegundos := '0' + txsegundos; AssignFile(F, ExtractFilePath(Application.ExeName) + 'NOMINA.XML'); Rewrite(F); WriteLn(F, ''); WriteLn(F, '' + txnif + 'AN0' + txanyo + txmes + txdia + txhora + txminutos + txsegundos + ''); WriteLn(F, '' + txanyo + '-' + txmes + '-' + txdia + 'T' + txhora + ':' + txminutos + ':' + txsegundos + ''); WriteLn(F, '' + txnumlineas + '' + txcantidadtotal + ''); WriteLn(F, '' + txnombre + '' + txnif + 'AN0'); WriteLn(F, 'SCT' + txanyo + txmes + txdia + txhora + txminutos + txsegundos + '001TRFtrue' + txnumlineas + '' + txcantidadtotal + ''); WriteLn(F, '' + txanyo + '-' + txmes + '-' + txdia + '' + txnombre + ''); WriteLn(F, 'ES' + txdireccion + '' + txdireccion2 + ''); WriteLn(F, '' + txcuenta + 'EUR' + txbic + 'SLEV'); dm.tnominasdetalle.First; linea := 1; while not dm.tnominasdetalle.Eof do begin txlinea := FormatFloat(',0000', linea); txlinea := stringreplace(txlinea, '.', '', [rfReplaceAll]); txnombre := stringreplace(dm.tnominasdetalleNOMBRE.AsString, 'Ñ', 'N', [rfReplaceAll]); txdireccion := stringreplace(dm.tnominasdetalledireccion.AsString, '/', '?', [rfReplaceAll]); txdireccion := stringreplace(txdireccion, 'º', '?', [rfReplaceAll]); txdireccion := stringreplace(txdireccion, 'Ñ', 'N', [rfReplaceAll]); txtotalapagar := FormatFloat(',0.00', dm.tnominasdetalletotalapagar.AsFloat); txtotalapagar := stringreplace(txtotalapagar, '.', '', [rfReplaceAll]); txtotalapagar := stringreplace(txtotalapagar, ',', '.', [rfReplaceAll]); WriteLn(F, '' + dm.tnominasdetalleNIF.AsString + '-20161-' + txanyo + txmes + txdia + txhora + txminutos + txsegundos + '-' + txlinea + ''); WriteLn(F, 'SEPASALA' + txtotalapagar + ''); WriteLn(F, '' + txnombre + 'ES'); WriteLn(F, '' + txdireccion + '' + dm.tnominasdetalleCP.AsString + ' ' + dm.tnominasdetallePOBLACION.AsString + ' . .'); WriteLn(F, '' + dm.tnominasdetalleCUENTAPAGO.AsString + 'SALANOMINA'); dm.tnominasdetalle.Next; linea := linea + 1; end; WriteLn(F, ''); CloseFile(F); end; procedure TBASE.Button18Click(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.connect(usbDevice); VFirmas.ShowModal(); end; except on e: exception do showmessage(e.Message); end; dm.qFirmas2.Append; dm.qFirmas2ide.Value := dm.qpartes_diarioside.AsInteger; dm.qFirmas2idt.Value := dm.qpartes_diariosidt.AsInteger; dm.qFirmas2firma.LoadFromFile('c:\agrigest\informes\firma.bmp'); dm.qFirmas2.post; tfirmanominas.Picture.LoadFromFile('c:\agrigest\informes\firma.bmp'); if not dm.qpartes_diarios.Active then dm.qpartes_diarios.Open; dm.qpartes_diarios.edit; dm.qpartes_diariosvalidado.Value := 1; dm.qpartes_diariosfirma.Value := dm.qFirmas2id.AsInteger; dm.qpartes_diarios.post; Deletefile('c:\agrigest\informes\firma.bmp'); end else begin showmessage('Tableta de firma no conectada'); end; end; procedure TBASE.Button19Click(Sender: TObject); var anyo, mes, dia: word; fecha: string; begin decodedate(dmproduccion.qpartesdiariosfecha.AsDateTime, anyo, mes, dia); fecha := floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia); dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add ('delete from restos_dia where lote in (select lote from ea_pesadas where fecha=' + '''' + fecha + '''' + ' and iddestino=' + dmproduccion.qpartesdiariosalmacen.AsString + ')'); dm.qaux1.ExecSQL; dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add ('insert into restos_dia (ide,idalmacen,lote,parcela,mprima,fecha,cant_inicial) select idempresa,iddestino,lote,parcela,mprima,fechatrabajo,sum(num_envases) from ea_pesadas where fechatrabajo=' + '''' + fecha + '''' + ' and iddestino=' + dmproduccion.qpartesdiariosalmacen.AsString + ' group by fecha,lote'); dm.qaux1.ExecSQL; dmproduccion.qrestos_dia.Close; dmproduccion.qrestos_dia.Open;; if dmproduccion.qpartesdiarios.State in [dsedit] then dmproduccion.qpartesdiarios.post; end; procedure TBASE.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; dm.tempresa.edit; dm.tempresafirmaresponsable.LoadFromFile('c:\agrigest\tmp\firma.bmp'); dm.tempresa.post; Deletefile('c:\agrigest\informes\firma.bmp'); end else begin showmessage('Dispositivo de firmas no conectado'); end; end; procedure TBASE.btcontrolproduccionClick(Sender: TObject); begin dm.qcontrolproduccion.post; end; procedure TBASE.bteaaceptarClick(Sender: TObject); begin // dm.tarticulosalmacen.post; // dm.qarticulosalmacen.open; // bteaanadir.Enabled:=true; // bteamodificar.Enabled:=true; // bteaborrar.Enabled:=true; // bteacancelar.Enabled:=false; // bteaaceptar.Enabled:=false; end; procedure TBASE.bteaanadirClick(Sender: TObject); begin // dm.qarticulosalmacen.Close; // dm.tarticulosalmacen.append; // dbedit115.SetFocus; // bteaanadir.Enabled:=false; // bteamodificar.Enabled:=false; // bteaborrar.Enabled:=false; // bteacancelar.Enabled:=true; // bteaaceptar.Enabled:=true; end; procedure TBASE.bteaborrarClick(Sender: TObject); begin dm.tarticulosalmacen.Delete; dm.qarticulosalmacen.Refresh; dm.qarticulosalmacen.First end; procedure TBASE.bteacancelarClick(Sender: TObject); begin // dm.tarticulosalmacen.cancel; // dm.qarticulosalmacen.open; // bteaanadir.Enabled:=true; // bteamodificar.Enabled:=true; // bteaborrar.Enabled:=true; // bteacancelar.Enabled:=false; // bteaaceptar.Enabled:=false; end; procedure TBASE.bteamodificarClick(Sender: TObject); begin // dm.tarticulosalmacen.edit; // dbedit115.SetFocus; // bteaanadir.Enabled:=false; // bteamodificar.Enabled:=false; // bteaborrar.Enabled:=false; // bteacancelar.Enabled:=true; // bteaaceptar.Enabled:=true; end; procedure TBASE.Button20Click(Sender: TObject); begin informedb.DataSource := dmestadisticas.dsqproduccionimpresion; if Edit2.Text <> '' then begin dmestadisticas.qproduccionimpresion.Close; dmestadisticas.qproduccionimpresion.Prepare; dmestadisticas.qproduccionimpresion.ParamByName('R').AsString := Edit2.Text; dmestadisticas.qproduccionimpresion.ParamByName('ALMACEN').AsString := dm.qalmacenesnombre.AsString; dmestadisticas.qproduccion.Open; end else begin dmestadisticas.qproduccionimpresion.Close; dmestadisticas.qproduccionimpresion.Prepare; dmestadisticas.qproduccionimpresion.ParamByName('R').AsString := '%'; dmestadisticas.qproduccionimpresion.ParamByName('ALMACEN').AsString := dm.qalmacenesnombre.AsString; dmestadisticas.qproduccion.Open; end; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\stockalmacen.fr3'); informes.Variables.Variables['TITULO'] := QUOTEDSTR('Stock del almacen: ' + dm.qalmacenesnombre.AsString + ' a fecha ' + datetostr(Date())); // informes.Report.FileName:=TMES.Text+' ' + qjornalestrabajador.asstring; informes.ShowReport(); informes.Clear end; procedure TBASE.Button21Click(Sender: TObject); begin dmestadisticas.qinfsalidas.Close; dmestadisticas.qinfsalidas.Prepare; dmestadisticas.qinfsalidas.ParamByName('FINICIO').AsDate := dmestadisticas.qcampanyasfechainicio.AsDateTime; dmestadisticas.qinfsalidas.ParamByName('FFIN').AsDate := dmestadisticas.qcampanyasfechafin.AsDateTime; dmestadisticas.qinfsalidas.ParamByName('PARCELA').AsString := dm.qparcelascodpar.AsString; dmestadisticas.qinfsalidas.Open; informedb.DataSource := dmestadisticas.dsqinfsalidas; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\entradasparcela.fr3'); informes.Variables.Variables['TITULO'] := QUOTEDSTR('Parcela: ' + dm.qparcelasnombre.AsString + ' Campaña: ' + dmestadisticas.qcampanyasdescripcion.AsString + ' ENVASADOS'); informes.ShowReport(); informes.Clear end; procedure TBASE.Button22Click(Sender: TObject); var archivo: string; begin archivo := 'c:\agrigest\salidas.xlsx'; try ExportaraExcel(archivo, 'SALIDAS', DBGrid69); finally showmessage ('Los datos han sido exportados correctamente a C:\AGRIGEST\salidas.XLSX'); end; end; procedure TBASE.btJborrarClick(Sender: TObject); begin tjornales.Locate('id', dm.qnominasdetalleid.AsInteger, [locaseinsensitive, lopartialkey]); tjornales.Delete; btactualizarempleadosnominas.Click; end; procedure TBASE.btJcancelarClick(Sender: TObject); begin if tjornales.State in [dsedit, dsinsert] then begin tjornales.cancel; nomfechadesde.Date := fechajornales.Date; nomfechahasta.Date := fechajornales.Date; btactualizarempleadosnominas.Click; btJnuevo.Enabled := true; btJmodificar.Enabled := true; btJborrar.Enabled := true; btJguardar.Enabled := false; btJcancelar.Enabled := false; fechajornales.Enabled := false; lnobservaciones.Enabled:=false; ljcentro.Enabled := false; ljtrabajo.Enabled := false; ljhora.Enabled := false; edjhoras.Enabled := false; edjprecio.Enabled := false; PdatosJornales.Enabled := false; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=0'); qaux.ExecSQL; qempleados.Refresh; end; btJnuevo.Enabled := true; btJmodificar.Enabled := true; btJguardar.Enabled := false; btJcancelar.Enabled := false; btJborrar.Enabled := true; end; procedure TBASE.btJexcelClick(Sender: TObject); var archivo: string; begin SaveDialog1.FileName := 'JORNALES.xlsx'; SaveDialog1.Execute(); archivo := SaveDialog1.FileName; try ExportaraExcel(archivo, 'JORNALES', DBGrid4); finally showmessage('Los datos han sido exportados correctamente a ' + archivo); end; end; procedure TBASE.btJguardarClick(Sender: TObject); var dia, mes, anyo: word; fecha, centro, trabajo, TipoHora, horas, precio: string; contador: Integer; totaljornal: real; begin qaux.SQL.Clear; qaux.SQL.Add('select max(id)+1 from trabajo_diario'); qaux.Open; contador := qaux.Fields[0].AsInteger; if tjornales.State in [dsedit] then begin tjornalesfecha.Value := fechajornales.Date; tjornalesparcela.Value := ljcentro.KeyValue; tjornalestypework.Value := ljtrabajo.KeyValue; tjornalesarticulo.Value := ljhora.KeyValue; tjornalesqhoras.Value := strtofloat(edjhoras.Text); tjornalesprecio.Value := strtofloat(edjprecio.Text); totaljornal := strtofloat(edjhoras.Text) * strtofloat(edjprecio.Text); tjornalestotal.Value := strtofloat(FormatFloat('0.00', totaljornal)); tjornalesestado.Value := 'C'; tjornalesobservaciones.Value:=lnobservaciones.Text; tjornales.post; dm.qnominasdetalle.Refresh; end else begin qaux.SQL.Clear; qaux.SQL.Add('select id,nombre from trabajadores where seleccionado=1'); qaux.Open; if qaux.RecordCount > 0 then begin while not qaux.Eof do begin tjornales.Append; tjornalesid.Value := contador; tjornalesfecha.Value := fechajornales.Date; tjornalesparcela.Value := ljcentro.KeyValue; tjornalesidt.Value := qaux.Fields[0].AsInteger; tjornalestrabajador.Value := qaux.Fields[1].AsString; tjornalestypework.Value := ljtrabajo.KeyValue; qtipohora.Close; qtipohora.Prepare; qtipohora.ParamByName('TRABAJADOR').AsInteger := tjornalesidt.AsInteger; qtipohora.ParamByName('EMPRESA').AsInteger := 1; // tjornalesempresa.AsInteger; qtipohora.Open; if qtipohoracodart.AsString <> '' then tjornalesarticulo.Value := qtipohoracodart.AsString else tjornalesarticulo.Value := ljhora.KeyValue; tjornalesqhoras.Value := strtofloat(edjhoras.Text); if qtipohoracodart.AsString <> '' then tjornalesprecio.Value := qtipohoraprecio.AsFloat else tjornalesprecio.Value := strtofloat(edjprecio.Text); totaljornal := tjornalesqhoras.AsFloat * tjornalesprecio.AsFloat; // strtofloat(edjhoras.text)*strtofloat(edjprecio.Text); tjornalestotal.Value := strtofloat(FormatFloat('0.00', totaljornal)); tjornalesestado.Value := 'C'; tjornalesobservaciones.Value:=lnobservaciones.Text; tjornales.post; contador := contador + 1; qaux.Next; nomfechadesde.Date := fechajornales.Date; nomfechahasta.Date := fechajornales.Date; btactualizarempleadosnominas.Click; end; end else begin showmessage('DEBE SELECCIONAR AL MENOS UN TRABAJADOR'); end; end; btJnuevo.Enabled := true; btJborrar.Enabled := true; btJguardar.Enabled := false; btJmodificar.Enabled := true; btJcancelar.Enabled := false; lnobservaciones.Enabled:=false; fechajornales.Enabled := false; ljcentro.Enabled := false; ljtrabajo.Enabled := false; ljhora.Enabled := false; edjhoras.Enabled := false; edjprecio.Enabled := false; PdatosJornales.Enabled := false; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=0'); qaux.ExecSQL; qempleados.Refresh; checktodos.Checked := false; end; procedure TBASE.Button23Click(Sender: TObject); var archivo: string; begin SaveDialog1.FileName := 'TRAZABILIDADENTRADAS.xls'; SaveDialog1.Execute(); archivo := SaveDialog1.FileName; try ExportaraExcel(archivo, 'STOCK', DBGrid38); finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure TBASE.btactualizarempleadosnominasClick(Sender: TObject); var anyo, mes, dia: word; filtro, filtro2, filtro3, fdesde, fhasta, filtrogrupo, filtrotrabajador: string; idt, filtrojornales, tempdia, tempmes: string; begin filtro := ''; decodedate(nomfechadesde.Date, anyo, mes, dia); tempdia := floattostr(dia); if Length(tempdia) = 1 then tempdia := '0' + tempdia; tempmes := floattostr(mes); if Length(tempmes) = 1 then tempmes := '0' + tempmes; fdesde := '''' + floattostr(anyo) + '-' + tempmes + '-' + tempdia + ''''; decodedate(nomfechahasta.Date, anyo, mes, dia); tempdia := floattostr(dia); if Length(tempdia) = 1 then tempdia := '0' + tempdia; tempmes := floattostr(mes); if Length(tempmes) = 1 then tempmes := '0' + tempmes; fhasta := '''' + floattostr(anyo) + '-' + tempmes + '-' + tempdia + ''''; if qgrupostrabajadores2id.AsInteger > 0 then begin filtrogrupo := ' and idt in (select id from trabajadores where activo=' + inttostr(qgrupostrabajadores2id.AsInteger) + ')'; end else filtrogrupo := ''; if tbuscarnominas.Text <> '' then begin filtrogrupo := ''; filtrotrabajador := ' and idt in (select id from trabajadores where nombre like(' + '''' + '%' + tbuscarnominas.Text + '%' + '''' + '))'; end; filtro := ' where fecha>=' + fdesde; filtro := filtro + ' and fecha<=' + fhasta; filtro := filtro + filtrogrupo + filtrotrabajador; { dm.qempleados.Close; dm.qempleados.SQL.Clear; dm.qempleados.SQL.Add('select distinct(idt),trabajador from trabajo_diario '); dm.qempleados.sql.add(filtro); dm.qempleados.sql.add(' order by trabajador asc'); dm.qempleados.Open; filtro:=''; filtro:=' where fecha>='+fdesde; filtro:=filtro+' and fecha<='+fhasta; } filtro := filtro + ' order by trabajador asc,fecha asc'; dm.qnominasdetalle.Close; dm.qnominasdetalle.SQL.Clear; dm.qnominasdetalle.SQL.Add('select * from trabajo_diario ' + filtro); dm.qnominasdetalle.Open; dm.qanticiposdetalle.Close; dm.qanticiposdetalle.SQL.Clear; dm.qanticiposdetalle.SQL.Add('select * from anticipos ' + filtro); dm.qanticiposdetalle.Open; dm.qaux.Close; dm.qaux.SQL.Clear; dm.qaux.SQL.Add('select count(distinct(idt)) from trabajo_diario ' + filtro); dm.qaux.Open; ltotalgrupo3.Caption := 'Total Empleados: ' + dm.qaux.Fields[0].AsString; idt := qempleadosid.AsString; if idt <> '' then begin 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); if TESTADO.ItemIndex <> 0 then filtrojornales := filtrojornales + ' and estado=' + TESTADO.Text; filtrojornales := filtrojornales + ' order by idt desc'; qjornales.Close; qjornales.SQL.Clear; qjornales.SQL.Add('select * from trabajo_diario ' + filtrojornales); qjornales.Open; end; filtro := ''; filtro2 := ''; filtro3 := ''; decodedate(nomlhdesde.Date, anyo, mes, dia); fdesde := '''' + floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia) + ''''; filtro := ' where codart in (select distinct(articulo) from trabajo_diario where fecha>=' + fdesde; filtro2 := ' where id in (select distinct(idt) from trabajo_diario td,articulos a, parcelas p where td.parcela=p.codpar and p.seleccionado=1 and td.articulo=a.codart and a.seleccionado=1 and fecha>=' + fdesde; filtro3 := ' where td.parcela=p.codpar and p.seleccionado=1 and td.idt=t.id and td.articulo=a.codart and a.seleccionado=1 and t.seleccionado=1 and fecha>=' + fdesde; // filtro2:=' where id in (select distinct(idt) from trabajo_diario td,articulos a where td.articulo=a.codart and a.seleccionado=1 and fecha>='+''''+fdesde+''''; // filtro3:=' where td.idt=t.id and td.articulo=a.codart and a.seleccionado=1 and t.seleccionado=1 and fecha>='+''''+fdesde+''''; decodedate(nomlhhasta.Date, anyo, mes, dia); fhasta := '''' + floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia) + ''''; filtro := filtro + ' and fecha<=' + fhasta; filtro := filtro + ') order by codart'; filtro2 := filtro2 + ' and fecha<=' + fhasta; filtro2 := filtro2 + ') order by nombre'; filtro3 := filtro3 + ' and fecha<=' + fhasta; filtro3 := filtro3 + ' group by idt,trabajador,articulo order by articulo,trabajador'; dm.qtipohoras2.Close; dm.qtipohoras2.SQL.Clear; dm.qtipohoras2.SQL.Add('select codart,seleccionado from articulos ' + filtro); dm.qtipohoras2.Open; dm.qtrabajadores2.Close; dm.qtrabajadores2.SQL.Clear; dm.qtrabajadores2.SQL.Add('select id,nombre,seleccionado from trabajadores ' + filtro2); dm.qtrabajadores2.Open; dm.qlistadohoras.Close; { dm.qlistadohoras.sql.clear; dm.qlistadohoras.sql.add('select idt,trabajador,articulo,sum(qhoras) as horas,sum(qhoras*a.equivalenciahoras) as horas2,sum(qhoras*td.precio) as total,sum((qhoras/a.equivalenciahoras)*td.precio) as total2 from trabajo_diario td,articulos a,trabajadores t '+filtro3); dm.qlistadohoras.Open; } { dmproduccion.qpartesdiarios.close; dmproduccion.qentradas.close; dmproduccion.qentradas2.close; dmproduccion.qsalidas.close; dmproduccion.qsalidas2.close; dmproduccion.qpartesdiarios.Open; dmproduccion.qentradas.Open; dmproduccion.qentradas2.Open; dmproduccion.qsalidas.Open; dmproduccion.qsalidas2.Open; } end; procedure TBASE.Button24Click(Sender: TObject); var anyo, mes, dia: word; fdesde, fhasta: string; begin decodedate(fprodesde.Date, anyo, mes, dia); fdesde := inttostr(anyo) + '-' + inttostr(mes) + '-' + inttostr(dia); // decodedate(fprohasta.Date, anyo, mes, dia); // fhasta := inttostr(anyo) + '-' + inttostr(mes) + '-' + inttostr(dia); informedb.DataSource := dm.dsqmovimientomesas; dm.qmovimientomesas.Close; dm.qmovimientomesas.Prepare; dm.qmovimientomesas.ParamByName('FECHA').AsDate := fprodesde.Date; // dm.qmovimientomesas.sql.Add('select * from movimiento_mesas where fecha in (select fecha from calendario_laboral where festivo=0) and fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''+' order by trabajador,fecha,entrada_real'); dm.qmovimientomesas.Open; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\listadoticados.fr3'); informes.Variables.Variables['TITULO'] := QUOTEDSTR('TICADOS DEL DIA' + datetostr(fprodesde.Date)); // informes.Report.FileName:=TMES.Text+' ' + qjornalestrabajador.asstring; informes.ShowReport(); informes.Clear end; procedure TBASE.Button25Click(Sender: TObject); var ult_parte, idt, dias: Integer; horas, resto, restohoras: real; parcial, festivo: Boolean; anyo, mes, dia: word; begin qaux.SQL.Clear; qaux.SQL.Add('delete from partes_diarios where validado=0 and idt=' + dm.qempleadosidt.AsString); qaux.ExecSQL; qaux.SQL.Clear; qaux.SQL.Add('select max(id)+1 from partes_diarios'); qaux.Open; ult_parte := qaux.Fields[0].AsInteger; dm.qtrabajo_diario.SQL.Clear; dm.qtrabajo_diario.SQL.Add('select * from trabajo_diario where idt=' + dm.qempleadosidt.AsString + ' and (idparte1 is NULL or idparte2 is NULL) order by trabajador asc,fecha'); dm.qtrabajo_diario.Open; if dm.qtrabajo_diario.RecordCount = 0 then begin dm.qtrabajo_diario.SQL.Clear; dm.qtrabajo_diario.SQL.Add('select * from trabajo_diario where idt=' + dm.qempleadosidt.AsString + ' and (idparte1=0 or idparte2=0) order by trabajador asc,fecha'); dm.qtrabajo_diario.Open; end; horas := 0; while not dm.qtrabajo_diario.Eof do begin horas := horas + dm.qtrabajo_diariohoras_acumuladas.AsFloat; if horas < 8 then begin dm.qtrabajo_diario.edit; dm.qtrabajo_diariohoras_acumuladas.Value := 0; if parcial = false then dm.qtrabajo_diarioidparte1.Value := ult_parte; if parcial = true then dm.qtrabajo_diarioidparte2.Value := ult_parte; dm.qtrabajo_diario.post; dm.qtrabajo_diario.Next; parcial := false; end; if horas > 8 then begin resto := horas - 8; horas := 8; parcial := true; dm.qtrabajo_diario.edit; dm.qtrabajo_diariohoras_acumuladas.Value := resto; dm.qtrabajo_diarioidparte1.Value := ult_parte; dm.qtrabajo_diario.post; end; if horas = 8 then begin decodedate(dm.qtrabajo_diariofecha.AsDateTime, anyo, mes, dia); qaux.SQL.Clear; qaux.SQL.Add ('select count(*) from calendario_laboral where festivo=0 and year(fecha)=' + floattostr(anyo) + ' and month(fecha)=' + floattostr(mes)); qaux.Open; dias := qaux.Fields[0].AsInteger; qaux.SQL.Clear; qaux.SQL.Add('select sum(horas) from partes_diarios where idt=' + dm.qempleadosidt.AsString + ' and year(fecha)=' + floattostr(anyo) + ' and month(fecha)=' + floattostr(mes)); qaux.Open; restohoras := (dias * 8) - qaux.Fields[0].AsFloat; if restohoras > 0 then begin dm.qpartes_diarios.Close; dm.qpartes_diarios.Open; dm.qpartes_diarios.Append; dm.qpartes_diariosid.Value := ult_parte; dm.qpartes_diarioside.Value := dm.qtrabajo_diarioempresa.AsInteger; dm.qpartes_diariosidt.Value := dm.qtrabajo_diarioidt.AsInteger; dm.qpartes_diariostrabajador.Value := dm.qtrabajo_diariotrabajador.AsString; dm.tcalendario_laboral.Open; dm.tcalendario_laboral.Locate('fecha', dm.qtrabajo_diariofecha.AsDateTime, [locaseinsensitive]); dm.qpartes_diariosfecha.Value := dm.qtrabajo_diariofecha.AsDateTime; if horas < restohoras then dm.qpartes_diarioshoras.Value := horas else dm.qpartes_diarioshoras.Value := restohoras; dm.qpartes_diariosvalidado.Value := 0; dm.qpartes_diariosfestivo.Value := dm.tcalendario_laboralfestivo.AsInteger; dm.qpartes_diarios.post; horas := 0; ult_parte := ult_parte + 1; end else begin horas := 0; ult_parte := ult_parte + 1; end; end; // dm.qtrabajo_diario.Next; end; dm.TFirmas.Open; dm.qfirmas.Open; end; procedure TBASE.Button26Click(Sender: TObject); begin // informedb.Datasource:=dmestadisticas.dsqproducciondetalle; dmestadisticas.qinfentradas.Close; dmestadisticas.qinfentradas.Prepare; dmestadisticas.qinfentradas.ParamByName('FINICIO').AsDate := dmestadisticas.qcampanyasfechainicio.AsDateTime; dmestadisticas.qinfentradas.ParamByName('FFIN').AsDate := dmestadisticas.qcampanyasfechafin.AsDateTime; dmestadisticas.qinfentradas.ParamByName('PARCELA').AsString := dm.qparcelascodpar.AsString; dmestadisticas.qinfentradas.Open; { dmestadisticas.qinfentradas.SQL.Clear; dmestadisticas.qinfentradas.SQL.Add('(select v.id,v.fecha,v.fechatrabajo,v.parcela,v.mprima_p as mprima,v.mprima_p as mprima_p,v.id_envase,v.num_envases,v.destino as cliente,'+''''+' '+''''+' as ciudad,v.peso_neto,v.peso_neto_teorico,v.peso_medio,v.temperatura,v.lote,v.idalbaran '); dmestadisticas.qinfentradas.SQL.Add(' from v_ea_pesadaslotes v where v.idea>0 and fecha>='+''''+vfechainicio+''''+' and fecha<='+''''+vfechafin+''''+' and v.pedidocliente is null)'); dmestadisticas.qinfentradas.SQL.Add(' UNION ALL'); dmestadisticas.qinfentradas.SQL.Add('(select v.id,v.fecha,v.fechatrabajo,v.parcela,v.mprima_p as mprima,v.mprima_p as mprima_p,v.id_envase,v.num_envases,c.nombre as cliente,p.iddestino as ciudad,v.peso_neto,v.peso_neto_teorico,v.peso_medio,v.temperatura,v.lote,v.idalbaran '); dmestadisticas.qinfentradas.SQL.Add(' from v_ea_pesadaslotes v, pedidos p,clientes c where v.idea>0 and fecha>='+''''+vfechainicio+''''+' and fecha<='+''''+vfechafin+''''+' and v.pedidocliente is not null and v.pedidocliente=p.id and p.idcliente=c.id)'); dmestadisticas.qinfentradas.SQL.Add(' order by mprima,id desc, fecha'); } informedb.DataSource := dmestadisticas.dsqinfentradas; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\entradasparcela.fr3'); informes.Variables.Variables['TITULO'] := QUOTEDSTR('Parcela: ' + dm.qparcelasnombre.AsString + ' Campaña: ' + dmestadisticas.qcampanyasdescripcion.AsString + ' RECOLECCIÓN'); informes.ShowReport(); informes.Clear end; procedure TBASE.Button27Click(Sender: TObject); var filtro: string; begin filtro := dmproduccion.qpartesdiariosid.AsString; dmproduccion.qpartesdiarios.filter := 'id=' + filtro; dmproduccion.qpartesdiarios.filtered := true; informedb.DataSource := dmproduccion.dspartesdiarios; informedb2.DataSource := dmproduccion.dsqentradas2; informedb3.DataSource := dmproduccion.dsqsalidas2; informedb4.DataSource := dmproduccion.dsqentradas; informedb5.DataSource := dmproduccion.dsqsalidaslotes; informedb6.DataSource := dmproduccion.dsqentradas; informedb7.DataSource := dmproduccion.dsqsalidaslotes; { if edit2.text<>'' then begin dmestadisticas.qproduccionimpresion.close; dmestadisticas.qproduccionimpresion.sql.clear; dmestadisticas.qproduccionimpresion.sql.add('select * from ea_pesadas ea where codigoR='+''''+'R'+edit2.Text+''''+' order by ea.destino,ea.id_envase,ea.fecha,ea.id,ea.mprima'); dmestadisticas.qproduccion.Open; end; } informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\informe_partediario.fr3'); informes.Variables.Variables['TITULO'] := QUOTEDSTR(Panel100.Caption); // informes.Report.FileName:=TMES.Text+' ' + qjornalestrabajador.asstring; informes.ShowReport(); informes.Clear; dmproduccion.qpartesdiarios.filtered := false; end; procedure TBASE.Button28Click(Sender: TObject); var ult_parte, idt, dias: Integer; horas, resto, restohoras: real; parcial, festivo: Boolean; anyo, mes, dia: word; begin qaux.SQL.Clear; qaux.SQL.Add('delete from partes_diarios where validado=0 and idt=' + dm.qpersonasmesasidt.AsString); qaux.ExecSQL; qaux.SQL.Clear; qaux.SQL.Add('select max(id)+1 from partes_diarios'); qaux.Open; ult_parte := qaux.Fields[0].AsInteger; dm.qtrabajo_diario.SQL.Clear; dm.qtrabajo_diario.SQL.Add('select * from trabajo_diario where idt=' + dm.qpersonasmesasidt.AsString + ' and (idparte1 is NULL or idparte2 is NULL) order by trabajador asc,fecha'); dm.qtrabajo_diario.Open; if dm.qtrabajo_diario.RecordCount = 0 then begin dm.qtrabajo_diario.SQL.Clear; dm.qtrabajo_diario.SQL.Add('select * from trabajo_diario where idt=' + dm.qpersonasmesasidt.AsString + ' and (idparte1=0 or idparte2=0) order by trabajador asc,fecha'); dm.qtrabajo_diario.Open; end; horas := 0; while not dm.qtrabajo_diario.Eof do begin horas := horas + dm.qtrabajo_diariohoras_acumuladas.AsFloat; if horas < 8 then begin dm.qtrabajo_diario.edit; dm.qtrabajo_diariohoras_acumuladas.Value := 0; if parcial = false then dm.qtrabajo_diarioidparte1.Value := ult_parte; if parcial = true then dm.qtrabajo_diarioidparte2.Value := ult_parte; dm.qtrabajo_diario.post; dm.qtrabajo_diario.Next; parcial := false; end; if horas > 8 then begin resto := horas - 8; horas := 8; parcial := true; dm.qtrabajo_diario.edit; dm.qtrabajo_diariohoras_acumuladas.Value := resto; dm.qtrabajo_diarioidparte1.Value := ult_parte; dm.qtrabajo_diario.post; end; if horas = 8 then begin decodedate(dm.qtrabajo_diariofecha.AsDateTime, anyo, mes, dia); qaux.SQL.Clear; qaux.SQL.Add ('select count(*) from calendario_laboral where festivo=0 and year(fecha)=' + floattostr(anyo) + ' and month(fecha)=' + floattostr(mes)); qaux.Open; dias := qaux.Fields[0].AsInteger; qaux.SQL.Clear; qaux.SQL.Add('select sum(horas) from partes_diarios where idt=' + dm.qpersonasmesasidt.AsString + ' and year(fecha)=' + floattostr(anyo) + ' and month(fecha)=' + floattostr(mes)); qaux.Open; restohoras := (dias * 8) - qaux.Fields[0].AsFloat; if restohoras > 0 then begin dm.qpartes_diarios2.Close; dm.qpartes_diarios2.Open; dm.qpartes_diarios2.Append; dm.qpartes_diarios2id.Value := ult_parte; dm.qpartes_diarios2ide.Value := dm.qtrabajo_diarioempresa.AsInteger; dm.qpartes_diarios2idt.Value := dm.qtrabajo_diarioidt.AsInteger; dm.qpartes_diarios2trabajador.Value := dm.qtrabajo_diariotrabajador.AsString; dm.tcalendario_laboral.Open; dm.tcalendario_laboral.Locate('fecha', dm.qtrabajo_diariofecha.AsDateTime, [locaseinsensitive]); dm.qpartes_diarios2fecha.Value := dm.qtrabajo_diariofecha.AsDateTime; if horas < restohoras then dm.qpartes_diarios2horas.Value := horas else dm.qpartes_diarios2horas.Value := restohoras; dm.qpartes_diarios2validado.Value := 0; dm.qpartes_diarios2festivo.Value := dm.tcalendario_laboralfestivo.AsInteger; dm.qpartes_diarios2.post; horas := 0; ult_parte := ult_parte + 1; end else begin horas := 0; ult_parte := ult_parte + 1; end; end; // dm.qtrabajo_diario.Next; end; dm.TFirmas.Open; dm.qfirmas.Open; end; procedure TBASE.Button29Click(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; // dm.TFirmas.Open; dm.qFirmas2.Append; dm.qFirmas2ide.Value := dm.qpartes_diarios2ide.AsInteger; dm.qFirmas2idt.Value := dm.qpartes_diarios2idt.AsInteger; dm.qFirmas2firma.LoadFromFile('c:\agrigest\informes\firma.bmp'); dm.qFirmas2.post; tfirmaproduccion.Picture.LoadFromFile('c:\agrigest\informes\firma.bmp'); if not dm.qpartes_diarios2.Active then dm.qpartes_diarios2.Open; dm.qpartes_diarios2.edit; dm.qpartes_diarios2validado.Value := 1; dm.qpartes_diarios2firma.Value := dm.qFirmas2id.AsInteger; dm.qpartes_diarios2.post; Deletefile('c:\agrigest\informes\firma.bmp'); end else begin showmessage('Tableta de firma no conectada'); end; end; procedure TBASE.Button2Click(Sender: TObject); begin if temp_fotosidt.AsInteger = templeadosID.AsInteger then temp_fotos.Delete; Image2.Picture := nil; end; procedure TBASE.btPcancelarClick(Sender: TObject); var codigo: Integer; begin codigo := dmtr.qlotescodigo.AsInteger; dmtr.qlotes.cancel; dmtr.qlotes.Locate('codigo', codigo, [locaseinsensitive, lopartialkey]); end; procedure TBASE.btLguardarClick(Sender: TObject); var codigo: Integer; begin codigo := dmtr.qlotescodigo.AsInteger; dmtr.qlotesPRODUCTOR.Value := qsocios2nombre.AsString; // dmtr.qlotespaisorigen.Value := qsocios2pais.AsString; dmtr.qlotes.post; dmtr.qlotes.Close; dmtr.qlotes.Open; dmtr.qlotes.Locate('codigo', codigo, [locaseinsensitive, lopartialkey]); end; procedure TBASE.btLImprimirClick(Sender: TObject); var vsgg,vsdop,vsigp,vsifs,vsbrc:string; begin if dmtr.qlotessgg.AsString='' then vsgg:='' else vsgg:='GLOGALGAP: '+ dmtr.qlotessgg.Asstring; if dmtr.qlotessdop.AsString='' then vsdop:='' else vsdop:='DOP: ' + dmtr.qlotessdop.Asstring; if dmtr.qlotessigp.AsString='' then vsigp:='' else vsigp:='IGP: ' + dmtr.qlotessigp.Asstring; if dmtr.qlotessifs.AsString='' then vsifs:='' else vsifs:='IFS: ' + dmtr.qlotessifs.Asstring; if dmtr.qlotessbrc.AsString='' then vsbrc:='' else vsbrc:='BRC: ' + dmtr.qlotessbrc.Asstring; dmtr.qsalidas_sd.Close; dmtr.qsalidas_sd.Prepare; dmtr.qsalidas_sd.ParamByName('LOTE').AsInteger := dmtr.qlotescodigo.AsInteger; dmtr.qsalidas_sd.Open; dmtr.qsalidas_ds.Close; dmtr.qsalidas_ds.Prepare; dmtr.qsalidas_ds.ParamByName('LOTE').AsInteger := dmtr.qlotescodigo.AsInteger; dmtr.qsalidas_ds.Open; dmtr.qinfentradas.Close; dmtr.qinfentradas.Prepare; dmtr.qinfentradas.ParamByName('LOTE').AsInteger := dmtr.qlotescodigo.AsInteger; dmtr.qinfentradas.Open; informedb.DataSource := dmtr.dsqinfentradas; // dmestadisticas.dsqproduccionimpresion; informedb2.DataSource := dmtr.dsqsalidas_sd; // dmestadisticas.dsqproduccionimpresion; informedb3.DataSource := dmtr.dsqsalidas_ds; // dmestadisticas.dsqproduccionimpresion; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\loteentradas.fr3'); informes.Variables.Variables['SELLOGG'] := QUOTEDSTR(vsgg); informes.Variables.Variables['SELLODOP'] := QUOTEDSTR(vsdop); informes.Variables.Variables['SELLOIGP'] := QUOTEDSTR(vsigp); informes.Variables.Variables['SELLOIFS'] := QUOTEDSTR(vsifs); informes.Variables.Variables['SELLOBRC'] := QUOTEDSTR(vsbrc); informes.Variables.Variables['TITULO'] := QUOTEDSTR('Entradas del LOTE: ' + dmtr.qlotescodigo.AsString + ' Trazabilidad: ' + dmtr.qlotestrazabilidad.AsString); informes.Variables.Variables['TITULO2'] := QUOTEDSTR('Envasados del LOTE: ' + dmtr.qlotescodigo.AsString + ' Trazabilidad: ' + dmtr.qlotestrazabilidad.AsString); informes.Variables.Variables['TITULO3'] := QUOTEDSTR('Desechos del LOTE: ' + dmtr.qlotescodigo.AsString + ' Trazabilidad: ' + dmtr.qlotestrazabilidad.AsString); informes.Variables.Variables['FECHA1'] := QUOTEDSTR('F.Cosecha'); informes.Variables.Variables['FECHA2'] := QUOTEDSTR('F.Trabajo'); informes.Variables.Variables['FECHA3'] := QUOTEDSTR('F.Elav.'); informes.Variables.Variables['FECHA4'] := QUOTEDSTR('F.Remani.'); informes.Variables.Variables['FECHA5'] := QUOTEDSTR('F.Elav.'); informes.Variables.Variables['FECHA6'] := QUOTEDSTR('F.Remani.'); informes.ShowReport(); informes.Clear end; procedure TBASE.btMmodificarClick(Sender: TObject); begin dmtr.qlotes.edit; lfecha.SetFocus; end; procedure TBASE.btPnuevoClick(Sender: TObject); var tcodigo: string; begin dmtr.qlotes.First; dmtr.qaux.SQL.Clear; dmtr.qaux.SQL.Add('select max(codigo)+1 from lotes'); dmtr.qaux.Open; tcodigo := dmtr.qaux.Fields[0].AsString; dmtr.qlotes.Append; dlotescodigo.SetFocus; dlotescodigo.Text := tcodigo; end; procedure TBASE.btprodaceptarClick(Sender: TObject); var anyo,mes,dia:word; vmesa, vmprima, vproducto: string; fdesde: string; begin decodedate(fprodesde.Date, anyo, mes, dia); fdesde := inttostr(anyo) + '-' + inttostr(mes) + '-' + inttostr(dia); // decodedate(fprohasta.Date, anyo, mes, dia); // fhasta := inttostr(anyo) + '-' + inttostr(mes) + '-' + inttostr(dia); Timer1.Enabled := false; if dmproduccion.qcalendario_laboral.State in [dsedit] then dmproduccion.qcalendario_laboral.Post; dmproduccion.qcalendario_laboral.close; dmproduccion.qcalendario_laboral.ParamByName('FECHA').Asdate:=fprodesde.Date; dmproduccion.qcalendario_laboral.Prepare; dmproduccion.qcalendario_laboral.Open; dm.qproduccion.Close; dm.qproduccion.prepare; dm.qproduccion.ParamByName('fecha').AsDate:=fprodesde.Date; dm.qproduccion.Open; { decodedate(fprodesde.Date,anyo,mes,dia); fdesde:=inttostr(anyo)+'-'+inttostr(mes)+'-'+inttostr(dia); decodedate(fprohasta.Date,anyo,mes,dia); fhasta:=inttostr(anyo)+'-'+inttostr(mes)+'-'+inttostr(dia); dm.qcontrolproduccion.Close; dm.qcontrolproduccion.sql.Clear; dm.qcontrolproduccion.sql.Add('select * from control_produccion where fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''); dm.qcontrolproduccion.open; dm.qproduccion.Close; dm.qproduccion.sql.Clear; dm.qproduccion.sql.Add('select * from v_produccion where fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''+' order by fecha desc'); dm.qproduccion.open; dm.qmesas.Close; dm.qmesas.SQL.Clear; dm.qmesas.SQL.Add('select distinct(mesa) from movimiento_mesas where fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''+' order by mesa'); dm.qmesas.open; dm.qproduccionmesa2.close; dm.qproduccionmesa2.sql.clear; dm.qproduccionmesa2.sql.Add('select p.mesa,p.cantidad,h.horasmesa,p.cantidad/h.horasmesa as cantidadhora from (SELECT mesa,sum(peso_real-tara) as cantidad,idt,embasadora FROM produccion where fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''+' group by mesa order by mesa) as p ' ); dm.qproduccionmesa2.sql.Add(' inner join '); dm.qproduccionmesa2.sql.Add(' (select mesa,sum(horas) as horasmesa from ( select mesa,sum(timestampdiff(minute,entrada_real,SALIDA_REAL)/60) as horas from movimiento_mesas where fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''+' and SALIDA_REAL is NOT null group by mesa '); dm.qproduccionmesa2.sql.Add(' union ALL'); dm.qproduccionmesa2.sql.Add(' select mesa,sum(timestampdiff(minute,entrada_real,now())/60) as horas from movimiento_mesas where fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''+' and SALIDA_REAL is null group by mesa ) as grupo GROUP by mesa) as h'); dm.qproduccionmesa2.SQL.Add(' on p.mesa=h.mesa'); dm.qproduccionmesa2.open; } if Pageproduccion.TabIndex = 5 then begin Timer1.Enabled := true; Panel49.Visible := false; qproduccionmesas.Close; qproduccionmesas.Prepare; qproduccionmesas.ParamByName('FECHA').AsDate := fprodesde.Date; qproduccionmesas.Open; qproduccionmatprima.Close; qproduccionmatprima.Prepare; qproduccionmatprima.ParamByName('FECHA').AsDate := fprodesde.Date; qproduccionmatprima.Open; qproduccionproducto.Close; qproduccionproducto.Prepare; qproduccionproducto.ParamByName('FECHA').AsDate := fprodesde.Date; qproduccionproducto.Open; if comboprodmesas.KeyValue = null then vmesa := '%' else vmesa := comboprodmesas.KeyValue; if comboprodmprimas.KeyValue = null then vmprima := '%' else vmprima := comboprodmprimas.KeyValue; if comboprodproducto.KeyValue = null then vproducto := '%' else vproducto := comboprodproducto.KeyValue; dm.qproduccionmesa.Close; dm.qproduccionmesa.Prepare; dm.qproduccionmesa.ParamByName('FECHA').AsDate := fprodesde.Date; dm.qproduccionmesa.ParamByName('MESA').AsString := vmesa; dm.qproduccionmesa.ParamByName('MPRIMA').AsString := vmprima; dm.qproduccionmesa.ParamByName('PRODUCTO').AsString := vproducto; dm.qproduccionmesa.ParamByName('HDESDE').Asinteger:=hdesde.ItemIndex; dm.qproduccionmesa.ParamByName('HHASTA').Asinteger:=hhasta.ItemIndex; dm.qproduccionmesa.Open; end; { dm.qproduccionembasadora.Close; dm.qproduccionembasadora.sql.Clear; dm.qproduccionembasadora.sql.Add('SELECT mesa,bascula,producto,count(*) as pesadas,sum(peso_real-tara) as cantidad,idt,embasadora FROM produccion where fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''+' group by mesa,bascula,producto,idt order by fecha DESC,mesa,bascula'); dm.qproduccionembasadora.open; dm.qproduccionhora.Close; dm.qproduccionhora.sql.Clear; dm.qproduccionhora.sql.Add('select hour(hora) as hora,sum(peso_real-tara) as cantidad from produccion where fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''+' group by hour(hora)'); dm.qproduccionhora.open; } if Pageproduccion.TabIndex = 6 then begin Timer1.Enabled := true; Panel49.Visible := false; dm.qproduccionhora.Close; dm.qproduccionhora.SQL.Clear; dm.qproduccionhora.SQL.Add ('select hour(hora) as desde,hour(hora)+1 as hasta,sum(peso_real-tara) as cantidad from produccion where fecha>=' + '''' + fdesde + '''' + ' group by hour(hora)'); dm.qproduccionhora.Open; end; if Pageproduccion.TabIndex = 7 then begin dm.qcontrolproduccion.Close; dm.qcontrolproduccion.Prepare; dm.qcontrolproduccion.ParamByName('fecha').AsDate:=fprodesde.Date; dm.qcontrolproduccion.Open; end; Timer1.Enabled := true; end; procedure TBASE.Button30Click(Sender: TObject); var archivo: string; begin archivo := 'c:\agrigest\STOCK' + dm.qalmacenesnombre.AsString + '.xlsx'; try ExportaraExcel(archivo, 'STOCK' + dm.qalmacenesnombre.AsString, DBGrid55); finally showmessage ('Los datos han sido exportados correctamente a C:\AGRIGEST\STOCK' + dm.qalmacenesnombre.AsString + '.XLSX'); end; end; procedure TBASE.Button35Click(Sender: TObject); var lote: string; begin lote := dmtr.qlotescodigo.AsString; qaux.SQL.Clear; qaux.SQL.Add ('update lotes set entran_reales=(SELECT sum(peso_neto) as entran_reales FROM v_ea_pesadaslotes where lote=' + inttostr(dmtr.qlotescodigo.AsInteger) + ' and idea>0) where codigo=' + inttostr(dmtr.qlotescodigo.AsInteger)); qaux.ExecSQL; qaux.SQL.Clear; qaux.SQL.Add ('update lotes set entran_teoricos=(SELECT sum(peso_neto_teorico) as entran_teoricos FROM v_ea_pesadaslotes where lote=' + inttostr(dmtr.qlotescodigo.AsInteger) + ' and idea>0) where codigo=' + inttostr(dmtr.qlotescodigo.AsInteger)); qaux.ExecSQL; qaux.SQL.Clear; qaux.SQL.Add ('update lotes set salen_reales=(SELECT sum(peso_neto) as entran_reales FROM v_ea_pesadaslotes where lote=' + inttostr(dmtr.qlotescodigo.AsInteger)); qaux.SQL.Add (' and ((idea>0 and iddestino<>0 and iddestino in (select id from almacenes where final=1)) or '); qaux.SQL.Add (' (idea<=0) and iddestino in (select id from almacenes where (final=1 or camara=1 or mermas=1))) and mprima_p in (select id from materias_primas where desechos=0)) where codigo=' + inttostr(dmtr.qlotescodigo.AsInteger)); qaux.ExecSQL; qaux.SQL.Clear; qaux.SQL.Add ('update lotes set salen_teoricos=(SELECT sum(peso_neto_teorico) as entran_teoricos FROM v_ea_pesadaslotes where lote=' + inttostr(dmtr.qlotescodigo.AsInteger)); qaux.SQL.Add (' and ((idea>0 and iddestino<>0 and iddestino in (select id from almacenes where final=1)) or '); qaux.SQL.Add (' (idea<=0) and iddestino in (select id from almacenes where (final=1 or camara=1 or mermas=1))) and mprima_p in (select id from materias_primas where desechos=0)) where codigo=' + inttostr(dmtr.qlotescodigo.AsInteger)); qaux.ExecSQL; qaux.SQL.Clear; qaux.SQL.Add ('update lotes set desperdicios=(SELECT sum(peso_neto) as desperdicios FROM v_ea_pesadaslotes where lote=' + inttostr(dmtr.qlotescodigo.AsInteger) + ' and mprima_p in (select id from materias_primas where desechos=1)) where codigo=' + inttostr(dmtr.qlotescodigo.AsInteger)); qaux.ExecSQL; dmtr.qsalidas.Refresh; dmtr.qea_pesadas.Refresh; dmtr.qlotes.Refresh; dmtr.qlotes.Locate('codigo', lote, [locaseinsensitive, lopartialkey]); end; procedure TBASE.Button36Click(Sender: TObject); var archivo: string; begin SaveDialog1.FileName := 'TRAZABILIDADSALIDAS.xls'; SaveDialog1.Execute(); archivo := SaveDialog1.FileName; try ExportaraExcel(archivo, 'STOCK', DBGrid36); finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure TBASE.btedocverClick(Sender: TObject); begin if btedocver.Caption = 'Ver Doc.' then begin paneldocumentosempleados.Visible := true; dmtr.qdocumentos.Open; dmtr.qdocumentos.filter := 'ide=' + templeadoside.AsString + ' and idt=' + templeadosID.AsString; dmtr.qdocumentos.Refresh; btedocver.Caption := 'Ocultar Doc.'; end else begin dmtr.qdocumentos.Close; paneldocumentosempleados.Visible := false; dmtr.qdocumentos.filter := 'id=-1 and idlote=-1'; btedocver.Caption := 'Ver Doc.'; end; end; procedure TBASE.btatborrarClick(Sender: TObject); begin dm.tanticipos.Locate('id', dm.qanticiposdetalleid.AsInteger, [locaseinsensitive, lopartialkey]); dm.tanticipos.Delete; btactualizarempleadosnominas.Click; end; procedure TBASE.btatcancelarClick(Sender: TObject); begin if dm.tanticipos.State in [dsedit, dsinsert] then begin dm.tanticipos.cancel; nomfechadesde.Date := fechaanticipos.Date; nomfechahasta.Date := fechaanticipos.Date; btactualizarempleadosnominas.Click; btatnuevo.Enabled := true; btatmodificar.Enabled := true; btatborrar.Enabled := true; btatguardar.Enabled := false; btatcancelar.Enabled := false; fechaanticipos.Enabled := false; panticipos.Enabled := false; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=0'); qaux.ExecSQL; qempleados.Refresh; end; end; procedure TBASE.btatexcelClick(Sender: TObject); var archivo: string; begin SaveDialog1.FileName := 'ANTICIPOS.xls'; SaveDialog1.Execute(); archivo := SaveDialog1.FileName; try ExportaraExcel(archivo, 'ANTICIPOS', DBGrid5); finally showmessage('Los datos han sido exportados correctamente a ' + archivo); end; end; procedure TBASE.btatguardarClick(Sender: TObject); var dia, mes, anyo: word; fecha: string; contador: Integer; totalimporte: real; begin qaux.SQL.Clear; qaux.SQL.Add('select max(id)+1 from anticipos'); qaux.Open; contador := qaux.Fields[0].AsInteger; if dm.tanticipos.State in [dsedit] then begin dm.tanticiposfecha.Value := fechaanticipos.Date; totalimporte := strtofloat(edimporte.Text); dm.tanticiposimporte.Value := strtofloat(FormatFloat('0.00', totalimporte)); dm.tanticiposimporteletras.Value := CantidadEnLetra(dm.tanticiposimporte.AsFloat, 1); dm.tanticiposobservaciones.Value := edconcepto.Text; dm.tanticiposformapago.Value := edformapago.Text; dm.tanticiposestado.Value := 'C'; dm.tanticipos.post; dm.tanticipos.Refresh; dm.qanticiposdetalle.Refresh; end else begin qaux.SQL.Clear; qaux.SQL.Add('select id,nombre from trabajadores where seleccionado=1'); qaux.Open; if qaux.RecordCount > 0 then begin while not qaux.Eof do begin dm.tanticipos.Append; dm.tanticiposid.Value := contador; dm.tanticiposfecha.Value := fechaanticipos.Date; totalimporte := strtofloat(edimporte.Text); dm.tanticiposimporte.Value := strtofloat(FormatFloat('0.00', totalimporte)); dm.tanticiposimporteletras.Value := CantidadEnLetra(dm.tanticiposimporte.AsFloat, 1); dm.tanticiposobservaciones.Value := edconcepto.Text; dm.tanticiposformapago.Value := edformapago.Text; dm.tanticiposestado.Value := 'C'; dm.tanticiposidt.Value := qaux.Fields[0].AsInteger; dm.tanticipostrabajador.Value := qaux.Fields[1].AsString; dm.tanticipos.post; contador := contador + 1; qaux.Next; nomfechadesde.Date := fechajornales.Date; nomfechahasta.Date := fechajornales.Date; btactualizarempleadosnominas.Click; end; end else begin showmessage('DEBE SELECCIONAR AL MENOS UN TRABAJADOR'); end; end; btatnuevo.Enabled := true; btatborrar.Enabled := true; btatguardar.Enabled := false; btatmodificar.Enabled := true; btatcancelar.Enabled := false; fechaanticipos.Enabled := false; panticipos.Enabled := false; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=0'); qaux.ExecSQL; qempleados.Refresh; checktodos.Checked := false; end; procedure TBASE.btatimprimirClick(Sender: TObject); var X: Integer; anyo, mes, dia, hora, minutos, segundos, milisegundos: word; txanyo, txmes, txdia, txhora, txminutos, txsegundos, txnumlineas, txcantidadtotal, txlinea: string; txnombre, txdireccion, txtotalapagar, archivo, tnif, tdireccion, tcuenta, tpoblacion, tcp: string; tempresacif, tempresanombre, tempresadireccion, tempresapoblacion, tempresacp, tempresacuenta: string; linea: real; F: TextFile; begin case listainformesanticipos.ItemIndex of 0: begin informedb.DataSource := dm.dsqanticiposdetalle; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\ANTICIPOSGENERAL.fr3'); // informes.Report.FileName:=dm.qnominasdetalle.asstring; informes.ShowReport(); informes.Clear end; 1: begin informedb.DataSource := dm.dsqanticiposdetalle; dm.qanticiposdetalle.Close; dm.qanticiposdetalle.filter := 'formapago=' + '''' + listainformesanticipos.Text + ''''; dm.qanticiposdetalle.filtered := true; dm.qanticiposdetalle.Open; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\recibo.fr3'); informes.ShowReport(); informes.Clear; dm.qanticiposdetalle.Close; dm.qanticiposdetalle.filtered := false; dm.qanticiposdetalle.Open; end; 2: begin dm.qanticiposdetalle.Close; dm.qanticiposdetalle.filter := 'formapago=' + '''' + listainformesanticipos.Text + ''''; dm.qanticiposdetalle.filtered := true; dm.qanticiposdetalle.Open; qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('select sum(importe) from (' + dm.qanticiposdetalle.SQL.Text + ') as e where formapago=' + '''' + listainformesanticipos.Text + '''' + 'group by formapago'); qaux.Open; decodedate(Date(), anyo, mes, dia); decodetime(Date(), hora, minutos, segundos, milisegundos); txanyo := floattostr(anyo); txmes := floattostr(mes); txdia := floattostr(dia); txhora := floattostr(hora); txminutos := floattostr(minutos); txsegundos := floattostr(segundos); txnumlineas := inttostr(dm.qanticiposdetalle.RecordCount); txcantidadtotal := FormatFloat(',0.00', qaux.Fields[0].AsFloat); txcantidadtotal := stringreplace(txcantidadtotal, '.', '', [rfReplaceAll]); txcantidadtotal := stringreplace(txcantidadtotal, ',', '.', [rfReplaceAll]); if Length(txmes) = 1 then txmes := '0' + txmes; if Length(txdia) = 1 then txdia := '0' + txdia; if Length(txhora) = 1 then txhora := '0' + txhora; if Length(txminutos) = 1 then txminutos := '0' + txminutos; if Length(txsegundos) = 1 then txsegundos := '0' + txsegundos; SaveDialog1.FileName := 'transferencia.xml'; SaveDialog1.Execute(); archivo := SaveDialog1.FileName; qaux.Close; qaux.SQL.Clear; qaux.SQL.Add ('select cif,nombre,direccion,codpost,poblacion,concat(cc_iban,cc_entidad,cc_oficina,cc_dc,cc_cc) as cuenta from empresa where id=' + dm.tempresaid.AsString); qaux.Open; tempresacif := qaux.Fields[0].AsString; tempresanombre := qaux.Fields[1].AsString; tempresanombre := stringreplace(tempresanombre, '/', '?', [rfReplaceAll]); tempresanombre := stringreplace(tempresanombre, 'º', '?', [rfReplaceAll]); tempresanombre := stringreplace(tempresanombre, 'Ñ', 'N', [rfReplaceAll]); tempresadireccion := qaux.Fields[2].AsString; tempresadireccion := stringreplace(tempresadireccion, '/', '?', [rfReplaceAll]); tempresadireccion := stringreplace(tempresadireccion, 'º', '?', [rfReplaceAll]); tempresadireccion := stringreplace(tempresadireccion, 'Ñ', 'N', [rfReplaceAll]); tempresapoblacion := qaux.Fields[4].AsString; tempresapoblacion := stringreplace(tempresapoblacion, '/', '?', [rfReplaceAll]); tempresapoblacion := stringreplace(tempresapoblacion, 'º', '?', [rfReplaceAll]); tempresapoblacion := stringreplace(tempresapoblacion, 'Ñ', 'N', [rfReplaceAll]); tempresacp := qaux.Fields[3].AsString; tempresacuenta := qaux.Fields[5].AsString; AssignFile(F, SaveDialog1.FileName); Rewrite(F); WriteLn(F, ''); WriteLn(F, '' + tempresacif + 'AN0' + txanyo + txmes + txdia + txhora + txminutos + txsegundos + ''); WriteLn(F, '' + txanyo + '-' + txmes + '-' + txdia + 'T' + txhora + ':' + txminutos + ':' + txsegundos + ''); WriteLn(F, '' + txnumlineas + '' + txcantidadtotal + ''); WriteLn(F, '' + tempresanombre + '' + tempresacif + 'AN0'); WriteLn(F, 'SCT' + txanyo + txmes + txdia + txhora + txminutos + txsegundos + '001TRFtrue' + txnumlineas + '' + txcantidadtotal + ''); WriteLn(F, '' + txanyo + '-' + txmes + '-' + txdia + '' + tempresanombre + ''); WriteLn(F, 'ES' + tempresadireccion + '' + tempresacp + ' ' + tempresapoblacion + ''); WriteLn(F, '' + tempresacuenta + 'EURCCRIES2AXXXSLEV'); dm.qanticiposdetalle.First; linea := 1; while not dm.qanticiposdetalle.Eof do begin qaux.Close; qaux.SQL.Clear; qaux.SQL.Add ('select nif,direccion,poblacion,cp,concat(cbiban,cbbanco,cboficina,cbdc,cbcc) as cuenta from trabajadores where id=' + dm.qanticiposdetalleidt.AsString); qaux.Open; tnif := qaux.Fields[0].AsString; tdireccion := qaux.Fields[1].AsString; tpoblacion := qaux.Fields[2].AsString; tcp := qaux.Fields[3].AsString; tcuenta := qaux.Fields[4].AsString; txlinea := FormatFloat(',0000', linea); txlinea := stringreplace(txlinea, '.', '', [rfReplaceAll]); txnombre := stringreplace(dm.qanticiposdetalletrabajador.AsString, 'Ñ', 'N', [rfReplaceAll]); txdireccion := stringreplace(tdireccion, '/', '?', [rfReplaceAll]); txdireccion := stringreplace(txdireccion, 'º', '?', [rfReplaceAll]); txdireccion := stringreplace(txdireccion, 'Ñ', 'N', [rfReplaceAll]); txtotalapagar := FormatFloat(',0.00', dm.qanticiposdetalleimporte.AsFloat); txtotalapagar := stringreplace(txtotalapagar, '.', '', [rfReplaceAll]); txtotalapagar := stringreplace(txtotalapagar, ',', '.', [rfReplaceAll]); WriteLn(F, '' + tnif + '-20161-' + txanyo + txmes + txdia + txhora + txminutos + txsegundos + '-' + txlinea + ''); WriteLn(F, 'SEPASALA' + txtotalapagar + ''); WriteLn(F, '' + txnombre + 'ES'); WriteLn(F, '' + txdireccion + '' + tcp + ' ' + tpoblacion + ' . .'); WriteLn(F, '' + tcuenta + 'SALANOMINA'); dm.qanticiposdetalle.Next; linea := linea + 1; end; WriteLn(F, ''); CloseFile(F); dm.qanticiposdetalle.Close; dm.qanticiposdetalle.filtered := false; dm.qanticiposdetalle.Open; end; 3: begin informedb.DataSource := dm.dsqanticiposdetalle; dm.qanticiposdetalle.Close; dm.qanticiposdetalle.filter := 'formapago=' + '''' + listainformesanticipos.Text + ''''; dm.qanticiposdetalle.filtered := true; dm.qanticiposdetalle.Open; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\pagare.fr3'); // informes.Report.FileName:=dm.qnominasdetalle.asstring; informes.ShowReport(); informes.Clear; dm.qanticiposdetalle.Close; dm.qanticiposdetalle.filtered := false; dm.qanticiposdetalle.Open; end; end; end; procedure TBASE.btatmodificarClick(Sender: TObject); var totaljornal: real; begin dm.tanticipos.Locate('id', dm.qanticiposdetalleid.AsInteger, [locaseinsensitive, lopartialkey]); dm.tanticipos.edit; fechaanticipos.Datetime := dm.qanticiposdetallefecha.AsDateTime; edconcepto.Enabled := true; edimporte.Enabled := true; edformapago.Enabled := true; edconcepto.Text := dm.qanticiposdetalleobservaciones.AsString; edimporte.Text := dm.qanticiposdetalleimporte.AsString; edformapago.Text := dm.qanticiposdetalleformapago.AsString; fechaanticipos.Enabled := true; panticipos.Enabled := true; btatnuevo.Enabled := false; btatmodificar.Enabled := false; btatguardar.Enabled := true; btatcancelar.Enabled := true; btatborrar.Enabled := false; end; procedure TBASE.btatnuevoClick(Sender: TObject); begin edconcepto.Enabled := true; edimporte.Enabled := true; edformapago.Enabled := true; fechaanticipos.Enabled := true; panticipos.Enabled := true; btatnuevo.Enabled := false; btatmodificar.Enabled := false; btatguardar.Enabled := true; btatcancelar.Enabled := true; btatborrar.Enabled := false; end; procedure TBASE.bteborrarClick(Sender: TObject); begin dm.tanticipos.Close; dm.tanticipos.filter := 'id=' + dm.qanticiposid.AsString; dm.tanticipos.filtered := true; dm.tanticipos.Open; dm.tanticipos.Delete; dm.qanticipos.Refresh; dm.qanticipos.First; end; procedure TBASE.btedocborrarClick(Sender: TObject); begin dmtr.qdocumentos.Delete; end; procedure TBASE.btedoccancelarClick(Sender: TObject); begin dmtr.qdocumentos.cancel; end; procedure TBASE.btedocguardarClick(Sender: TObject); var archivo: TMemorystream; ext, nomarchivo: string; begin { try ext:= ExtractFileExt(opendialog1.FileName); nomarchivo:= extractfilename(opendialog1.FileName); dmtr.documentosidt.Value:=templeadosid.Asinteger; dmtr.documentoside.Value:=templeadoside.AsInteger; dmtr.documentosnomarchivo.Value:=nomarchivo; // dmtr.documentosdescripcion.Value:=nomarchivo; dmtr.documentosfecha.Value:=date(); dmtr.documentosextension.Value:=ext; dmtr.documentosarchivo.LoadFromFile(opendialog1.FileName); dmtr.documentos.Post; finally end; } end; procedure TBASE.btedocmodificarClick(Sender: TObject); var ext: string; begin if DialogLotes.Execute then begin try ext := ExtractFileExt(DialogLotes.FileName); if (ext = '.jpg') or (ext = '.jpeg') or (ext = '.bmp') or (ext = '.png') then begin imgfoto.Picture.LoadFromFile(DialogLotes.FileName); imgfoto.Visible := true; end finally dmtr.qdocumentos.edit; DBGrid75.SetFocus; end; end; end; procedure TBASE.btedocnuevoClick(Sender: TObject); var ext, nomarchivo: string; X: Integer; begin { if opendialog1.Execute then begin try finally if opendialog1.Files.Count=1 then begin dmtr.documentos.Append; ext:= ExtractFileExt(opendialog1.FileName); nomarchivo:= extractfilename(opendialog1.FileName); dmtr.documentosidt.Value:=templeadosid.Asinteger; dmtr.documentosfecha.Value:=date(); dmtr.documentoside.Value:=templeadoside.AsInteger; dmtr.documentosnomarchivo.Value:=nomarchivo; dmtr.documentosdescripcion.Value:=nomarchivo; dmtr.documentosextension.Value:=ext; dmtr.documentosarchivo.LoadFromFile(opendialog1.FileName); dmtr.documentos.Post; end else begin memo1.Clear; memo1.Lines.AddStrings(opendialog1.files); for x := 0 to opendialog1.Files.Count-1 do begin dmtr.documentos.Append; ext:= ExtractFileExt(memo1.Lines[x]); nomarchivo:= extractfilename(memo1.Lines[x]); dmtr.documentosidt.Value:=templeadosid.Asinteger; dmtr.documentosfecha.Value:=date(); dmtr.documentoside.Value:=templeadoside.AsInteger; dmtr.documentosnomarchivo.Value:=nomarchivo; dmtr.documentosdescripcion.Value:=nomarchivo; dmtr.documentosextension.Value:=ext; dmtr.documentosarchivo.LoadFromFile(memo1.Lines[x]); dmtr.documentos.Post; end; end; end; end; } end; procedure TBASE.bteModificarClick(Sender: TObject); begin dm.tanticipos.Locate('id', dm.qanticiposid.AsString, [locaseinsensitive]); dm.tanticipos.edit; fechaanticipo.SetFocus; end; procedure TBASE.btdborrarClick(Sender: TObject); begin dmtr.qdocumentos.Delete; end; procedure TBASE.btdcancelarClick(Sender: TObject); begin dmtr.qdocumentos.cancel; end; procedure TBASE.btddescargarClick(Sender: TObject); var archivo: string; begin archivo := dmtr.qdocumentosnomarchivo.AsString; SaveDialog1.FileName := archivo; SaveDialog1.Execute(); archivo := SaveDialog1.FileName; dmtr.qdocumentosarchivo.SaveToFile(archivo); end; procedure TBASE.btdguardarClick(Sender: TObject); var archivo: TMemorystream; ext, nomarchivo: string; begin try ext := ExtractFileExt(DialogLotes.FileName); nomarchivo := extractfilename(DialogLotes.FileName); dmtr.documentos_tmpidlote.Value := dmtr.qlotesid.AsInteger; dmtr.documentos_tmpide.Value := dmtr.qlotesidempresa.AsInteger; dmtr.documentos_tmpnomarchivo.Value := nomarchivo; dmtr.documentos_tmpdescripcion.Value := nomarchivo; dmtr.documentos_tmpfecha.Value := Date(); dmtr.documentos_tmpextension.Value := ext; dmtr.documentos_tmparchivo.LoadFromFile(DialogLotes.FileName); dmtr.documentos_tmp.post; finally end; end; procedure TBASE.btdmodificarClick(Sender: TObject); var ext: string; begin if DialogLotes.Execute then begin try ext := ExtractFileExt(DialogLotes.FileName); if (ext = '.jpg') or (ext = '.jpeg') or (ext = '.bmp') or (ext = '.png') then begin imgfoto.Picture.LoadFromFile(DialogLotes.FileName); imgfoto.Visible := true; end finally dmtr.qdocumentos.edit; DBGrid34.SetFocus; end; end; end; procedure TBASE.btdnuevoClick(Sender: TObject); var ext, nomarchivo: string; X: Integer; begin if DialogLotes.Execute then begin try finally if DialogLotes.Files.Count = 1 then begin qaux.SQL.Clear; qaux.SQL.Add('delete from documentos_tmp '); qaux.ExecSQL; dmtr.documentos_tmp.Open; dmtr.documentos_tmp.Append; ext := ExtractFileExt(DialogLotes.FileName); nomarchivo := extractfilename(DialogLotes.FileName); dmtr.documentos_tmpidlote.Value := dmtr.qlotescodigo.AsInteger; dmtr.documentos_tmpfecha.Value := Date(); dmtr.documentos_tmpide.Value := dmtr.qlotesidempresa.AsInteger; dmtr.documentos_tmpnomarchivo.Value := nomarchivo; dmtr.documentos_tmpdescripcion.Value := nomarchivo; dmtr.documentos_tmpextension.Value := ext; dmtr.documentos_tmparchivo.LoadFromFile(DialogLotes.FileName); dmtr.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; dmtr.qdocumentos.Close; dmtr.qdocumentos.SQL.Clear; dmtr.qdocumentos.SQL.Add('select * from documentos where ide=' + dmtr.qlotesidempresa.AsString + ' and idlote=' + dmtr.qlotescodigo.AsString + ' order by fecha desc'); dmtr.qdocumentos.Open; end else begin Memo1.Clear; Memo1.Lines.AddStrings(DialogLotes.Files); for X := 0 to DialogLotes.Files.Count - 1 do begin qaux.SQL.Clear; qaux.SQL.Add('delete from documentos_tmp '); qaux.ExecSQL; dmtr.documentos_tmp.Open; dmtr.documentos_tmp.Append; ext := ExtractFileExt(Memo1.Lines[X]); nomarchivo := extractfilename(Memo1.Lines[X]); dmtr.documentos_tmpidt.Value := dmtr.qlotescodigo.AsInteger; dmtr.documentos_tmpfecha.Value := Date(); dmtr.documentos_tmpide.Value := dmtr.qlotesidempresa.AsInteger; dmtr.documentos_tmpnomarchivo.Value := nomarchivo; dmtr.documentos_tmpdescripcion.Value := nomarchivo; dmtr.documentos_tmpextension.Value := ext; dmtr.documentos_tmparchivo.LoadFromFile(Memo1.Lines[X]); dmtr.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; dmtr.qdocumentos.Close; dmtr.qdocumentos.SQL.Clear; dmtr.qdocumentos.SQL.Add('select * from documentos where ide=' + dmtr.qlotesidempresa.AsString + ' and idt=' + dmtr.qlotescodigo.AsString + ' order by fecha desc'); dmtr.qdocumentos.Open; end; end; end; end; end; procedure TBASE.btdverClick(Sender: TObject); var nomarchivo: string; begin nomarchivo := dmtr.qdocumentosnomarchivo.AsString; Deletefile('c:\agrigest\tmp\*.*'); dmtr.qdocumentosarchivo.SaveToFile('c:\agrigest\tmp\' + nomarchivo); ShellExecute(BASE.Handle, nil, PChar('c:\agrigest\tmp\' + nomarchivo), '', '', SW_SHOWNORMAL); end; procedure TBASE.Button3Click(Sender: TObject); var archivo: string; begin SaveDialog1.FileName := stringreplace(('ENTRADAS-' + dmproduccion.qpartesdiariosnombre_almacen. AsString + '-' + dmproduccion.qpartesdiariosfecha.AsString + '.xlsx'), '/', '-', [rfReplaceAll]); SaveDialog1.Execute(); archivo := SaveDialog1.FileName; try ExportaraExcel(archivo, 'entradas', DBGrid63); finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure TBASE.Button40Click(Sender: TObject); var PanelDC: HDC; Jpg: TJPEGImage; bmp: Tbitmap; ext: string; imagen: tPicture; archivo: TMemorystream; begin if OpenPictureDialog1.Execute then begin imagen := tPicture.Create; bmp := Tbitmap.Create; Jpg := TJPEGImage.Create; try imgfotoe.Visible := true; dm.tempresa.edit; dm.tempresalogo.LoadFromFile(OpenPictureDialog1.FileName); dm.tempresa.post; ext := ExtractFileExt(OpenPictureDialog1.FileName); If not DirectoryExists('c:\agrigest\tmp') then CreateDir('c:\agrigest\tmp'); Deletefile('c:\agrigest\tmp\empimg' + ext); imgfotoe.Picture := nil; dm.tempresalogo.SaveToFile('c:\agrigest\tmp\empimg' + ext); imgfotoe.Picture.LoadFromFile('c:\agrigest\tmp\empimg' + ext); finally imagen.Free; end; end; end; procedure TBASE.Button41Click(Sender: TObject); begin dm.tempresa.edit; dm.tempresalogo.Value := nil; dm.tempresa.post; end; procedure TBASE.Button42Click(Sender: TObject); begin dm.tempresa.edit; dm.tempresafirmaresponsable.Value := nil; dm.tempresa.post; end; procedure TBASE.Button43Click(Sender: TObject); var archivo: string; begin SaveDialog1.FileName := stringreplace(('ENTRADAS-' + dmproduccion.qpartesdiariosnombre_almacen. AsString + '-' + dmproduccion.qpartesdiariosfecha.AsString + '.xlsx'), '/', '-', [rfReplaceAll]); SaveDialog1.Execute(); archivo := SaveDialog1.FileName; try ExportaraExcel(archivo, 'entradas', DBGrid63); finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure TBASE.Button44Click(Sender: TObject); var archivo: string; begin SaveDialog1.FileName := stringreplace(('ENVASADOS-' + dmproduccion.qpartesdiariosnombre_almacen. AsString + '-' + dmproduccion.qpartesdiariosfecha.AsString + '.xlsx'), '/', '-', [rfReplaceAll]); SaveDialog1.Execute(); archivo := SaveDialog1.FileName; try ExportaraExcel(archivo, 'envasados', DBGrid62); finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure TBASE.Button45Click(Sender: TObject); begin dmestadisticas.qinfdesechos.Close; dmestadisticas.qinfdesechos.Prepare; dmestadisticas.qinfdesechos.ParamByName('FINICIO').AsDate := dmestadisticas.qcampanyasfechainicio.AsDateTime; dmestadisticas.qinfdesechos.ParamByName('FFIN').AsDate := dmestadisticas.qcampanyasfechafin.AsDateTime; dmestadisticas.qinfdesechos.ParamByName('PARCELA').AsString := dm.qparcelascodpar.AsString; dmestadisticas.qinfdesechos.Open; informedb.DataSource := dmestadisticas.dsqinfdesechos; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\entradasparcela.fr3'); informes.Variables.Variables['TITULO'] := QUOTEDSTR('Parcela: ' + dm.qparcelasnombre.AsString + ' Campaña: ' + dmestadisticas.qcampanyasdescripcion.AsString + ' DESECHOS'); informes.ShowReport(); informes.Clear end; procedure TBASE.Button47Click(Sender: TObject); var archivo: string; begin SaveDialog1.FileName := stringreplace(('ENTRADAS DETALLADAS-' + dmproduccion.qpartesdiariosnombre_almacen.AsString + '-' + dmproduccion.qpartesdiariosfecha.AsString + '.xlsx'), '/', '-', [rfReplaceAll]); SaveDialog1.Execute(); archivo := SaveDialog1.FileName; try ExportaraExcel(archivo, 'entradas', DBGrid59); finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure TBASE.Button48Click(Sender: TObject); var archivo: string; begin SaveDialog1.FileName := stringreplace(('SALIDAS DETALLADAS-' + dmproduccion.qpartesdiariosnombre_almacen.AsString + '-' + dmproduccion.qpartesdiariosfecha.AsString + '.xlsx'), '/', '-', [rfReplaceAll]); SaveDialog1.Execute(); archivo := SaveDialog1.FileName; try ExportaraExcel(archivo, 'entradas', DBGrid60); finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure TBASE.Button49Click(Sender: TObject); begin qgastosparcela.Close; qgastosparcela.Prepare; qgastosparcela.ParamByName('DESDE').AsDate := cdesde.Date; qgastosparcela.ParamByName('HASTA').AsDate := chasta.Date; qgastosparcela.ParamByName('PARCELA').AsString := dm.qparcelascodpar.AsString; qgastosparcela.Open; end; procedure TBASE.Button4Click(Sender: TObject); begin baceptarempleados.Visible := true; bcancelarempleados.Visible := true; Vaciar.Visible := true; Vaciar2.Visible := true; templeados.edit; DBEdit1.Enabled := false; end; procedure TBASE.Button50Click(Sender: TObject); begin informedb.DataSource := dsqgastosparcela; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\informegastos.fr3'); informes.Variables.Variables['PERIODO'] := QUOTEDSTR('Desde el ' + datetostr(cdesde.Date) + ' hasta el ' + datetostr(chasta.Date)); informes.ShowReport(); informes.Clear end; procedure TBASE.Button51Click(Sender: TObject); var archivo: string; begin SaveDialog1.FileName := 'GASTOS DE LA PARCELA ' + dm.qparcelascodpar.AsString; SaveDialog1.Execute(); archivo := SaveDialog1.FileName; try ExportaraExcel(archivo, 'GASTOS', DBGrid42); finally showmessage('Los datos han sido exportados correctamente'); end; end; procedure TBASE.Button52Click(Sender: TObject); begin comboprodmesas.KeyValue := null; comboprodmprimas.KeyValue := null; comboprodproducto.KeyValue := null; hdesde.ItemIndex:=5; hhasta.ItemIndex:=24; btprodaceptar.Click; end; procedure TBASE.Button53Click(Sender: TObject); begin qcostesrestosdia.Prepare; qcostesrestosdia.ParamByName('EMPRESA').asinteger:=dmproduccion.qpartesdiariosidempresa.AsInteger ; qcostesrestosdia.ParamByName('ALMACEN').asinteger:=dmproduccion.qpartesdiariosalmacen.AsInteger ; qcostesrestosdia.ParamByName('FECHA').asdatetime:=dmproduccion.qpartesdiariosfecha.AsDateTime ; qcostesrestosdia.Open; restosdia := Trestosdia.Create(nil); try restosdia.ShowModal; finally restosdia.Free; qcostesrestosdia.close; end; end; procedure TBASE.Button54Click(Sender: TObject); var archivo,vmes,vnombre,vnif,vhoras:string; tdia,tmes,tanyo:word; vdia,vanyo,vide,vidt:integer; begin qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('delete from emp_asistencia'); qaux.execsql; qasistencia.Open; dm.qnominasdetalle.First; while not dm.qnominasdetalle.Eof do begin decodedate(dm.qnominasdetallefecha.AsDateTime,tanyo,tmes,tdia); vdia:=tdia; vanyo:=tanyo; vhoras:=floattostr(dm.qnominasdetalleqhoras.AsFloat); case tmes of 1:vmes:='ENERO'; 2:vmes:='FEBRERO'; 3:vmes:='MARZO'; 4:vmes:='ABRIL'; 5:vmes:='MAYO'; 6:vmes:='JUNIO'; 7:vmes:='JULIO'; 8:vmes:='AGOSTO'; 9:vmes:='SEPTIEMBRE'; 10:vmes:='OCTUBRE'; 11:vmes:='NOVIEMBRE'; 12:vmes:='DICIEMBRE'; end; vide:=dm.qnominasdetalleempresa.AsInteger; vidt:=dm.qnominasdetalleidt.AsInteger; qempleados.Locate('ide,id',vararrayof([vide,vidt]),[locaseinsensitive]); vnif:=qempleadosnif.asstring; vnombre:=qempleadosnombre.AsString; qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('select * from emp_asistencia where ide=:EMPRESA and idt=:TRABAJADOR and anyo=:ANYO and mes=:MES'); qaux.Prepare; qaux.ParamByName('EMPRESA').AsInteger:=vide; qaux.ParamByName('TRABAJADOR').AsInteger:=vidt; qaux.ParamByName('ANYO').AsInteger:=vanyo; qaux.ParamByName('MES').Asstring:=vmes; qaux.Open; if qaux.RecordCount=0 then begin qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('insert into emp_asistencia (ide,idt,nif,nombre,anyo,mes) values (:EMPRESA,:TRABAJADOR,:NIF,:NOMBRE,:ANYO,:MES)'); qaux.Prepare; qaux.ParamByName('EMPRESA').AsInteger:=vide; qaux.ParamByName('TRABAJADOR').AsInteger:=vidt; qaux.ParamByName('NIF').Asstring:=vnif; qaux.ParamByName('NOMBRE').Asstring:=vnombre; qaux.ParamByName('ANYO').AsInteger:=vanyo; qaux.ParamByName('MES').Asstring:=vmes; qaux.execsql; qasistencia.Refresh; qasistencia.Locate('ide,idt,anyo,mes',vararrayof([vide,vidt,vanyo,vmes]),[locaseinsensitive]); end; qasistencia.Edit; case vdia of { 1:qasistenciad1.AsString:='X'; 2:qasistenciad2.AsString:='X'; 3:qasistenciad3.AsString:='X'; 4:qasistenciad4.AsString:='X'; 5:qasistenciad5.AsString:='X'; 6:qasistenciad6.AsString:='X'; 7:qasistenciad7.AsString:='X'; 8:qasistenciad8.AsString:='X'; 9:qasistenciad9.AsString:='X'; 10:qasistenciad10.AsString:='X'; 11:qasistenciad11.AsString:='X'; 12:qasistenciad12.AsString:='X'; 13:qasistenciad13.AsString:='X'; 14:qasistenciad14.AsString:='X'; 15:qasistenciad15.AsString:='X'; 16:qasistenciad16.AsString:='X'; 17:qasistenciad17.AsString:='X'; 18:qasistenciad18.AsString:='X'; 19:qasistenciad19.AsString:='X'; 20:qasistenciad20.AsString:='X'; 21:qasistenciad21.AsString:='X'; 22:qasistenciad22.AsString:='X'; 23:qasistenciad23.AsString:='X'; 24:qasistenciad24.AsString:='X'; 25:qasistenciad25.AsString:='X'; 26:qasistenciad26.AsString:='X'; 27:qasistenciad27.AsString:='X'; 28:qasistenciad28.AsString:='X'; 29:qasistenciad29.AsString:='X'; 30:qasistenciad30.AsString:='X'; 31:qasistenciad31.AsString:='X'; } 1:if qasistenciad1.asstring=' ' then qasistenciad1.value:=vhoras else qasistenciad1.Value:=floattostr(strtofloat(qasistenciad1.AsString)+strtofloat(vhoras)); 2:if qasistenciad2.asstring=' ' then qasistenciad2.value:=vhoras else qasistenciad2.Value:=floattostr(strtofloat(qasistenciad2.AsString)+strtofloat(vhoras)); 3:if qasistenciad3.asstring=' ' then qasistenciad3.value:=vhoras else qasistenciad3.Value:=floattostr(strtofloat(qasistenciad3.AsString)+strtofloat(vhoras)); 4:if qasistenciad4.asstring=' ' then qasistenciad4.value:=vhoras else qasistenciad4.Value:=floattostr(strtofloat(qasistenciad4.AsString)+strtofloat(vhoras)); 5:if qasistenciad5.asstring=' ' then qasistenciad5.value:=vhoras else qasistenciad5.Value:=floattostr(strtofloat(qasistenciad5.AsString)+strtofloat(vhoras)); 6:if qasistenciad6.asstring=' ' then qasistenciad6.value:=vhoras else qasistenciad6.Value:=floattostr(strtofloat(qasistenciad6.AsString)+strtofloat(vhoras)); 7:if qasistenciad7.asstring=' ' then qasistenciad7.value:=vhoras else qasistenciad7.Value:=floattostr(strtofloat(qasistenciad7.AsString)+strtofloat(vhoras)); 8:if qasistenciad8.asstring=' ' then qasistenciad8.value:=vhoras else qasistenciad8.Value:=floattostr(strtofloat(qasistenciad8.AsString)+strtofloat(vhoras)); 9:if qasistenciad9.asstring=' ' then qasistenciad9.value:=vhoras else qasistenciad9.Value:=floattostr(strtofloat(qasistenciad9.AsString)+strtofloat(vhoras)); 10:if qasistenciad10.asstring=' ' then qasistenciad10.value:=vhoras else qasistenciad10.Value:=floattostr(strtofloat(qasistenciad10.AsString)+strtofloat(vhoras)); 11:if qasistenciad11.asstring=' ' then qasistenciad11.value:=vhoras else qasistenciad11.Value:=floattostr(strtofloat(qasistenciad11.AsString)+strtofloat(vhoras)); 12:if qasistenciad12.asstring=' ' then qasistenciad12.value:=vhoras else qasistenciad12.Value:=floattostr(strtofloat(qasistenciad12.AsString)+strtofloat(vhoras)); 13:if qasistenciad13.asstring=' ' then qasistenciad13.value:=vhoras else qasistenciad13.Value:=floattostr(strtofloat(qasistenciad13.AsString)+strtofloat(vhoras)); 14:if qasistenciad14.asstring=' ' then qasistenciad14.value:=vhoras else qasistenciad14.Value:=floattostr(strtofloat(qasistenciad14.AsString)+strtofloat(vhoras)); 15:if qasistenciad15.asstring=' ' then qasistenciad15.value:=vhoras else qasistenciad15.Value:=floattostr(strtofloat(qasistenciad15.AsString)+strtofloat(vhoras)); 16:if qasistenciad18.asstring=' ' then qasistenciad18.value:=vhoras else qasistenciad18.Value:=floattostr(strtofloat(qasistenciad18.AsString)+strtofloat(vhoras)); 17:if qasistenciad17.asstring=' ' then qasistenciad17.value:=vhoras else qasistenciad17.Value:=floattostr(strtofloat(qasistenciad17.AsString)+strtofloat(vhoras)); 18:if qasistenciad18.asstring=' ' then qasistenciad18.value:=vhoras else qasistenciad18.Value:=floattostr(strtofloat(qasistenciad18.AsString)+strtofloat(vhoras)); 19:if qasistenciad19.asstring=' ' then qasistenciad19.value:=vhoras else qasistenciad19.Value:=floattostr(strtofloat(qasistenciad19.AsString)+strtofloat(vhoras)); 20:if qasistenciad20.asstring=' ' then qasistenciad20.value:=vhoras else qasistenciad20.Value:=floattostr(strtofloat(qasistenciad20.AsString)+strtofloat(vhoras)); 21:if qasistenciad21.asstring=' ' then qasistenciad21.value:=vhoras else qasistenciad21.Value:=floattostr(strtofloat(qasistenciad21.AsString)+strtofloat(vhoras)); 22:if qasistenciad22.asstring=' ' then qasistenciad22.value:=vhoras else qasistenciad22.Value:=floattostr(strtofloat(qasistenciad22.AsString)+strtofloat(vhoras)); 23:if qasistenciad23.asstring=' ' then qasistenciad23.value:=vhoras else qasistenciad23.Value:=floattostr(strtofloat(qasistenciad23.AsString)+strtofloat(vhoras)); 24:if qasistenciad24.asstring=' ' then qasistenciad24.value:=vhoras else qasistenciad24.Value:=floattostr(strtofloat(qasistenciad24.AsString)+strtofloat(vhoras)); 25:if qasistenciad25.asstring=' ' then qasistenciad25.value:=vhoras else qasistenciad25.Value:=floattostr(strtofloat(qasistenciad25.AsString)+strtofloat(vhoras)); 26:if qasistenciad26.asstring=' ' then qasistenciad26.value:=vhoras else qasistenciad26.Value:=floattostr(strtofloat(qasistenciad26.AsString)+strtofloat(vhoras)); 27:if qasistenciad27.asstring=' ' then qasistenciad27.value:=vhoras else qasistenciad27.Value:=floattostr(strtofloat(qasistenciad27.AsString)+strtofloat(vhoras)); 28:if qasistenciad28.asstring=' ' then qasistenciad28.value:=vhoras else qasistenciad28.Value:=floattostr(strtofloat(qasistenciad28.AsString)+strtofloat(vhoras)); 29:if qasistenciad29.asstring=' ' then qasistenciad29.value:=vhoras else qasistenciad29.Value:=floattostr(strtofloat(qasistenciad29.AsString)+strtofloat(vhoras)); 30:if qasistenciad30.asstring=' ' then qasistenciad30.value:=vhoras else qasistenciad30.Value:=floattostr(strtofloat(qasistenciad30.AsString)+strtofloat(vhoras)); 31:if qasistenciad31.asstring=' ' then qasistenciad31.value:=vhoras else qasistenciad31.Value:=floattostr(strtofloat(qasistenciad31.AsString)+strtofloat(vhoras)); end; qasistencia.Post; dm.qnominasdetalle.Next; end; decodedate(nomfechadesde.date,tanyo,tmes,tdia); case tmes of 1:vmes:='ENERO'; 2:vmes:='FEBRERO'; 3:vmes:='MARZO'; 4:vmes:='ABRIL'; 5:vmes:='MAYO'; 6:vmes:='JUNIO'; 7:vmes:='JULIO'; 8:vmes:='AGOSTO'; 9:vmes:='SEPTIEMBRE'; 10:vmes:='OCTUBRE'; 11:vmes:='NOVIEMBRE'; 12:vmes:='DICIEMBRE'; end; qasistencia.Close; qasistencia.SQL.Clear; qasistencia.SQL.Add('select * from v_emp_asistencia where ide=:EMPRESA and anyo=:ANYO and mes=:MES order by anyo,nombre2'); qasistencia.Prepare; qasistencia.ParamByName('EMPRESA').AsInteger:=vide; qasistencia.ParamByName('MES').Asstring:=vmes; qasistencia.ParamByName('ANYO').Asinteger:=vanyo; qasistencia.Open; savedialog1.FileName:='PARTE COMUNICACION.xlsx'; savedialog1.Execute(); archivo:=savedialog1.FileName; try Exportaraexcel(archivo,'PARTE',GRIDASISTENCIA); finally showmessage('Los datos han sido exportados correctamente a '+archivo); end; { qasistencia.Close; qasistencia.SQL.Clear; qasistencia.SQL.Add('select * from v_emp_asistencia order by ide,idt,anyo,mes'); qasistencia.Open;} end; procedure TBASE.Button55Click(Sender: TObject); {var hStore: HCERTSTORE; hCert: PCCERT_CONTEXT; CertName: string; dwKeySpec: DWORD; cbKeySpec: DWORD;} begin { // Abre el almacén de certificados "Root" hStore := CertOpenSystemStore(0, 'Root'); if hStore = 0 then RaiseLastOSError; try // Enumera los certificados en el almacén hCert := CertEnumCertificatesInStore(hStore, nil); while hCert <> nil do begin // Obtiene el tipo de clave del certificado cbKeySpec := sizeof(dwKeySpec); if CertGetCertificateContextProperty(hCert, CERT_KEY_SPEC_PROP_ID, @dwKeySpec, cbKeySpec) then begin // Filtra por certificados con tipo de clave CERT_NCRYPT_KEY_SPEC if dwKeySpec = CERT_NCRYPT_KEY_SPEC then begin // Obtiene el nombre del sujeto del certificado CertName := CertNameToStr(hCert^.pCertInfo^.Subject); Memo3.Lines.Add(CertName); end; end; // Obtiene el siguiente certificado hCert := CertEnumCertificatesInStore(hStore, hCert); end; finally // Cierra el almacén de certificados CertCloseStore(hStore, 0); end; } end; procedure TBASE.Button56Click(Sender: TObject); var archivo: string; begin SaveDialog1.FileName := 'PARTE DE COMUNICACION.xlsx'; SaveDialog1.Execute(); archivo := SaveDialog1.FileName; try ExportaraExcel(archivo, 'JORNADAS', DBGrid76); finally showmessage('Los datos han sido exportados correctamente a ' + archivo); end; end; procedure TBASE.Button57Click(Sender: TObject); var archivo: string; begin SaveDialog1.FileName := 'JORNADAS POR GRUPOOS.xlsx'; SaveDialog1.Execute(); archivo := SaveDialog1.FileName; try ExportaraExcel(archivo, 'JORNADAS', DBGrid43); finally showmessage('Los datos han sido exportados correctamente a ' + archivo); end; end; procedure TBASE.Button58Click(Sender: TObject); begin qlistadoporgrupo.close; qlistadoporgrupo.Prepare; qlistadoporgrupo.ParamByName('DESDE').AsDate:=VFECHADESDELG.Date; qlistadoporgrupo.ParamByName('HASTA').AsDate:=VFECHAHASTALG.Date; qlistadoporgrupo.open; end; procedure TBASE.Button59Click(Sender: TObject); var archivo,vmes,vnombre,vnif,vhoras:string; tdia,tmes,tanyo:word; vdia,vanyo,vide,vidt:integer; begin qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('delete from emp_asistencia'); qaux.execsql; qticados.close; qticados.Prepare; qticados.ParamByName('DESDE').AsDate:=vdesdejornadas.Date; qticados.ParamByName('HASTA').AsDate:=vhastajornadas.Date; qticados.Open; qticados.First; while not qticados.Eof do begin decodedate(qticadosfecha.AsDateTime,tanyo,tmes,tdia); vdia:=tdia; vanyo:=tanyo; // vhoras:=floattostr(qticadosnum_horas_m.AsFloat); case tmes of 1:vmes:='ENERO'; 2:vmes:='FEBRERO'; 3:vmes:='MARZO'; 4:vmes:='ABRIL'; 5:vmes:='MAYO'; 6:vmes:='JUNIO'; 7:vmes:='JULIO'; 8:vmes:='AGOSTO'; 9:vmes:='SEPTIEMBRE'; 10:vmes:='OCTUBRE'; 11:vmes:='NOVIEMBRE'; 12:vmes:='DICIEMBRE'; end; vide:=qticadoside.AsInteger; vidt:=qticadosidt.AsInteger; vnif:=qticadosnif.asstring; vnombre:=qticadosnombre.AsString; qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('select * from emp_asistencia where ide=:EMPRESA and idt=:TRABAJADOR and anyo=:ANYO and mes=:MES'); qaux.Prepare; qaux.ParamByName('EMPRESA').AsInteger:=vide; qaux.ParamByName('TRABAJADOR').AsInteger:=vidt; qaux.ParamByName('ANYO').AsInteger:=vanyo; qaux.ParamByName('MES').Asstring:=vmes; qaux.Open; if qaux.RecordCount=0 then begin qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('insert into emp_asistencia (ide,idt,nif,nombre,anyo,mes) values (:EMPRESA,:TRABAJADOR,:NIF,:NOMBRE,:ANYO,:MES)'); qaux.Prepare; qaux.ParamByName('EMPRESA').AsInteger:=vide; qaux.ParamByName('TRABAJADOR').AsInteger:=vidt; qaux.ParamByName('NIF').Asstring:=vnif; qaux.ParamByName('NOMBRE').Asstring:=vnombre; qaux.ParamByName('ANYO').AsInteger:=vanyo; qaux.ParamByName('MES').Asstring:=vmes; qaux.execsql; qasistir.close; qasistir.Open; qasistir.Locate('ide,idt,anyo,mes',vararrayof([vide,vidt,vanyo,vmes]),[locaseinsensitive]); end; qasistir.Edit; case vdia of 1:qasistird1.value:='X'; 2:qasistird2.value:='X'; 3:qasistird3.value:='X'; 4:qasistird4.value:='X'; 5:qasistird5.value:='X'; 6:qasistird6.value:='X'; 7:qasistird7.value:='X'; 8:qasistird8.value:='X'; 9:qasistird9.value:='X'; 10:qasistird10.value:='X'; 11:qasistird11.value:='X'; 12:qasistird12.value:='X'; 13:qasistird13.value:='X'; 14:qasistird14.value:='X'; 15:qasistird15.value:='X'; 16:qasistird16.value:='X'; 17:qasistird17.value:='X'; 18:qasistird18.value:='X'; 19:qasistird19.value:='X'; 20:qasistird20.value:='X'; 21:qasistird21.value:='X'; 22:qasistird22.value:='X'; 23:qasistird23.value:='X'; 24:qasistird24.value:='X'; 25:qasistird25.value:='X'; 26:qasistird26.value:='X'; 27:qasistird27.value:='X'; 28:qasistird28.value:='X'; 29:qasistird29.value:='X'; 30:qasistird30.value:='X'; 31:qasistird31.value:='X'; end; qasistir.Post; qticados.Next; end; decodedate(vdesdejornadas.date,tanyo,tmes,tdia); case tmes of 1:vmes:='ENERO'; 2:vmes:='FEBRERO'; 3:vmes:='MARZO'; 4:vmes:='ABRIL'; 5:vmes:='MAYO'; 6:vmes:='JUNIO'; 7:vmes:='JULIO'; 8:vmes:='AGOSTO'; 9:vmes:='SEPTIEMBRE'; 10:vmes:='OCTUBRE'; 11:vmes:='NOVIEMBRE'; 12:vmes:='DICIEMBRE'; end; qasistir.Close; qasistir.SQL.Clear; qasistir.SQL.Add('select *,(select fechaalta from trabajadores where id=idt) as fechaalta,(select fechabaja from trabajadores where id=idt) as fechabaja from v_emp_asistencia where ide=:EMPRESA and anyo=:ANYO and mes=:MES order by anyo,nombre'); qasistir.Prepare; qasistir.ParamByName('EMPRESA').AsInteger:=vide; qasistir.ParamByName('MES').Asstring:=vmes; qasistir.ParamByName('ANYO').Asinteger:=vanyo; qasistir.Open; end; procedure TBASE.Button5Click(Sender: TObject); begin dm.qinfjornales.Close; dm.qinfjornales.SQL.Clear; dm.qinfjornales.SQL := qjornales.SQL; dm.qinfjornales.Open; informedb.DataSource := dm.dsqinfjornales; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\JORNALES.fr3'); informes.Report.FileName := TMES.Text + ' ' + qjornalestrabajador.AsString; informes.ShowReport(); informes.Clear end; procedure TBASE.Button6Click(Sender: TObject); begin while not dm.qnominasdetalle.Eof do begin tjornales.Locate('id', dm.qnominasdetalleid.AsInteger, [locaseinsensitive, lopartialkey]); tjornales.Delete; dm.qnominasdetalle.Next; end; dm.qnominasdetalle.Refresh; end; procedure TBASE.Button7Click(Sender: TObject); begin informedb.DataSource := dm.DSprenominas; informes.Report.Clear; if COMBOLISTADOS.ItemIndex = 0 then informes.LoadFromFile('c:\agrigest\informes\PREVIONOMINAS.fr3'); if COMBOLISTADOS.ItemIndex = 1 then informes.LoadFromFile('c:\agrigest\informes\PREVIONOMINASASESORIA.fr3'); if COMBOLISTADOS.ItemIndex = 2 then informes.LoadFromFile('c:\agrigest\informes\PREVIONOMINASBANCO.fr3'); // informes.Report.FileName:=TMES.Text+' ' + qjornalestrabajador.asstring; informes.ShowReport(); informes.Clear end; procedure TBASE.Button8Click(Sender: TObject); var archivo: string; begin archivo := 'c:\agrigest\entradas.xlsx'; try ExportaraExcel(archivo, 'ENTRADAS', DBGrid46); finally showmessage ('Los datos han sido exportados correctamente a C:\AGRIGEST\entradas.XLSX'); end; end; procedure TBASE.btJimprimirClick(Sender: TObject); begin informedb.DataSource := dm.dsqnominasdetalle; dm.qnominasdetalle.SortedFields := 'trabajador,fecha,parcela'; dm.qnominasdetalle.SortType := stascending; informes.Report.Clear; informes.LoadFromFile('c:\agrigest\informes\JORNALESGENERAL.fr3'); // informes.Report.FileName:=dm.qnominasdetalle.asstring; informes.ShowReport(); informes.Clear end; procedure TBASE.btJmodificarClick(Sender: TObject); var totaljornal: real; begin tjornales.Locate('id', dm.qnominasdetalleid.AsInteger, [locaseinsensitive, lopartialkey]); tjornales.edit; dm.qparcelas.Open; dm.qtrabajos.Open; dm.qtipohoras.Open; fechajornales.Datetime := tjornalesfecha.AsDateTime; ljcentro.Enabled := true; lnobservaciones.Enabled:=true; ljcentro.KeyValue := tjornalesparcela.AsString; ljtrabajo.Enabled := true; ljtrabajo.KeyValue := tjornalestypework.AsString; ljhora.Enabled := true; ljhora.KeyValue := tjornalesarticulo.AsString; edjhoras.Enabled := true; edjhoras.Text := tjornalesqhoras.AsString; edjprecio.Text := tjornalesprecio.AsString; fechajornales.Enabled := true; PdatosJornales.Enabled := true; btJnuevo.Enabled := false; btJmodificar.Enabled := false; btJguardar.Enabled := true; btJcancelar.Enabled := true; btJborrar.Enabled := false; end; procedure TBASE.btJnuevoClick(Sender: TObject); begin dmestadisticas.qcampanyas.Open; dm.qparcelas.Open; dm.qtrabajos.Open; dm.qtipohoras.Open; // fechajornales.Date:=date; ljcentro.Enabled := true; ljtrabajo.Enabled := true; ljhora.Enabled := true; edjhoras.Enabled := true; lnobservaciones.Enabled:=true; lnobservaciones.Text:=''; fechajornales.Enabled := true; PdatosJornales.Enabled := true; btJnuevo.Enabled := false; btJmodificar.Enabled := false; btJguardar.Enabled := true; btJcancelar.Enabled := true; btJborrar.Enabled := false; end; procedure TBASE.Button9Click(Sender: TObject); begin informedb.DataSource := dm.dsqlistadotrabajos; informes.Report.Clear; if listainformes2.ItemIndex = 0 then informes.LoadFromFile('c:\agrigest\informes\listadotrabajosvalorado.fr3'); if listainformes2.ItemIndex = 1 then informes.LoadFromFile('c:\agrigest\informes\listadotrabajos.fr3'); informes.Variables.Variables['TITULO'] := QUOTEDSTR('LISTADO DE TRABAJOS DESDE EL ' + datetostr(nomlttdesde.Date) + ' HASTA EL ' + datetostr(nomltthasta.Date)); informes.ShowReport(); end; procedure TBASE.btvalorarClick(Sender: TObject); var anyo, mes, dia, anyo2, mes2, dia2: word; filtro, fdesde, fhasta, fdesde2, fhasta2, falta, iban, textor: string; diaslaborables, maximodias, diascomputables, diascalculo, condiciones: Integer; irpf, desempleo, formacion, contingencias, salariobase, anticipos, indemnizacion, penalizacion: real; begin condiciones := 0; if CheckBox2.Checked then begin condiciones := condiciones + 1; end; if CheckBox3.Checked then begin condiciones := condiciones + 1; end; if CheckBox4.Checked then begin condiciones := condiciones + 1; end; if CheckBox5.Checked then begin condiciones := condiciones + 1; end; dm.ttrabajadores.Open; dm.tempresa.Open; salariobase := dm.tempresasalariobasedia.AsFloat;; filtro := ''; decodedate(nomfechadesde.Date, anyo, mes, dia); fdesde := floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia); filtro := ' where estado<>' + '''' + 'P' + '''' + ' and estado<>' + '''' + 'S' + '''' + ' and fecha>=' + '''' + fdesde + ''''; decodedate(nomfechahasta.Date, anyo, mes, dia); fhasta := floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia); filtro := filtro + ' and fecha<=' + '''' + fhasta + ''''; if CheckBox6.Checked then begin filtro := filtro + ' and articulo in (select codart from articulos where facturar=0)'; end else filtro := filtro + ' and articulo in (select codart from articulos where facturar=1)'; if condiciones >= 1 then filtro := filtro + ' and (('; if CheckBox2.Checked then begin filtro := filtro + ' idt in (select id from trabajadores where regimen_cot=' + '''' + 'GENERAL' + '''' + ')'; condiciones := condiciones - 1; if condiciones = 0 then filtro := filtro + ' ))' else filtro := filtro + ') or ('; end; if CheckBox3.Checked then begin filtro := filtro + ' idt in (select id from trabajadores where regimen_cot=' + '''' + 'AGRARIO' + '''' + ')'; condiciones := condiciones - 1; if condiciones = 0 then filtro := filtro + ' ))' else filtro := filtro + ') or ('; end; if CheckBox4.Checked then begin filtro := filtro + ' idt in (select id from trabajadores where pagarporbanco=0)'; condiciones := condiciones - 1; if condiciones = 0 then filtro := filtro + ' ))' else filtro := filtro + ') or ('; end; if CheckBox5.Checked then begin filtro := filtro + ' idt in (select id from trabajadores where pagarporbanco=1)'; condiciones := condiciones - 1; if condiciones = 0 then filtro := filtro + ' ))' else filtro := filtro + ') or ('; end; filtro := filtro + ' group by idt order by trabajador asc,fecha asc'; dm.tprenominas.Close; dm.qaux1.Close; dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add('delete from prenominas'); dm.qaux1.ExecSQL; dm.qaux1.Close; dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add ('update trabajo_diario td set precio=(select precio from articulos a where a.codart=td.articulo) where estado<>' + '''' + 'P' + ''''); dm.qaux1.ExecSQL; dm.qaux1.Close; dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add ('update trabajo_diario td set total=precio*qhoras where estado<>' + '''' + 'P' + ''''); dm.qaux1.ExecSQL; dm.qaux1.Close; dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add('delete from prenominas'); dm.qaux1.ExecSQL; dm.tprenominas.Open; dm.qaux1.Close; dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add ('select count(*) from calendario_laboral where festivo=0 and fecha>=' + '''' + fdesde + '''' + ' and fecha<=' + '''' + fhasta + ''''); dm.qaux1.Open; diaslaborables := dm.qaux1.Fields[0].AsInteger; dm.qaux1.Close; dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add ('select idt,trabajador,sum(qhoras) as horas,sum(total) as total from trabajo_diario ' + filtro); // dm.qaux1.SQL.Add('where articulo in (select codart from articulos where facturar=1) and estado='+''''+'C'+''''); // dm.qaux1.SQL.Add(' and fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''+' group by idt order by idt'); dm.qaux1.Open; if dm.qaux1.RecordCount >= 1 then begin while not(dm.qaux1.Eof) do begin dm.ttrabajadores.Locate('id', dm.qaux1.Fields[0].AsInteger, [locaseinsensitive]); irpf := dm.ttrabajadoresirpf.AsFloat; desempleo := dm.ttrabajadoresdesempleo.AsFloat; formacion := dm.ttrabajadoresformacion.AsFloat; contingencias := dm.ttrabajadorescontingencias.AsFloat; if nomfechadesde.Date >= dm.ttrabajadoresfechaalta.AsDateTime then begin decodedate(nomfechadesde.Date, anyo2, mes2, dia2); fdesde2 := floattostr(anyo2) + '-' + floattostr(mes2) + '-' + floattostr(dia2); end else begin decodedate(dm.ttrabajadoresfechaalta.AsDateTime, anyo2, mes2, dia2); fdesde2 := floattostr(anyo2) + '-' + floattostr(mes2) + '-' + floattostr(dia2); end; if dm.ttrabajadoresFECHABAJA.AsString = '' then begin fhasta2 := fhasta; end else begin decodedate(dm.ttrabajadoresFECHABAJA.AsDateTime, anyo2, mes2, dia2); fhasta2 := floattostr(anyo2) + '-' + floattostr(mes2) + '-' + floattostr(dia2); end; dm.qaux3.Close; dm.qaux3.SQL.Clear; dm.qaux3.SQL.Add ('select count(*) from calendario_laboral where festivo=0 and fecha>=' + '''' + fdesde2 + '''' + ' and fecha<=' + '''' + fhasta2 + ''''); dm.qaux3.Open; diascomputables := dm.qaux3.Fields[0].AsInteger; dm.qaux3.Close; dm.qaux3.SQL.Clear; dm.qaux3.SQL.Add('select sum(importe) from anticipos where idt=' + dm.qaux1.Fields[0].AsString + ' and fecha>=' + '''' + fdesde + '''' + ' and fecha<=' + '''' + fhasta + ''''); dm.qaux3.Open; anticipos := dm.qaux3.Fields[0].AsFloat; dm.qaux3.Close; dm.qaux3.SQL.Clear; dm.qaux3.SQL.Add('select sum(indemnizacion) from anticipos where idt=' + dm.qaux1.Fields[0].AsString + ' and fecha>=' + '''' + fdesde + '''' + ' and fecha<=' + '''' + fhasta + ''''); dm.qaux3.Open; indemnizacion := dm.qaux3.Fields[0].AsFloat; dm.qaux3.Close; dm.qaux3.SQL.Clear; dm.qaux3.SQL.Add('select sum(penalizacion) from anticipos where idt=' + dm.qaux1.Fields[0].AsString + ' and fecha>=' + '''' + fdesde + '''' + ' and fecha<=' + '''' + fhasta + ''''); dm.qaux3.Open; penalizacion := dm.qaux3.Fields[0].AsFloat; if diaslaborables <= diascomputables then maximodias := diaslaborables else maximodias := diascomputables; if Trunc(dm.qaux1.Fields[3].AsFloat / dm.tempresasalariobasedia.AsFloat) < maximodias then diascalculo := Trunc(dm.qaux1.Fields[3].AsFloat / dm.tempresasalariobasedia.AsFloat) else diascalculo := maximodias; dm.tprenominas.Append; dm.tprenominasIDT.Value := dm.ttrabajadoresID.AsInteger; dm.tprenominasanyo.Value := anyo; dm.tprenominasmes.Value := floattostr(mes); dm.tprenominasnif.Value := dm.ttrabajadoresNIF.AsString; dm.tprenominasnombre.Value := dm.ttrabajadoresnombre.AsString; dm.tprenominasdireccion.Value := dm.ttrabajadoresdireccion.AsString; dm.tprenominascp.Value := dm.ttrabajadorescp.AsString; dm.tprenominaspoblacion.Value := dm.ttrabajadorespoblacion.AsString; dm.tprenominashoras.Value := dm.qaux1.Fields[2].AsFloat; dm.tprenominasfechaalta.Value := dm.ttrabajadoresfechaalta.AsDateTime; if dm.ttrabajadoresFECHABAJA.AsString <> '' then begin dm.tprenominasfechabaja.Value := dm.ttrabajadoresFECHABAJA.AsDateTime; // strtodate(fhasta2); end; dm.tprenominasdiastrabajados.Value := Trunc(dm.qaux1.Fields[3].AsFloat / dm.tempresasalariobasedia.AsFloat); dm.tprenominasdiasmaximo.Value := maximodias; dm.tprenominasdiascalculo.Value := diascalculo; dm.tprenominastotalbruto.Value := strtofloat(FormatFloat('0.00', dm.qaux1.Fields[3].AsFloat)); dm.tprenominasIRPF.Value := irpf; dm.tprenominastotalirpf.Value := strtofloat(FormatFloat('0.00', (irpf / 100) * dm.tprenominastotalbruto.AsFloat)); // (salariobase*diascalculo); dm.tprenominasdesempleo.Value := desempleo; dm.tprenominastotaldesempleo.Value := strtofloat(FormatFloat('0.00', (desempleo / 100) * (dm.tprenominastotalbruto.AsFloat - indemnizacion))); // (salariobase*diascalculo); dm.tprenominasformacion.Value := formacion; dm.tprenominastotalformacion.Value := strtofloat(FormatFloat('0.00', (formacion / 100) * (dm.tprenominastotalbruto.AsFloat - indemnizacion))); // (salariobase*diascalculo); dm.tprenominascontingencias.Value := contingencias; dm.tprenominastotalcontingencias.Value := strtofloat(FormatFloat('0.00', (contingencias / 100) * (dm.tprenominastotalbruto.AsFloat - indemnizacion))); // (salariobase*diascalculo); dm.tprenominastotalneto.Value := strtofloat(FormatFloat('0.00', dm.qaux1.Fields[3].AsFloat - dm.tprenominastotalirpf.AsFloat - dm.tprenominastotaldesempleo.AsFloat - dm.tprenominastotalformacion.AsFloat - dm.tprenominastotalcontingencias.AsFloat - penalizacion)); dm.tprenominasanticipos.Value := strtofloat(FormatFloat('0.00', anticipos)); dm.tprenominasindemnizacion.Value := strtofloat(FormatFloat('0.00', indemnizacion)); dm.tprenominaspenalizacion.Value := strtofloat(FormatFloat('0.00', penalizacion)); dm.tprenominasTOTALAPAGAR.Value := strtofloat(FormatFloat('0.00', dm.tprenominastotalneto.AsFloat - dm.tprenominasanticipos.AsFloat)); dm.tprenominascuentapago.Value := dm.ttrabajadoresCBIBAN.AsString + dm.ttrabajadoresCBBANCO.AsString + dm.ttrabajadoresCBOFICINA.AsString + dm.ttrabajadoresCBDC.AsString + dm.ttrabajadoresCBCC.AsString; dm.tprenominasfechapago.Value := Date; dm.tprenominasestado.Value := 'S'; dm.tprenominassalariobase.Value := salariobase; dm.tprenominasdiaslaborables.Value := diaslaborables; dm.tprenominascorrecto.Value := 0; dm.tprenominasfechainicio.Value := nomfechadesde.Date; dm.tprenominasfechafin.Value := nomfechahasta.Date; dm.tprenominas.post; condiciones := 0; if CheckBox2.Checked then begin condiciones := condiciones + 1; end; if CheckBox3.Checked then begin condiciones := condiciones + 1; end; if CheckBox4.Checked then begin condiciones := condiciones + 1; end; if CheckBox5.Checked then begin condiciones := condiciones + 1; end; filtro := ''; decodedate(nomfechadesde.Date, anyo, mes, dia); fdesde := floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia); filtro := ' where estado<>' + '''' + 'S' + '''' + ' and estado<>' + '''' + 'P' + '''' + ' and fecha>=' + '''' + fdesde + ''''; decodedate(nomfechahasta.Date, anyo, mes, dia); fhasta := floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia); filtro := filtro + ' and fecha<=' + '''' + fhasta + ''''; if CheckBox6.Checked then begin filtro := filtro + ' and articulo in (select codart from articulos where facturar=0)'; end else filtro := filtro + ' and articulo in (select codart from articulos where facturar=1)'; if condiciones >= 1 then filtro := filtro + ' and (('; if CheckBox2.Checked then begin filtro := filtro + ' idt in (select id from trabajadores where regimen_cot=' + '''' + 'GENERAL' + '''' + ')'; condiciones := condiciones - 1; if condiciones = 0 then filtro := filtro + ' ))' else filtro := filtro + ') or ('; end; if CheckBox3.Checked then begin filtro := filtro + ' idt in (select id from trabajadores where regimen_cot=' + '''' + 'AGRARIO' + '''' + ')'; condiciones := condiciones - 1; if condiciones = 0 then filtro := filtro + ' ))' else filtro := filtro + ') or ('; end; if CheckBox4.Checked then begin filtro := filtro + ' idt in (select id from trabajadores where pagarporbanco=0)'; condiciones := condiciones - 1; if condiciones = 0 then filtro := filtro + ' ))' else filtro := filtro + ') or ('; end; if CheckBox5.Checked then begin filtro := filtro + ' idt in (select id from trabajadores where pagarporbanco=1)'; condiciones := condiciones - 1; if condiciones = 0 then filtro := filtro + ' ))' else filtro := filtro + ') or ('; end; dm.qaux3.Close; dm.qaux3.SQL.Clear; dm.qaux3.SQL.Add('update trabajo_diario set estado=' + '''' + 'V' + '''' + ',control=' + dm.tprenominasid.AsString + ' ' + filtro + ' and idt=' + dm.ttrabajadoresID.AsString); dm.qaux3.ExecSQL; dm.qaux1.Next; end; end; end; procedure TBASE.btVerdocumentosClick(Sender: TObject); begin if btVerdocumentos.Caption = 'Ver documentos' then begin Paneldocumentos.Visible := true; { dmtr.documentos.close; dmtr.documentos.filter:='ide='+dmtr.qlotesidempresa.asstring+' and idlote='+dmtr.qlotesid.AsString; dmtr.documentos.open; } btVerdocumentos.Caption := 'Ocultar Doc.'; end else begin // dmtr.documentos.close; Paneldocumentos.Visible := false; // dmtr.documentos.Filter:='id=-1 and idlote=-1'; // dmtr.documentos.open; btVerdocumentos.Caption := 'Ver documentos'; end; end; procedure TBASE.Vaciar2Click(Sender: TObject); begin DBEdit3.Text := ''; end; procedure TBASE.baceptarempleadosClick(Sender: TObject); var tid: string; begin tid := templeadosID.AsString; if templeados.State in [dsedit, dsinsert] then templeados.post; qempleados.Refresh; qempleados.Locate('id', tid, [locaseinsensitive]); baceptarempleados.Visible := false; bcancelarempleados.Visible := false; Vaciar.Visible := false; Vaciar2.Visible := false; end; procedure TBASE.Balancedeventas1Click(Sender: TObject); begin balanceventas := Tbalanceventas.Create(nil); try balanceventas.ShowModal(); finally balanceventas.Free; end; end; procedure TBASE.bcancelarempleadosClick(Sender: TObject); begin if templeados.State in [dsedit, dsinsert] then templeados.cancel; baceptarempleados.Visible := false; bcancelarempleados.Visible := false; Vaciar.Visible := false; Vaciar2.Visible := false; end; procedure TBASE.bcancelarjornalClick(Sender: TObject); begin if tjornales.State in [dsedit, dsinsert] then begin tjornales.cancel; qjornales.Refresh; qjornales.First; bmodificarjornales.Enabled := true; bborrarjornales.Enabled := true; baceptar.Enabled := false; bcancelarjornal.Enabled := false; btinsertar.Enabled := true; tfechajornal.Enabled := false; lparcela.Enabled := false; ltrabajo.Enabled := false; ltipohora.Enabled := false; thoras.Enabled := false; lprecio.Enabled := false; end; end; procedure TBASE.bcborrarClick(Sender: TObject); begin dm.qcampanyas.Delete; dm.qcampanyas.Refresh; dm.qcampanyas.First end; procedure TBASE.bccaceptarClick(Sender: TObject); begin dm.qparcelas.post; end; procedure TBASE.bccanadirClick(Sender: TObject); begin dm.qparcelas.Append; DBEdit79.SetFocus; end; procedure TBASE.bccancelarClick(Sender: TObject); begin dm.qcampanyas.cancel; dm.qcampanyas.Refresh; end; procedure TBASE.bccborrarClick(Sender: TObject); begin dm.qparcelas.Delete; dm.qparcelas.Refresh; dm.qparcelas.First end; procedure TBASE.bcccancelarClick(Sender: TObject); begin dm.qparcelas.cancel; dm.qparcelas.Refresh; end; procedure TBASE.bccmodificarClick(Sender: TObject); begin dm.qparcelas.edit; DBEdit79.SetFocus; end; procedure TBASE.bcmodificarClick(Sender: TObject); begin dm.qcampanyas.edit; DBEdit89.SetFocus; bcanadir.Enabled := false; bcmodificar.Enabled := false; bcborrar.Enabled := false; bccancelar.Enabled := true; bcaceptar.Enabled := true; end; procedure TBASE.beaceptarClick(Sender: TObject); begin Panel150.Enabled := false; dm.tempresa.post; beanadir.Enabled := true; bemodificar.Enabled := true; beborrar.Enabled := true; becancelar.Enabled := false; beaceptar.Enabled := false; end; procedure TBASE.beanadirClick(Sender: TObject); begin Panel50.Enabled := true; dm.tempresa.Append; EmpActiva.Checked := true; DBEdit40.SetFocus; beanadir.Enabled := false; bemodificar.Enabled := false; beborrar.Enabled := false; becancelar.Enabled := true; beaceptar.Enabled := true; end; procedure TBASE.beborrarClick(Sender: TObject); begin dm.tempresa.Delete; dm.tempresa.Refresh; dm.tempresa.First end; procedure TBASE.becancelarClick(Sender: TObject); begin Panel150.Enabled := false; dm.tempresa.cancel; dm.tempresa.Refresh; beanadir.Enabled := true; bemodificar.Enabled := true; beborrar.Enabled := true; becancelar.Enabled := false; beaceptar.Enabled := false; end; procedure TBASE.bemodificarClick(Sender: TObject); begin Panel150.Enabled := true; dm.tempresa.edit; // dbedit40.SetFocus; beanadir.Enabled := false; bemodificar.Enabled := false; beborrar.Enabled := false; becancelar.Enabled := true; beaceptar.Enabled := true; end; procedure TBASE.baceptarClick(Sender: TObject); var totaljornal: real; begin if dsjornales.State in [dsinsert] then begin qaux.Close; qaux.SQL.Clear; qaux.SQL.Add('select max(id)+1 from trabajo_diario'); qaux.Open; tjornalesid.Value := qaux.Fields[0].AsInteger; tjornalesfecha.Value := tfechajornal.Date; tjornalesparcela.Value := lparcela.KeyValue; tjornalesidt.Value := qempleadosid.AsInteger; tjornalestrabajador.Value := qempleadosnombre.AsString; tjornalestypework.Value := ltrabajo.KeyValue; tjornalesarticulo.Value := ltipohora.KeyValue; tjornalesqhoras.Value := strtofloat(thoras.Text); tjornalesprecio.Value := strtofloat(lprecio.Text); totaljornal := strtofloat(thoras.Text) * strtofloat(lprecio.Text); tjornalestotal.Value := strtofloat(FormatFloat('0.00', totaljornal)); tjornalesestado.Value := 'C'; tjornales.post; qjornales.Refresh; qjornales.First; bmodificarjornales.Enabled := true; bborrarjornales.Enabled := true; baceptar.Enabled := false; bcancelarjornal.Enabled := false; btinsertar.Enabled := true; tfechajornal.Enabled := false; lparcela.Enabled := false; ltrabajo.Enabled := false; ltipohora.Enabled := false; thoras.Enabled := false; lprecio.Enabled := false; end; if dsjornales.State = dsedit then begin tjornalesfecha.Value := tfechajornal.Date; tjornalesparcela.Value := lparcela.KeyValue; tjornalestypework.Value := ltrabajo.KeyValue; tjornalesarticulo.Value := ltipohora.KeyValue; tjornalesqhoras.Value := strtofloat(thoras.Text); tjornalesprecio.Value := strtofloat(lprecio.Text); totaljornal := strtofloat(thoras.Text) * strtofloat(lprecio.Text); tjornalestotal.Value := strtofloat(FormatFloat('0.00', totaljornal)); tjornalesestado.Value := 'C'; tjornales.post; qjornales.Refresh; qjornales.First; bmodificarjornales.Enabled := true; bborrarjornales.Enabled := true; baceptar.Enabled := false; btinsertar.Enabled := true; tfechajornal.Enabled := false; lparcela.Enabled := false; ltrabajo.Enabled := false; ltipohora.Enabled := false; thoras.Enabled := false; lprecio.Enabled := false; end; end; procedure TBASE.baborrarClick(Sender: TObject); begin dm.talmacenes.Delete; dm.qalmacenes.Refresh; dm.qalmacenes.First end; procedure TBASE.bacancelarClick(Sender: TObject); begin dm.talmacenes.cancel; dm.qalmacenes.Open; baanadir.Enabled := true; bamodificar.Enabled := true; baborrar.Enabled := true; bacancelar.Enabled := false; baaceptar.Enabled := false; end; procedure TBASE.nomlhdesdeChange(Sender: TObject); var fdesde, fhasta, filtro, filtro2, filtro3: string; anyo, mes, dia: word; begin filtro := ''; filtro2 := ''; filtro3 := ''; decodedate(nomlhdesde.Date, anyo, mes, dia); fdesde := floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia); filtro := ' where codart in (select distinct(articulo) from trabajo_diario where fecha>=' + '''' + fdesde + ''''; filtro2 := ' where id in (select distinct(idt) from trabajo_diario td,articulos a, parcelas p where td.parcela=p.codpar and p.seleccionado=1 and td.articulo=a.codart and a.seleccionado=1 and fecha>=' + '''' + fdesde + ''''; filtro3 := ' where td.parcela=p.codpar and p.seleccionado=1 and td.idt=t.id and td.articulo=a.codart and a.seleccionado=1 and t.seleccionado=1 and fecha>=' + '''' + fdesde + ''''; decodedate(nomlhhasta.Date, anyo, mes, dia); fhasta := floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia); filtro := filtro + ' and fecha<=' + '''' + fhasta + ''''; filtro := filtro + ') order by codart'; filtro2 := filtro2 + ' and fecha<=' + '''' + fhasta + ''''; filtro2 := filtro2 + ') order by nombre'; filtro3 := filtro3 + ' and fecha<=' + '''' + fhasta + ''''; filtro3 := filtro3 + ' group by idt,trabajador,articulo order by articulo,trabajador'; dm.qtipohoras2.Close; dm.qtipohoras2.SQL.Clear; dm.qtipohoras2.SQL.Add('select codart,seleccionado from articulos ' + filtro); dm.qtipohoras2.Open; dm.qtrabajadores2.Close; dm.qtrabajadores2.SQL.Clear; dm.qtrabajadores2.SQL.Add('select id,nombre,seleccionado from trabajadores ' + filtro2); dm.qtrabajadores2.Open; dm.qlistadohoras.Close; dm.qlistadohoras.SQL.Clear; dm.qlistadohoras.SQL.Add ('select idt,trabajador,articulo,sum(qhoras) as horas,sum(qhoras*a.equivalenciahoras) as horas2,sum(qhoras*td.precio) as total,sum(qhoras*a.equivalenciahoras*td.precio) as total2 '); dm.qlistadohoras.SQL.Add ('from trabajo_diario td,articulos a,trabajadores t,parcelas p ' + filtro3); dm.qlistadohoras.Open; end; procedure TBASE.nomlttdesdeChange(Sender: TObject); var fdesde, fhasta, filtro, filtro2, filtro3: string; anyo, mes, dia: word; begin filtro := ''; filtro2 := ''; filtro3 := ''; decodedate(nomlttdesde.Date, anyo, mes, dia); fdesde := floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia); filtro := ' where id in (select distinct(typework) from trabajo_diario where fecha>=' + '''' + fdesde + ''''; filtro2 := ' where id in (select distinct(idt) from trabajo_diario td,tipo_trabajo a where td.typework=a.id and a.seleccionado=1 and fecha>=' + '''' + fdesde + ''''; filtro3 := ' where td.idt=t.id and td.typework=a.id and a.seleccionado=1 and t.seleccionado=1 and fecha>=' + '''' + fdesde + ''''; decodedate(nomltthasta.Date, anyo, mes, dia); fhasta := floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia); filtro := filtro + ' and fecha<=' + '''' + fhasta + ''''; filtro := filtro + ') order by id'; filtro2 := filtro2 + ' and fecha<=' + '''' + fhasta + ''''; filtro2 := filtro2 + ') order by nombre'; filtro3 := filtro3 + ' and fecha<=' + '''' + fhasta + ''''; filtro3 := filtro3 + ' group by idt,trabajador,typework order by typework,trabajador'; dm.qtipotrabajo2.Close; dm.qtipotrabajo2.SQL.Clear; dm.qtipotrabajo2.SQL.Add('select id,seleccionado from tipo_trabajo ' + filtro); dm.qtipotrabajo2.Open; dm.qtrabajadores3.Close; dm.qtrabajadores3.SQL.Clear; dm.qtrabajadores3.SQL.Add('select id,nombre,seleccionado from trabajadores ' + filtro2); dm.qtrabajadores3.Open; dm.qlistadotrabajos.Close; dm.qlistadotrabajos.SQL.Clear; dm.qlistadotrabajos.SQL.Add ('select idt,trabajador,typework,sum(qhoras) as horas,sum(qhoras*td.precio) as total from trabajo_diario td,tipo_trabajo a,trabajadores t ' + filtro3); dm.qlistadotrabajos.Open; end; procedure TBASE.nomltthastaChange(Sender: TObject); var fdesde, fhasta, filtro, filtro2, filtro3: string; anyo, mes, dia: word; begin filtro := ''; filtro2 := ''; filtro3 := ''; decodedate(nomlttdesde.Date, anyo, mes, dia); fdesde := floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia); filtro := ' where id in (select distinct(typework) from trabajo_diario where fecha>=' + '''' + fdesde + ''''; filtro2 := ' where id in (select distinct(idt) from trabajo_diario td,tipo_trabajo a where td.typework=a.id and a.seleccionado=1 and fecha>=' + '''' + fdesde + ''''; filtro3 := ' where td.idt=t.id and td.typework=a.id and a.seleccionado=1 and t.seleccionado=1 and fecha>=' + '''' + fdesde + ''''; decodedate(nomltthasta.Date, anyo, mes, dia); fhasta := floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia); filtro := filtro + ' and fecha<=' + '''' + fhasta + ''''; filtro := filtro + ') order by id'; filtro2 := filtro2 + ' and fecha<=' + '''' + fhasta + ''''; filtro2 := filtro2 + ') order by nombre'; filtro3 := filtro3 + ' and fecha<=' + '''' + fhasta + ''''; filtro3 := filtro3 + ' group by idt,trabajador,typework order by typework,trabajador'; dm.qtipotrabajo2.Close; dm.qtipotrabajo2.SQL.Clear; dm.qtipotrabajo2.SQL.Add('select id,seleccionado from tipo_trabajo ' + filtro); dm.qtipotrabajo2.Open; dm.qtrabajadores3.Close; dm.qtrabajadores3.SQL.Clear; dm.qtrabajadores3.SQL.Add('select id,nombre,seleccionado from trabajadores ' + filtro2); dm.qtrabajadores3.Open; dm.qlistadotrabajos.Close; dm.qlistadotrabajos.SQL.Clear; dm.qlistadotrabajos.SQL.Add ('select idt,trabajador,typework,sum(qhoras) as horas,sum(qhoras*td.precio) as total from trabajo_diario td,tipo_trabajo a,trabajadores t ' + filtro3); dm.qlistadotrabajos.Open; end; procedure TBASE.fechaloteCloseUp(Sender: TObject); begin dmtr.qlotesfecha.Value := fechalote.Date; end; procedure TBASE.fechaloteEnter(Sender: TObject); begin fechalote.Date := Date; end; procedure TBASE.DBCheckBox13MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if dm.tcalendario_laboral.State in [dsedit] then dm.tcalendario_laboral.post; end; procedure TBASE.DBCheckBox14MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if dm.tcalendario_laboral.State in [dsedit] then dm.tcalendario_laboral.post; end; procedure TBASE.DBCheckBox15MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if dmproduccion.qcalendario_laboral.State in [dsedit] then dmproduccion.qcalendario_laboral.post; end; procedure TBASE.DBCheckBox16MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if dmproduccion.qcalendario_laboral.State in [dsedit] then dmproduccion.qcalendario_laboral.post; end; procedure TBASE.DBEdit116Enter(Sender: TObject); var numdia, numanyo: Integer; anyo, mes, dia: word; begin decodedate(strtodate(lfecha.Text), anyo, mes, dia); numdia := dayoftheyear(strtodate(lfecha.Text)); numanyo := anyo - 2000; if dmtr.qlotes.State in [dsedit, dsinsert] then begin dmtr.qlotestrazabilidad.Value := qparcelas2numero.AsString + inttostr(numdia) + inttostr(numanyo); end else begin dmtr.qlotes.edit; dmtr.qlotestrazabilidad.Value := qparcelas2numero.AsString + inttostr(numdia) + inttostr(numanyo); end end; procedure TBASE.DBEdit145Exit(Sender: TObject); begin if dmproduccion.qpartesdiarios.State in [dsedit] then dmproduccion.qpartesdiarios.post; end; procedure TBASE.DBEdit27Exit(Sender: TObject); begin DBEdit2.Text := DBEdit8.Text + ' ' + DBEdit27.Text; end; procedure TBASE.DBEdit8Exit(Sender: TObject); begin DBEdit2.Text := DBEdit8.Text + ' ' + DBEdit27.Text; end; procedure TBASE.DBEdit9Exit(Sender: TObject); begin if (not EsNif(DBEdit9.Text)) and (not EsCif(DBEdit9.Text)) then showmessage('¡¡¡ EL NIF INTRODUCIDO ES ERRONEO ¡¡¡'); end; procedure TBASE.DBGrid19DblClick(Sender: TObject); begin if (dm.qnominasproduccionestado.AsString = 'C') OR (dm.qnominasproduccionestado.AsString = 'S') then BEGIN if dm.qnominasproduccionestado.AsString = 'C' then begin tjornales.Locate('id', dm.qnominasproduccionid.AsString, [locaseinsensitive]); tjornales.edit; tjornalesestado.Value := 'S'; tjornales.post; dm.qnominasproduccion.Refresh; dm.qnominasproduccion.Locate('id', tjornalesid.AsString, [locaseinsensitive]); end ELSE begin tjornales.Locate('id', dm.qnominasproduccionid.AsString, [locaseinsensitive]); tjornales.edit; tjornalesestado.Value := 'C'; tjornales.post; dm.qnominasproduccion.Refresh; dm.qnominasproduccion.Locate('id', tjornalesid.AsString, [locaseinsensitive]); end; END; end; procedure TBASE.DBGrid19DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if dm.qnominasproduccionestado.AsString = 'C' then begin DBGrid19.Canvas.brush.Color := amarillo; end; if dm.qnominasproduccionestado.AsString = 'S' then begin DBGrid19.Canvas.brush.Color := rojo; end; if dm.qnominasproduccionestado.AsString = 'V' then begin DBGrid19.Canvas.brush.Color := azul; end; if dm.qnominasproduccionestado.AsString = 'P' then begin DBGrid19.Canvas.brush.Color := verde; end; DBGrid19.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure TBASE.DBGrid1CellClick(Column: TColumn); var i: TBookmark; begin if qempleadosseleccionado.AsInteger = 1 then begin i := qempleados.GetBookmark; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=0 where id=' + qempleadosid.AsString); qaux.ExecSQL; qempleados.Refresh; qempleados.GotoBookmark((i)); end ELSE begin i := qempleados.GetBookmark; qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=1 where id=' + qempleadosid.AsString); qaux.ExecSQL; qempleados.Refresh; qempleados.GotoBookmark((i)); end end; procedure TBASE.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if qempleadosseleccionado.AsInteger = 1 then begin DBGrid1.Canvas.brush.Color := verde; end; if qempleadosseleccionado.AsInteger = 0 then begin DBGrid1.Canvas.brush.Color := clWindow; end; DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure TBASE.DBGrid1TitleClick(Column: TColumn); var st: ZAbstractRODataset.TSortType; begin st := qempleados.SortType; qempleados.SortedFields := Column.FieldName; If st = stascending then qempleados.SortType := stDescending else qempleados.SortType := stascending; dsqtrabajadores.DataSet.First; end; procedure TBASE.DBGrid21Exit(Sender: TObject); begin if dmproduccion.qrestos_dia.State in [dsedit] then begin dmproduccion.qrestos_dia.post; end; end; procedure TBASE.DBGrid25CellClick(Column: TColumn); begin if (dm.qtrabajadores2seleccionado.AsInteger = 0) OR (dm.qtrabajadores2seleccionado.AsInteger = 1) then BEGIN if dm.qtrabajadores2seleccionado.AsInteger = 0 then begin dm.qtrabajadores2.edit; dm.qtrabajadores2seleccionado.Value := 1; dm.qtrabajadores2.post; dm.qtrabajadores2.Refresh; end else begin dm.qtrabajadores2.edit; dm.qtrabajadores2seleccionado.Value := 0; dm.qtrabajadores2.post; dm.qtrabajadores2.Refresh; end; END; end; procedure TBASE.DBGrid25DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if dm.qtrabajadores2seleccionado.AsInteger = 0 then begin DBGrid25.Canvas.brush.Color := clwhite; end; if dm.qtrabajadores2seleccionado.AsInteger = 1 then begin DBGrid25.Canvas.brush.Color := verde; end; DBGrid25.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure TBASE.DBGrid26CellClick(Column: TColumn); begin if (dm.qtipohoras2seleccionado.AsInteger = 0) OR (dm.qtipohoras2seleccionado.AsInteger = 1) then BEGIN if dm.qtipohoras2seleccionado.AsInteger = 0 then begin dm.qtipohoras2.edit; dm.qtipohoras2seleccionado.Value := 1; dm.qtipohoras2.post; dm.qtipohoras2.Refresh; end ELSE begin dm.qtipohoras2.edit; dm.qtipohoras2seleccionado.Value := 0; dm.qtipohoras2.post; dm.qtipohoras2.Refresh; end; END; end; procedure TBASE.DBGrid26DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if dm.qtipohoras2seleccionado.AsInteger = 0 then begin DBGrid26.Canvas.brush.Color := clwhite; end; if dm.qtipohoras2seleccionado.AsInteger = 1 then begin DBGrid26.Canvas.brush.Color := verde; end; DBGrid26.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure TBASE.DBGrid28CellClick(Column: TColumn); begin if (dm.qtrabajadores3seleccionado.AsInteger = 0) OR (dm.qtrabajadores3seleccionado.AsInteger = 1) then BEGIN if dm.qtrabajadores3seleccionado.AsInteger = 0 then begin dm.qtrabajadores3.edit; dm.qtrabajadores3seleccionado.Value := 1; dm.qtrabajadores3.post; dm.qtrabajadores3.Refresh; end else begin dm.qtrabajadores3.edit; dm.qtrabajadores3seleccionado.Value := 0; dm.qtrabajadores3.post; dm.qtrabajadores3.Refresh; end; END; end; procedure TBASE.DBGrid28DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if dm.qtrabajadores3seleccionado.AsInteger = 0 then begin DBGrid28.Canvas.brush.Color := clwhite; end; if dm.qtrabajadores3seleccionado.AsInteger = 1 then begin DBGrid28.Canvas.brush.Color := verde; end; DBGrid28.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure TBASE.DBGrid29CellClick(Column: TColumn); begin if (dm.qtipotrabajo2seleccionado.AsInteger = 0) OR (dm.qtipotrabajo2seleccionado.AsInteger = 1) then BEGIN if dm.qtipotrabajo2seleccionado.AsInteger = 0 then begin dm.qtipotrabajo2.edit; dm.qtipotrabajo2seleccionado.Value := 1; dm.qtipotrabajo2.post; dm.qtipotrabajo2.Refresh; end ELSE begin dm.qtipotrabajo2.edit; dm.qtipotrabajo2seleccionado.Value := 0; dm.qtipotrabajo2.post; dm.qtipotrabajo2.Refresh; end; END; end; procedure TBASE.DBGrid29DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if dm.qtipotrabajo2seleccionado.AsInteger = 0 then begin DBGrid29.Canvas.brush.Color := clwhite; end; if dm.qtipotrabajo2seleccionado.AsInteger = 1 then begin DBGrid29.Canvas.brush.Color := verde; end; DBGrid29.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure TBASE.DBGrid2CellClick(Column: TColumn); begin if (qjornalesestado.AsString = 'C') OR (qjornalesestado.AsString = 'S') then BEGIN if qjornalesestado.AsString = 'C' then begin tjornales.Locate('id', qjornalesid.AsString, [locaseinsensitive]); tjornales.edit; tjornalesestado.Value := 'S'; tjornales.post; qjornales.Refresh; qjornales.Locate('id', tjornalesid.AsString, [locaseinsensitive]); end ELSE begin tjornales.Locate('id', qjornalesid.AsString, [locaseinsensitive]); tjornales.edit; tjornalesestado.Value := 'C'; tjornales.post; qjornales.Refresh; qjornales.Locate('id', tjornalesid.AsString, [locaseinsensitive]); end; END; end; procedure TBASE.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 TBASE.DBGrid32CellClick(Column: TColumn); begin if (dm.qparcela2seleccionado.AsInteger = 0) OR (dm.qparcela2seleccionado.AsInteger = 1) then BEGIN if dm.qparcela2seleccionado.AsInteger = 0 then begin dm.qparcela2.edit; dm.qparcela2seleccionado.Value := 1; dm.qparcela2.post; dm.qparcela2.Refresh; end ELSE begin dm.qparcela2.edit; dm.qparcela2seleccionado.Value := 0; dm.qparcela2.post; dm.qparcela2.Refresh; end; END; end; procedure TBASE.DBGrid32DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if dm.qparcela2seleccionado.AsInteger = 0 then begin DBGrid32.Canvas.brush.Color := clwhite; end; if dm.qparcela2seleccionado.AsInteger = 1 then begin DBGrid32.Canvas.brush.Color := verde; end; DBGrid32.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure TBASE.DBGrid33DblClick(Sender: TObject); begin Button18.Click; end; procedure TBASE.DBGrid33DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if dm.qpartes_diariosfestivo.AsInteger = 1 then begin DBGrid33.Canvas.brush.Color := rojo; end; if dm.qpartes_diariosvalidado.AsInteger = 1 then begin DBGrid33.Canvas.brush.Color := verde; end; DBGrid33.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure TBASE.DBGrid36DblClick(Sender: TObject); begin mostrarpesadas(dmtr.qsalidasid.AsString); { fpesadas := Tfpesadas.Create(nil); try fpesadas.desdefuera:=1; if fpesadas.qpesadas.Active = false then begin fpesadas.qpesadas.Open; fpesadas.qlotes.open; end; fpesadas.Edit1.Text := dmtr.qsalidasid.AsString; fpesadas.btbuscar.Click; fpesadas.ShowModal; fpesadas.desdefuera:=0; finally fpesadas.Free; end; } end; procedure Tbase.MostrarPesadas(const idPesada: string); var fpesadas: Tfpesadas; begin fpesadas := Tfpesadas.Create(nil); with fpesadas do begin try qpesadas.Open; qlotes.open; qenvases.Open; qformatos.Open; qcalidad.Open; qpalets.open; qmprimas.Open; qalmacenes.Open; qtipohora.Open; Edit1.Text := idPesada; btbuscar.Click; ShowModal; finally Free; end; end; end; procedure TBASE.DBGrid38DblClick(Sender: TObject); begin mostrarpesadas(dmtr.qea_pesadasid.AsString); { fpesadas := Tfpesadas.Create(nil); try fpesadas.desdefuera:=1; if fpesadas.qpesadas.Active = false then begin fpesadas.qpesadas.Open; fpesadas.qlotes.open; end; fpesadas.Edit1.Text := ; fpesadas.btbuscar.Click; fpesadas.ShowModal; fpesadas.desdefuera:=0; finally fpesadas.Free; end;} end; procedure TBASE.DBGrid3CellClick(Column: TColumn); var tid: string; begin tid := dm.qanticiposid.AsString; fechaanticipo.Date := dm.qanticiposfecha.AsDateTime; limporteanticipo.Text := dm.qanticiposimporte.AsString; if (dm.qanticiposestado.AsString = 'C') OR (dm.qanticiposestado.AsString = 'S') then BEGIN if dm.qanticiposestado.AsString = 'C' then begin dm.tanticipos.Locate('id', dm.qanticiposid.AsString, [locaseinsensitive]); dm.tanticipos.edit; dm.tanticiposestado.Value := 'S'; dm.tanticipos.post; dm.qanticipos.Refresh; dm.qanticipos.Locate('id', dm.tanticiposid.AsString, [locaseinsensitive]); end ELSE begin dm.tanticipos.Locate('id', dm.qanticiposid.AsString, [locaseinsensitive]); dm.tanticipos.edit; dm.tanticiposestado.Value := 'C'; dm.tanticipos.post; dm.qanticipos.Refresh; dm.qanticipos.Locate('id', dm.tanticiposid.AsString, [locaseinsensitive]); end; END; end; procedure TBASE.DBGrid3DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if dm.qanticiposestado.AsString = 'C' then begin DBGrid3.Canvas.brush.Color := amarillo; end; if dm.qanticiposestado.AsString = 'S' then begin DBGrid3.Canvas.brush.Color := rojo; end; if dm.qanticiposestado.AsString = 'V' then begin DBGrid3.Canvas.brush.Color := azul; end; if dm.qanticiposestado.AsString = 'P' then begin DBGrid3.Canvas.brush.Color := verde; end; DBGrid3.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure TBASE.DBGrid41DblClick(Sender: TObject); begin mostrarpesadas(dmestadisticas.qdesechosdetallesid.AsString); { fpesadas := Tfpesadas.Create(nil); try if fpesadas.qpesadas.Active = false then fpesadas.qpesadas.Open; fpesadas.Edit1.Text := fpesadas.btbuscar.Click; fpesadas.ShowModal; finally fpesadas.Free; end; } end; procedure TBASE.DBGrid44DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if dmproduccion.qpartesdiariosestado.AsInteger = 0 then begin DBGrid44.Canvas.brush.Color := verde; end; if dmproduccion.qpartesdiariosestado.AsInteger = 1 then begin DBGrid44.Canvas.brush.Color := rojo; end; DBGrid44.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure TBASE.DBGrid46DblClick(Sender: TObject); begin mostrarpesadas(dmproduccion.qproduccion_detallesid.AsString); { fpesadas := Tfpesadas.Create(nil); try if fpesadas.qpesadas.Active = false then fpesadas.qpesadas.Open; fpesadas.Edit1.Text := ; fpesadas.btbuscar.Click; fpesadas.ShowModal; finally fpesadas.Free; end; } end; procedure TBASE.DBGrid4CellClick(Column: TColumn); begin if (dm.qnominasdetalleestado.AsString = 'C') OR (dm.qnominasdetalleestado.AsString = 'S') then BEGIN if dm.qnominasdetalleestado.AsString = 'C' then begin tjornales.Locate('id', dm.qnominasdetalleid.AsString, [locaseinsensitive]); tjornales.edit; tjornalesestado.Value := 'S'; tjornales.post; dm.qnominasdetalle.Refresh; dm.qnominasdetalle.Locate('id', tjornalesid.AsString, [locaseinsensitive]); end ELSE begin tjornales.Locate('id', dm.qnominasdetalleid.AsString, [locaseinsensitive]); tjornales.edit; tjornalesestado.Value := 'C'; tjornales.post; dm.qnominasdetalle.Refresh; dm.qnominasdetalle.Locate('id', tjornalesid.AsString, [locaseinsensitive]); end; END; end; procedure TBASE.DBGrid4DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if dm.qnominasdetalleestado.AsString = 'C' then begin DBGrid4.Canvas.brush.Color := amarillo; end; if dm.qnominasdetalleestado.AsString = 'S' then begin DBGrid4.Canvas.brush.Color := rojo; end; if dm.qnominasdetalleestado.AsString = 'V' then begin DBGrid4.Canvas.brush.Color := azul; end; if dm.qnominasdetalleestado.AsString = 'P' then begin DBGrid4.Canvas.brush.Color := verde; end; DBGrid4.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure TBASE.DBGrid4TitleClick(Column: TColumn); var st: ZAbstractRODataset.TSortType; begin st := dm.qnominasdetalle.SortType; dm.qnominasdetalle.SortedFields := Column.FieldName; If st = stascending then dm.qnominasdetalle.SortType := stDescending else dm.qnominasdetalle.SortType := stascending; dm.dsqnominasdetalle.DataSet.First; end; procedure TBASE.DBGrid55DblClick(Sender: TObject); begin mostrarpesadas(dmestadisticas.qproduccion_almacenid.AsString); { fpesadas := Tfpesadas.Create(nil); try if fpesadas.qpesadas.Active = false then fpesadas.qpesadas.Open; fpesadas.Edit1.Text := ; fpesadas.btbuscar.Click; fpesadas.ShowModal; finally fpesadas.Free; end;} end; procedure TBASE.DBGrid56CellClick(Column: TColumn); begin if Column.Field.FieldName = 'activo' then begin if dm.qseriesactivo.AsInteger = 1 then begin dm.qseries.edit; dm.qseriesactivo.Value := 0; dm.qseries.post; DBGrid56.SelectedIndex := 1; end else begin dm.qseries.edit; dm.qseriesactivo.Value := 1; dm.qseries.post; DBGrid56.SelectedIndex := 1; end; end; end; procedure TBASE.DBGrid56DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); const IsChecked: array [Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED); var DrawState: Integer; DrawRect: TRect; // dibujar check begin if (gdFocused in State) then begin if (Column.Field.FieldName = 'activo') then begin gcrcheck.Left := Rect.Left + DBGrid56.Left + 2; gcrcheck.Top := Rect.Top + DBGrid56.Top + 2; gcrcheck.Width := Rect.Right - Rect.Left; gcrcheck.Height := Rect.Bottom - Rect.Top; gcrcheck.Visible := true; end; end else begin if (Column.Field.FieldName = 'activo') then begin DrawRect := Rect; InflateRect(DrawRect, -1, -1); if Column.Field.AsInteger = 0 then DrawState := IsChecked[false]; if Column.Field.AsInteger = 1 then DrawState := IsChecked[true]; // DrawState := ISChecked[Column.Field.Asinteger]; DBGrid56.Canvas.FillRect(Rect); DrawFrameControl(DBGrid56.Canvas.Handle, DrawRect, DFC_BUTTON, DrawState); end; end; end; procedure TBASE.DBGrid59DblClick(Sender: TObject); begin mostrarpesadas(dmproduccion.qentradasid.AsString); { fpesadas := Tfpesadas.Create(nil); try if fpesadas.qpesadas.Active = false then fpesadas.qpesadas.Open; fpesadas.Edit1.Text := ; fpesadas.btbuscar.Click; fpesadas.ShowModal; finally fpesadas.Free; end;} end; procedure TBASE.DBGrid5CellClick(Column: TColumn); begin if (dm.qanticiposdetalleestado.AsString = 'C') OR (dm.qanticiposdetalleestado.AsString = 'S') then BEGIN if dm.qanticiposdetalleestado.AsString = 'C' then begin dm.tanticipos.Locate('id', dm.qanticiposdetalleid.AsString, [locaseinsensitive]); dm.tanticipos.edit; dm.tanticiposestado.Value := 'S'; dm.tanticipos.post; dm.qanticiposdetalle.Refresh; dm.qanticiposdetalle.Locate('id', dm.tanticiposid.AsString, [locaseinsensitive]); end ELSE begin dm.tanticipos.Locate('id', dm.qanticiposdetalleid.AsString, [locaseinsensitive]); dm.tanticipos.edit; dm.tanticiposestado.Value := 'C'; dm.tanticipos.post; dm.qanticiposdetalle.Refresh; dm.qanticiposdetalle.Locate('id', dm.tanticiposid.AsString, [locaseinsensitive]); end; END; end; procedure TBASE.DBGrid5DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if dm.qanticiposdetalleestado.AsString = 'C' then begin DBGrid5.Canvas.brush.Color := amarillo; end; if dm.qanticiposdetalleestado.AsString = 'S' then begin DBGrid5.Canvas.brush.Color := rojo; end; if dm.qanticiposdetalleestado.AsString = 'V' then begin DBGrid5.Canvas.brush.Color := azul; end; if dm.qanticiposdetalleestado.AsString = 'P' then begin DBGrid5.Canvas.brush.Color := verde; end; DBGrid5.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure TBASE.DBGrid5TitleClick(Column: TColumn); var st: ZAbstractRODataset.TSortType; begin st := dm.qanticiposdetalle.SortType; dm.qanticiposdetalle.SortedFields := Column.FieldName; If st = stascending then dm.qanticiposdetalle.SortType := stDescending else dm.qanticiposdetalle.SortType := stascending; dm.dsqanticiposdetalle.DataSet.First; end; procedure TBASE.DBGrid60DblClick(Sender: TObject); begin mostrarpesadas(dmproduccion.qsalidaslotesid.AsString); { fpesadas := Tfpesadas.Create(nil); try if fpesadas.qpesadas.Active = false then fpesadas.qpesadas.Open; fpesadas.Edit1.Text := ; fpesadas.btbuscar.Click; fpesadas.ShowModal; finally fpesadas.Free; end;} end; procedure TBASE.DBGrid60DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if dmproduccion.qsalidaslotespeso_neto.AsFloat < dmproduccion.qsalidaslotespeso_neto_teorico.AsFloat then begin DBGrid60.Canvas.brush.Color := rojo; end; DBGrid60.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure TBASE.DBGrid64CellClick(Column: TColumn); var i: TBookmark; begin i := qempleados.GetBookmark; if qempleadosseleccionado.AsInteger = 1 then begin qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=0 where id=' + qempleadosid.AsString); qaux.ExecSQL; qempleados.Refresh; qempleados.GotoBookmark((i)); end ELSE begin qaux.SQL.Clear; qaux.SQL.Add('update trabajadores set seleccionado=1 where id=' + qempleadosid.AsString); qaux.ExecSQL; qempleados.Refresh; qempleados.GotoBookmark((i)); end end; procedure TBASE.DBGrid64DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if qempleadosseleccionado.AsInteger = 1 then begin DBGrid64.Canvas.brush.Color := verde; end; if qempleadosseleccionado.AsInteger = 0 then begin DBGrid64.Canvas.brush.Color := clWindow; end; DBGrid64.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure TBASE.DBGrid64TitleClick(Column: TColumn); var st: ZAbstractRODataset.TSortType; begin st := qempleados.SortType; qempleados.SortedFields := Column.FieldName; If st = stascending then qempleados.SortType := stDescending else qempleados.SortType := stascending; dsqtrabajadores.DataSet.First; end; procedure TBASE.DBGrid68DblClick(Sender: TObject); begin Button29.Click; end; procedure TBASE.DBGrid68DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if dm.qpartes_diarios2festivo.AsInteger = 1 then begin DBGrid68.Canvas.brush.Color := rojo; end; if dm.qpartes_diarios2validado.AsInteger = 1 then begin DBGrid68.Canvas.brush.Color := verde; end; DBGrid68.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure TBASE.DBGrid69DblClick(Sender: TObject); begin mostrarpesadas(dmestadisticas.qsalidasdetallesid.AsString); { fpesadas := Tfpesadas.Create(nil); try if fpesadas.qpesadas.Active = false then fpesadas.qpesadas.Open; fpesadas.Edit1.Text := ; fpesadas.btbuscar.Click; fpesadas.ShowModal; finally fpesadas.Free; end;} end; procedure TBASE.DBGrid7CellClick(Column: TColumn); begin if dm.tprenominascorrecto.AsInteger = 0 then begin dm.tprenominas.edit; dm.tprenominascorrecto.Value := 1; dm.tprenominas.post; dm.tprenominas.Refresh; end ELSE begin dm.tprenominas.edit; dm.tprenominascorrecto.Value := 0; dm.tprenominas.post; dm.tprenominas.Refresh; end; end; procedure TBASE.DBGrid7DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if dm.tprenominascorrecto.AsInteger = 0 then begin DBGrid7.Canvas.brush.Color := amarillo; end; if dm.tprenominascorrecto.AsInteger = 1 then begin DBGrid7.Canvas.brush.Color := verde; end; DBGrid7.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; procedure TBASE.DBGrid8TitleClick(Column: TColumn); var st: ZAbstractRODataset.TSortType; begin st := dm.qproductos.SortType; dm.qproductos.SortedFields := Column.FieldName; If st = stascending then dm.qproductos.SortType := stDescending else dm.qproductos.SortType := stascending; dm.dsqproductos.DataSet.First; end; procedure TBASE.listagrupos2CloseUp(Sender: TObject); begin vtactivo := qgrupostrabajadores2id.AsInteger; qempleados.Close; qempleados.Open; end; procedure TBASE.DBLookupComboBox12CloseUp(Sender: TObject); begin vtactivo := qgrupostrabajadores2id.AsInteger; qempleados.Close; qempleados.Open; btactualizarempleadosnominas.Click; end; procedure TBASE.DBLookupComboBox18Exit(Sender: TObject); begin dmtr.qlotespaisorigen.Value := qsocios2pais.AsString; end; procedure TBASE.DBLookupComboBox7CloseUp(Sender: TObject); begin if dmtr.qlotes.State in [dsinsert, dsedit] then dmtr.qlotesdesc_generador.Value := dmtr.qtiposgeneradordescripcion.AsString; end; procedure TBASE.DBMemo1Exit(Sender: TObject); begin if templeados.State in [dsedit, dsinsert] then templeados.post; Panel8.SetFocus; end; procedure TBASE.dlotescodigoExit(Sender: TObject); begin if dmtr.qlotes.State in [dsedit, dsinsert] then begin if lfecha.Text = '' then dmtr.qlotesfecha.Value := Date(); end; end; procedure TBASE.dlotesfcaducidadExit(Sender: TObject); begin btLguardar.SetFocus; end; procedure TBASE.dlotesfechaetiquetaExit(Sender: TObject); begin dmtr.qlotesfecha_caducidad.Value := dmtr.qlotesfecha.AsDateTime + 2; end; procedure TBASE.dlotesftrabajoExit(Sender: TObject); begin dmtr.qlotesfecha.Value := dmtr.qlotesfechaini_trabajo.AsDateTime; dmtr.qlotesfechafin_trabajo.Value := dmtr.qlotesfechaini_trabajo.AsDateTime; end; procedure TBASE.dsdocempleadosDataChange(Sender: TObject; Field: TField); var img: tPicture; ext, nomarchivo: string; SearchRec: TSearchRec; begin { If not DirectoryExists('c:\agrigest\tmp') then CreateDir('c:\agrigest\tmp'); if dmtr.documentos.State in [dsbrowse] then begin if FindFirst('c:\agrigest\tmp\*.*', faAnyFile, SearchRec) = 0 then repeat Deletefile('c:\agrigest\tmp\'+SearchRec.name); until (FindNext(SearchRec) <> 0); FindClose(SearchRec); if dmtr.documentos.RecordCount>0 then begin imgfoto.Picture:=nil; ext:=dmtr.documentosextension.AsString; nomarchivo:=dmtr.documentosnomarchivo.asstring; if nomarchivo<>'' then dmtr.documentosarchivo.savetofile('c:\agrigest\tmp\'+nomarchivo); if (ext='.jpg') or (ext='.jpeg') or (ext='.bmp') or (ext='.png') then begin imageempleados.Picture:=nil; if nomarchivo<>'' then imageempleados.Picture.LoadFromFile('c:\agrigest\tmp\'+nomarchivo); imageempleados.Visible:=true; btedocver2.Visible:=false; end else begin imageempleados.Visible:=false; btedocver2.Visible:=true; end; end; if dmtr.documentos.RecordCount=0 then begin imageempleados.Visible:=false; btedocver2.Visible:=false; imageempleados.Picture:=nil; end; end; } end; procedure TBASE.dsdocempleadosStateChange(Sender: TObject); begin { if dmtr.documentos.State in [dsedit,dsinsert] then begin btedocnuevo.enabled:=false; btedocmodificar.enabled:=false; btedocborrar.enabled:=false; btedocguardar.enabled:=true; btedoccancelar.enabled:=true; end; if dmtr.documentos.State in [dsbrowse] then begin btedocnuevo.enabled:=true; btedocmodificar.enabled:=true; btedocborrar.enabled:=true; btedocguardar.enabled:=false; btedoccancelar.enabled:=false; end; } end; procedure TBASE.dsdoclotesDataChange(Sender: TObject; Field: TField); var img: tPicture; ext, nomarchivo: string; SearchRec: TSearchRec; begin If not DirectoryExists('c:\agrigest\tmp') then CreateDir('c:\agrigest\tmp'); if dmtr.qdocumentos.State in [dsbrowse] then begin if FindFirst('c:\agrigest\tmp\*.*', faAnyFile, SearchRec) = 0 then repeat Deletefile('c:\agrigest\tmp\' + SearchRec.name); until (FindNext(SearchRec) <> 0); FindClose(SearchRec); if dmtr.qdocumentos.RecordCount > 0 then begin imgfoto.Picture := nil; ext := dmtr.qdocumentosextension.AsString; nomarchivo := dmtr.qdocumentosnomarchivo.AsString; if nomarchivo <> '' then dmtr.qdocumentosarchivo.SaveToFile('c:\agrigest\tmp\' + nomarchivo); if (ext = '.jpg') or (ext = '.jpeg') or (ext = '.bmp') or (ext = '.png') then begin imgfoto.Picture := nil; if nomarchivo <> '' then imgfoto.Picture.LoadFromFile('c:\agrigest\tmp\' + nomarchivo); imgfoto.Visible := true; btdver.Visible := false; end else begin imgfoto.Visible := false; btdver.Visible := true; end; end; if dmtr.qdocumentos.RecordCount = 0 then begin imgfoto.Visible := false; btdver.Visible := false; imgfoto.Picture := nil; end; // imagen.Free; // bmp.free; end; end; procedure TBASE.dsdoclotesStateChange(Sender: TObject); begin if dmtr.qdocumentos.State in [dsedit, dsinsert] then begin btdnuevo.Enabled := false; btdmodificar.Enabled := false; btdborrar.Enabled := false; btdimprimir.Enabled := false; btdguardar.Enabled := true; btdcancelar.Enabled := true; end; if dmtr.qdocumentos.State in [dsbrowse] then begin btdnuevo.Enabled := true; btdmodificar.Enabled := true; btdborrar.Enabled := true; btdimprimir.Enabled := true; btdguardar.Enabled := false; btdcancelar.Enabled := false; end; end; procedure TBASE.dsempresaStateChange(Sender: TObject); begin if dm.tempresa.State in [dsedit, dsinsert] then begin beanadir.Enabled := false; beborrar.Enabled := false; bemodificar.Enabled := false; beaceptar.Enabled := true; becancelar.Enabled := true; Panel150.Enabled := true; Panel169.Enabled := true; Panel170.Enabled := true; Panel116.Enabled := true; end else begin beanadir.Enabled := true; beborrar.Enabled := true; bemodificar.Enabled := true; beaceptar.Enabled := false; becancelar.Enabled := false; Panel150.Enabled := false; Panel169.Enabled := false; Panel170.Enabled := false; Panel116.Enabled := true; end; end; procedure TBASE.dsqalmacenesDataChange(Sender: TObject; Field: TField); begin dmestadisticas.qcontenido.Close; dmestadisticas.qcontenido.Prepare; dmestadisticas.qcontenido.ParamByName('ALMACEN').AsString := dm.qalmacenesnombre.AsString; dmestadisticas.qcontenido.Open; dmestadisticas.qproduccion_almacen.Close; dmestadisticas.qproduccion_almacen.Prepare; dmestadisticas.qproduccion_almacen.ParamByName('ALMACEN').AsString := dm.qalmacenesnombre.AsString; dmestadisticas.qproduccion_almacen.Open; end; procedure TBASE.dsqlotesStateChange(Sender: TObject); begin if dmtr.qlotes.State in [dsedit, dsinsert] then begin Panel83.Enabled := true; btlnuevo.Enabled := false; btLmodificar.Enabled := false; btLguardar.Enabled := true; btLcancelar.Enabled := true; end; if dmtr.qlotes.State in [dsbrowse] then begin Panel83.Enabled := false; btlnuevo.Enabled := true; btLmodificar.Enabled := true; btLguardar.Enabled := false; btLcancelar.Enabled := false; end; end; procedure TBASE.dsqmesasDataChange(Sender: TObject; Field: TField); var anyo, mes, dia: word; fdesde, fhasta: string; begin decodedate(fprodesde.Date, anyo, mes, dia); fdesde := inttostr(anyo) + '-' + inttostr(mes) + '-' + inttostr(dia); // decodedate(fprohasta.Date, anyo, mes, dia); // fhasta := inttostr(anyo) + '-' + inttostr(mes) + '-' + inttostr(dia); dm.qnominasproduccion.Close; dm.qnominasproduccion.SQL.Clear; dm.qnominasproduccion.SQL.Add ('select * from trabajo_diario where origen like(' + '''' + '%' + dm.qmesasmesa.AsString + '%' + '''' + ') and fecha=' + '''' + fdesde + '''' + ' and idt in ('); dm.qnominasproduccion.SQL.Add('select idt from movimiento_mesas where mesa=' + '''' + dm.qmesasmesa.AsString + '''' + ' and fecha=' + '''' + fdesde + '''' + ') order by idt'); dm.qnominasproduccion.Open; dm.qmovimientomesas.Close; dm.qmovimientomesas.SQL.Clear; dm.qmovimientomesas.SQL.Add('select * from movimiento_mesas where mesa=' + '''' + dm.qmesasmesa.AsString + '''' + ' and fecha=' + '''' + fdesde + '''' + ' order by trabajador,entrada_real'); dm.qmovimientomesas.Open; end; procedure TBASE.dsqparcelas2DataChange(Sender: TObject; Field: TField); begin if dmtr.qlotes.State in [dsedit,dsinsert] then begin if qparcelas2tiene_gg.AsInteger=1 then dmtr.qlotessgg.Value:=qparcelas2sello_gg.AsString else dmtr.qlotessgg.Value:=''; if qparcelas2tiene_dop.AsInteger=1 then dmtr.qlotessdop.Value:=qparcelas2sello_dop.AsString else dmtr.qlotessdop.Value:=''; if qparcelas2tiene_igp.AsInteger=1 then dmtr.qlotessigp.Value:=qparcelas2sello_igp.AsString else dmtr.qlotessigp.Value:=''; if qparcelas2tiene_ifs.AsInteger=1 then dmtr.qlotessifs.Value:=qparcelas2sello_ifs.AsString else dmtr.qlotessifs.Value:=''; if qparcelas2tiene_brc.AsInteger=1 then dmtr.qlotessbrc.Value:=qparcelas2sello_brc.AsString else dmtr.qlotessbrc.Value:=''; end; end; procedure TBASE.dsqsocios2DataChange(Sender: TObject; Field: TField); begin qparcelas2.Close; qparcelas2.Prepare; qparcelas2.ParamByName('PROPIETARIO').Asstring:=qsocios2id.Asstring; qparcelas2.Open; { qparcelas2.SQL.Clear; qparcelas2.SQL.Add ('select codpar,empresa,nombre,propietario,numero from parcelas where propietario=' + qsocios2id.AsString + ' order by nombre'); qparcelas2.Open;} if qparcelas2.RecordCount = 0 then begin qparcelas2.Close; qparcelas2.prepare; qparcelas2.parambyname('PROPIETARIO').AsString:='%'; // ('select codpar,empresa,nombre,propietario,numero from parcelas order by nombre'); qparcelas2.Open; end; end; procedure TBASE.dsqtipohoraDataChange(Sender: TObject; Field: TField); begin lprecio.Text := dm.qtipohorasprecio.AsString; end; procedure TBASE.dsqtrabajadoresDataChange(Sender: TObject; Field: TField); var idt, filtrojornales, filtroanticipos: string; begin { paneldocumentosempleados.Visible:=false; btedocver.Caption:='Ver Doc.'; if (templeados.State=dsinsert) or (templeados.State=dsedit) then templeados.Post; if qempleados.RecordCount>0 then begin temp_fotos.Close; temp_fotos.Filtered:=false; temp_fotos.Filter:='ide='+qempleadoside.Asstring+' and idt='+qempleadosid.Asstring; temp_fotos.filtered:=true; temp_fotos.open; If not DirectoryExists('c:\agrigest\tmp') then CreateDir('c:\agrigest\tmp'); Deletefile('c:\agrigest\tmp\empimg.jpg'); image2.Picture:=nil; if temp_fotosidt.AsInteger=qempleadosid.AsInteger then begin temp_fotosimagen.savetofile('c:\agrigest\tmp\empimg.jpg'); image2.Picture.LoadFromFile('c:\agrigest\tmp\empimg.jpg'); end; } idt := qempleadosid.AsString; templeados.Locate('id', idt, [locaseinsensitive]); if (qempleados.RecordCount > 0) and (TabJornales.Visible) then begin // templeados.Open; Label46.Caption := qempleadosnombre.AsString; Label10.Caption := qempleadosnombre.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); if TESTADO.ItemIndex <> 0 then filtrojornales := filtrojornales + ' and estado=' + TESTADO.Text; filtrojornales := filtrojornales + ' order by fecha desc'; qjornales.Close; qjornales.SQL.Clear; qjornales.SQL.Add('select * from trabajo_diario ' + filtrojornales); qjornales.Open; filtroanticipos := 'where idt=' + idt; if tanyo2.ItemIndex <> 0 then filtroanticipos := filtroanticipos + ' and year(fecha)=' + tanyo2.Text; if tmes2.ItemIndex <> 0 then filtroanticipos := filtroanticipos + ' and month(fecha)=' + inttostr(tmes2.ItemIndex); if testado2.ItemIndex <> 0 then filtroanticipos := filtroanticipos + ' and estado=' + testado2.Text; filtroanticipos := filtroanticipos + ' order by fecha desc'; dm.qanticipos.Close; dm.qanticipos.SQL.Clear; dm.qanticipos.SQL.Add('select * from anticipos ' + filtroanticipos); dm.qanticipos.Open; end; end; procedure TBASE.dstrabajadoresStateChange(Sender: TObject); begin if templeados.State = dsbrowse then begin Panel164.Enabled := false; Panel7.Enabled := false; Panel6.Enabled := false; Button3.Enabled := true; Button4.Enabled := true; falta.Enabled := false; fbaja.Enabled := false; listagrupos.Enabled := false; end else begin Panel164.Enabled := true; Panel7.Enabled := true; Panel6.Enabled := true; Button3.Enabled := false; Button4.Enabled := false; falta.Enabled := true; fbaja.Enabled := true; listagrupos.Enabled := true; end; end; procedure TBASE.tbuscarlotesChange(Sender: TObject); begin filtrolotes := '%' + tbuscarlotes.Text + '%'; dmtr.qlotes.Close; dmtr.qlotes.Open; end; procedure TBASE.tbuscarnominasChange(Sender: TObject); begin filtrotrabajadores := '%' + tbuscarnominas.Text + '%'; qempleados.Close; qempleados.Open; btactualizarempleadosnominas.Click end; procedure TBASE.tbuscarparcelasChange(Sender: TObject); begin filtroparcelas := '%' + tbuscarparcelas.Text + '%'; dm.qparcelas.Close; dm.qparcelas.Open; end; procedure TBASE.EntradassalidasClick(Sender: TObject); begin infmovimientos := Tinfmovimientos.Create(nil); try infmovimientos.ShowModal(); finally infmovimientos.Free; end; end; procedure TBASE.Empleados2Click(Sender: TObject); begin fempleados := Tfempleados.Create(nil); try fempleados.ShowModal(); finally fempleados.Free; end; end; procedure TBASE.EntradasEnvasados1Click(Sender: TObject); begin mostrarpesadas('');{ fpesadas := Tfpesadas.Create(nil); try if fpesadas.qpesadas.Active = false then begin end; fpesadas.Edit1.Text := ''; fpesadas.ShowModal; finally fpesadas.Free; end; } end; procedure TBASE.EntradasMateriales1Click(Sender: TObject); begin fentradas.Entradas := Tentradas.Create(nil); try fentradas.Entradas.ShowModal(); finally fentradas.Entradas.Free; end; end; procedure TBASE.EnvasesAlmacen1Click(Sender: TObject); begin envases_almacen := Tenvases_almacen.Create(nil); try envases_almacen.ShowModal(); finally envases_almacen.Free; end; end; procedure TBASE.EPIS1Click(Sender: TObject); begin epis := Tepis.Create(nil); try epis.ShowModal(); finally epis.Free; end; end; procedure TBASE.Estadodestocks1Click(Sender: TObject); begin consumosfito := Tconsumosfito.Create(nil); try consumosfito.ShowModal(); finally consumosfito.Free; end; end; procedure TBASE.faltaCloseUp(Sender: TObject); begin templeadosFECHAALTA.Value := falta.Date; end; procedure TBASE.fbajaCloseUp(Sender: TObject); begin templeadosFECHABAJA.Value := fbaja.Date; end; procedure TBASE.ffinCloseUp(Sender: TObject); begin if not(dm.qcampanyas.State in [dsedit, dsinsert]) then dm.qcampanyas.edit; dm.qcampanyasfechafin.Value := ffin.Date; end; procedure TBASE.finicioCloseUp(Sender: TObject); begin if not(dm.qcampanyas.State in [dsedit, dsinsert]) then dm.qcampanyas.edit; dm.qcampanyasfechainicio.Value := finicio.Date; end; procedure TBASE.Formasdepago1Click(Sender: TObject); begin fformaspago := Tfformaspago.Create(nil); try fformaspago.ShowModal; finally fformaspago.Free; end; end; procedure TBASE.Formatosdeimpresin1Click(Sender: TObject); begin formularios := Tformularios.Create(nil); try formularios.ShowModal; finally formularios.Free; end; end; procedure TBASE.FormCreate(Sender: TObject); var i: Integer; begin Application.OnMessage := AppMessage; gcrcheck.DataField := 'activo'; gcrcheck.Visible := false; gcrcheck.SendToBack; gcrcheck.Color := DBGrid56.Color; gcrcheck.Caption := ''; // explained later in the article gcrcheck.ValueChecked := '0'; gcrcheck.ValueUnChecked := '1'; end; procedure TBASE.FormKeyPress(Sender: TObject; var Key: Char); var formatos: tformatsettings; punto: string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto := formatos.DecimalSeparator; if punto = ',' then begin if (Key = '.') and (activecontrol is TDBEdit) then begin if (activecontrol as TDBEdit).Field.DataType in [ftFloat, ftCurrency, ftBCD, ftfmtbcd] then Key := ',' end; if (Key = '.') and (activecontrol is TDBGrid) then begin Key := ',' end; if (Key = '.') and (activecontrol is TEdit) then begin if (activecontrol as TEdit).name = 'thoras' then Key := ','; if (activecontrol as TEdit).name = 'edimporte' then Key := ','; if (activecontrol as TEdit).name = 'edjhoras' then Key := ','; if (activecontrol as TEdit).name = 'lprecio' then Key := ','; if (activecontrol as TEdit).name = 'edjprecio' then Key := ','; if (activecontrol as TEdit).name = 'limporteanticipos' then Key := ','; end; end; if (Key = #13) then begin Perform(WM_NextDLGCtl, 0, 0); Key := #0; end; end; procedure TBASE.FormShow(Sender: TObject); begin dm.DBagrigest.Disconnect; dm.tempresa.Open; Timer2.Interval := dm.tempresatavisostock.AsInteger * 60000; if tlimitado = '0' then begin tfechajornal.Date := Date; fechaanticipo.Date := Date; end; if tlimitado = '1' then begin tfechajornal.Date := Date; fechaanticipo.Date := Date; btproduccion.Visible := true; Btjornales.Visible := true; Btjornales.Caption := 'Partes de Trabajo'; BtEmpleados.Visible := false; btempresa.Visible := false; btAgenda.Visible := false; btexpediciones.Visible := false; bttrazabilidad.Visible := false; Panel117.Visible := false; end; if tlimitado = '2' then begin tfechajornal.Date := Date; fechaanticipo.Date := Date; btproduccion.Visible := true; Btjornales.Visible := false; Btjornales.Caption := 'Partes de Trabajo'; BtEmpleados.Visible := false; btempresa.Visible := true; btAgenda.Visible := false; btexpediciones.Visible := false; bttrazabilidad.Visible := true; Panel117.Visible := false; Menu.Items[3].Visible := false; Menu.Items[1].Visible := false; end; if tlimitado = '3' then begin pmenu.Visible:=false; Menu.Items[0].Visible := false; Menu.Items[1].Visible := false; Menu.Items[2].Visible := false; Menu.Items[3].Visible := false; Menu.Items[4].Visible := false; Menu.Items[5].Visible := false; // Menu.Items[6].Visible := false; Menu.Items[6].Items[0].Visible:=false; Menu.Items[6].Items[1].Visible:=false; Menu.Items[6].Items[2].Visible:=false; Menu.Items[6].Items[3].Visible:=false; Menu.Items[6].Items[4].Visible:=false; Menu.Items[6].Items[5].Visible:=false; Menu.Items[6].Items[6].Visible:=false; Menu.Items[7].Visible := false; Menu.Items[8].Visible := false; Menu.Items[9].Visible := false; end; end; procedure TBASE.fprodesdeChange(Sender: TObject); var anyo, mes, dia: word; fdesde, fhasta: string; begin { timer1.Enabled:=false; decodedate(fprodesde.Date,anyo,mes,dia); fdesde:=inttostr(anyo)+'-'+inttostr(mes)+'-'+inttostr(dia); decodedate(fprohasta.Date,anyo,mes,dia); fhasta:=inttostr(anyo)+'-'+inttostr(mes)+'-'+inttostr(dia); dm.qmesas.Close; dm.qmesas.SQL.Clear; dm.qmesas.SQL.Add('select distinct(mesa) from movimiento_mesas where fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''+' order by mesa'); dm.qmesas.open; if pageproduccion.TabIndex=0 then begin end; if pageproduccion.TabIndex=1 then begin end; if pageproduccion.TabIndex=2 then begin end; if pageproduccion.TabIndex=6 then begin dm.qcontrolproduccion.Close; dm.qcontrolproduccion.sql.Clear; dm.qcontrolproduccion.sql.Add('select * from control_produccion where fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''); dm.qcontrolproduccion.open; end; dm.qproduccionmesa2.close; dm.qproduccionmesa2.sql.clear; dm.qproduccionmesa2.sql.Add('SELECT mesa,sum(cantidad) as cantidad,sum(horasmesa) as horasmesa,sum(cantidad)/sum(horasmesa) as cantidadhora FROM vista_produccionmesahora where fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''+' group by mesa order by mesa ' ); dm.qproduccionmesa2.open; dm.qproduccionmesa.Close; dm.qproduccionmesa.sql.Clear; dm.qproduccionmesa.sql.Add('SELECT * FROM vista_produccionmesasdetalle where fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''); dm.qproduccionmesa.open; dm.qproduccion.Close; dm.qproduccion.sql.Clear; dm.qproduccion.sql.Add('select * from vista_produccion where fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''); dm.qproduccion.open; dm.qproduccionembasadora.Close; dm.qproduccionembasadora.sql.Clear; dm.qproduccionembasadora.sql.Add('SELECT mesa,bascula,producto,count(*) as pesadas,sum(peso_real-tara) as cantidad,idt,embasadora FROM produccion where fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''+' group by mesa,bascula,producto,idt order by fecha DESC,mesa,bascula'); dm.qproduccionembasadora.open; dm.qproduccionhora.Close; dm.qproduccionhora.sql.Clear; dm.qproduccionhora.sql.Add('select hour(hora) as hora,sum(peso_real-tara) as cantidad from produccion where fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''+' group by hour(hora)'); dm.qproduccionhora.open; timer1.Enabled:=true; } end; procedure TBASE.fprohastaChange(Sender: TObject); var anyo, mes, dia: word; fdesde, fhasta: string; begin { timer1.Enabled:=false; decodedate(fprodesde.Date,anyo,mes,dia); fdesde:=inttostr(anyo)+'-'+inttostr(mes)+'-'+inttostr(dia); decodedate(fprohasta.Date,anyo,mes,dia); fhasta:=inttostr(anyo)+'-'+inttostr(mes)+'-'+inttostr(dia); if pageproduccion.TabIndex=6 then begin dm.qcontrolproduccion.Close; dm.qcontrolproduccion.sql.Clear; dm.qcontrolproduccion.sql.Add('select * from control_produccion where fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''); dm.qcontrolproduccion.open; end; dm.qmesas.Close; dm.qmesas.SQL.Clear; dm.qmesas.SQL.Add('select distinct(mesa) from movimiento_mesas where fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''+' order by mesa'); dm.qmesas.open; dm.qproduccionmesa2.close; dm.qproduccionmesa2.sql.clear; dm.qproduccionmesa2.sql.Add('select p.mesa,p.cantidad,h.horasmesa,p.cantidad/h.horasmesa as cantidadhora from (SELECT mesa,sum(peso_real-tara) as cantidad,idt,embasadora FROM produccion where fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''+' group by mesa order by mesa) as p ' ); dm.qproduccionmesa2.sql.Add(' inner join '); dm.qproduccionmesa2.sql.Add(' (select mesa,sum(horas) as horasmesa from ( select mesa,sum(timestampdiff(minute,entrada_real,SALIDA_REAL)/60) as horas from movimiento_mesas where fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''+' and SALIDA_REAL is NOT null group by mesa '); dm.qproduccionmesa2.sql.Add(' union '); dm.qproduccionmesa2.sql.Add(' select mesa,sum(timestampdiff(minute,entrada_real,now())/60) as horas from movimiento_mesas where fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''+' and SALIDA_REAL is null group by mesa ) as grupo GROUP by mesa) as h'); dm.qproduccionmesa2.SQL.Add(' on p.mesa=h.mesa'); dm.qproduccionmesa2.open; dm.qproduccionmesa.Close; dm.qproduccionmesa.sql.Clear; dm.qproduccionmesa.sql.Add('SELECT * FROM vista_produccionmesasdetalle where fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''); dm.qproduccionmesa.open; dm.qproduccionembasadora.Close; dm.qproduccionembasadora.sql.Clear; dm.qproduccionembasadora.sql.Add('SELECT mesa,bascula,producto,count(*) as pesadas,sum(peso_real-tara) as cantidad,idt,embasadora FROM produccion where fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''+' group by mesa,bascula,producto,idt order by fecha DESC,mesa,bascula'); dm.qproduccionembasadora.open; dm.qproduccionhora.Close; dm.qproduccionhora.sql.Clear; dm.qproduccionhora.sql.Add('select hour(hora) as hora,sum(peso_real-tara) as cantidad from produccion where fecha>='+''''+fdesde+''''+' and fecha<='+''''+fhasta+''''+' group by hour(hora)'); dm.qproduccionhora.open; timer1.Enabled:=true; } end; procedure TBASE.Gruposdeempleados1Click(Sender: TObject); begin grupostrabajadores := Tgrupostrabajadores.Create(nil); try grupostrabajadores.ShowModal(); finally grupostrabajadores.Free; end; end; procedure TBASE.GruposFamilias1Click(Sender: TObject); begin fgruposfamilias := Tfgruposfamilias.Create(nil); try fgruposfamilias.ShowModal(); finally fgruposfamilias.Free; end; end; procedure TBASE.hdesdeCloseUp(Sender: TObject); begin btprodaceptar.Click; end; procedure TBASE.hhastaCloseUp(Sender: TObject); begin btprodaceptar.Click; end; procedure TBASE.imgfotoClick(Sender: TObject); var nomarchivo: string; begin { nomarchivo:=dmtr.documentosnomarchivo.asstring; ShellExecute(base.Handle,nil,PChar('c:\agrigest\tmp\'+nomarchivo),'','',SW_SHOWNORMAL); } end; procedure TBASE.Inventarios1Click(Sender: TObject); begin controlstock := Tcontrolstock.Create(nil); try controlstock.ShowModal(); finally controlstock.Free; end; end; procedure TBASE.Librosdecampo1Click(Sender: TObject); begin cuadernos := Tcuadernos.Create(nil); try cuadernos.ShowModal(); finally cuadernos.Free; end; end; procedure TBASE.TiposdeImpuestos1Click(Sender: TObject); begin ftipos_impuestos := Tftipos_impuestos.Create(nil); try ftipos_impuestos.ShowModal; finally ftipos_impuestos.Free; end; end; procedure TBASE.listaanyosChange(Sender: TObject); var dia, mes, anyo: word; bisiesto: Integer; begin bisiesto := 0; dia := 1; if listameses.ItemIndex = 0 then mes := 1 else mes := listameses.ItemIndex; if listaanyos.ItemIndex = 0 then anyo := 1900 else anyo := StrToInt(listaanyos.Text); if listaanyos.ItemIndex <> 0 then if isleapyear(StrToInt(listaanyos.Text)) then bisiesto := 1; nomfechadesde.Date := encodedate(anyo, mes, dia); if (mes = 1) or (mes = 3) or (mes = 5) or (mes = 7) or (mes = 8) or (mes = 10) or (mes = 12) then dia := 31; if (mes = 4) or (mes = 6) or (mes = 9) or (mes = 11) then dia := 30; if (mes = 2) and (bisiesto = 1) then dia := 29; if (mes = 2) and (bisiesto = 0) then dia := 28; if listameses.ItemIndex = 0 then mes := 12 else mes := listameses.ItemIndex; if listaanyos.ItemIndex = 0 then anyo := 2100 else anyo := StrToInt(listaanyos.Text); nomfechahasta.Date := encodedate(anyo, mes, dia); end; procedure TBASE.listamesesChange(Sender: TObject); var dia, mes, anyo: word; bisiesto: Integer; begin bisiesto := 0; dia := 1; if listameses.ItemIndex = 0 then mes := 1 else mes := listameses.ItemIndex; if listaanyos.ItemIndex = 0 then anyo := 1900 else anyo := StrToInt(listaanyos.Text); if listaanyos.ItemIndex <> 0 then if isleapyear(StrToInt(listaanyos.Text)) then bisiesto := 1; nomfechadesde.Date := encodedate(anyo, mes, dia); if (mes = 1) or (mes = 3) or (mes = 5) or (mes = 7) or (mes = 8) or (mes = 10) or (mes = 12) then dia := 31; if (mes = 4) or (mes = 6) or (mes = 9) or (mes = 11) then dia := 30; if (mes = 2) and (bisiesto = 1) then dia := 29; if (mes = 2) and (bisiesto = 0) then dia := 28; if listameses.ItemIndex = 0 then mes := 12 else mes := listameses.ItemIndex; if listaanyos.ItemIndex = 0 then anyo := 2100 else anyo := StrToInt(listaanyos.Text); nomfechahasta.Date := encodedate(anyo, mes, dia); end; procedure TBASE.ljhoraCloseUp(Sender: TObject); begin edjprecio.Text := dm.qtipohorasprecio.AsString; end; procedure TBASE.lprecioEnter(Sender: TObject); begin if lprecio.Text = '' then lprecio.Text := '0'; end; procedure TBASE.ltipohoraExit(Sender: TObject); begin lprecio.Text := dm.qtipohorasprecio.AsString; end; procedure TBASE.Maquinria1Click(Sender: TObject); begin vehiculos := Tvehiculos.Create(nil); try vehiculos.ShowModal; finally vehiculos.Free; end; end; procedure TBASE.Materiaprima1Click(Sender: TObject); begin cc_materiasprimas := Tcc_materiasprimas.Create(nil); try cc_materiasprimas.ShowModal; finally cc_materiasprimas.Free; end; end; procedure TBASE.MateriasPrimas1Click(Sender: TObject); begin genericas := Tgenericas.Create(nil); try genericas.ShowModal(); finally genericas.Free; end; end; procedure TBASE.calendarionotasClick(Sender: TObject); var anyo, mes, dia: word; vfecha, vanyo, vanyosig, vmes, vmessig, vdia: string; begin decodedate(calendarionotas.Date, anyo, mes, dia); vanyo := floattostr(anyo); vanyosig := floattostr(anyo); vmes := floattostr(mes); vmessig := floattostr(mes + 1); vdia := floattostr(dia); if Length(vmes) = 1 then vmes := '0' + vmes; if Length(vmessig) = 1 then vmessig := '0' + vmessig; if vmessig = '13' then begin vmessig := '01'; vanyosig := floattostr(anyo + 1); end; if Length(vdia) = 1 then vdia := '0' + vdia; vfecha := floattostr(anyo) + '-' + vmes + '-' + vdia; dm.tcalendario_laboral.Refresh; dm.tcalendario_laboral.Locate('fecha', vfecha, [locaseinsensitive]); dm.qaux1.Close; dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add ('select count(*) from calendario_laboral where festivo=0 and fecha>=' + '''' + vanyo + '-' + vmes + '-01' + '''' + 'and fecha<' + '''' + vanyosig + '-' + vmessig + '-01' + ''''); dm.qaux1.Open; Label80.Caption := 'Dias laborables del mes: ' + dm.qaux1.Fields[0].AsString; end; procedure TBASE.CalibresCalidades1Click(Sender: TObject); begin fcalibrescalidad := Tfcalibrescalidad.Create(nil); try fcalibrescalidad.ShowModal(); finally fcalibrescalidad.Free; end; end; procedure TBASE.Campaas1Click(Sender: TObject); begin usuarios := Tusuarios.Create(nil); try usuarios.ShowModal; finally usuarios.Free; end; end; procedure TBASE.CheckBox10Click(Sender: TObject); begin if CheckBox10.Checked then begin dm.qaux1.Close; dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add('update trabajadores set seleccionado=1'); dm.qaux1.ExecSQL; dm.qtipohoras2.Refresh; end else begin dm.qaux1.Close; dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add('update trabajadores set seleccionado=0'); dm.qaux1.ExecSQL; dm.qtrabajadores2.Refresh; end; end; procedure TBASE.CheckBox11Click(Sender: TObject); begin if CheckBox11.Checked then begin dm.qaux1.Close; dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add('update prenominas set correcto=1'); dm.qaux1.ExecSQL; dm.tprenominas.Refresh; end else begin dm.qaux1.Close; dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add('update prenominas set correcto=0'); dm.qaux1.ExecSQL; dm.tprenominas.Refresh; end; end; procedure TBASE.CheckBox12Click(Sender: TObject); begin if CheckBox12.Checked then begin dm.qaux1.Close; dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add('update parcelas set seleccionado=1'); dm.qaux1.ExecSQL; dm.qparcela2.Refresh; end else begin dm.qaux1.Close; dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add('update parcelas set seleccionado=0'); dm.qaux1.ExecSQL; dm.qparcela2.Refresh; end; end; procedure TBASE.checktodos2Click(Sender: TObject); var selectqempleados: string; begin selectqempleados := qempleados.SQL.Text; if checktodos2.Checked then begin qaux.SQL.Clear; qaux.SQL.Add ('update trabajadores set seleccionado=1 where id in (select id from (' + selectqempleados + ') as emp)'); qaux.ExecSQL; end else begin qaux.SQL.Clear; qaux.SQL.Add ('update trabajadores set seleccionado=0 where id in (select id from (' + selectqempleados + ') as emp)'); qaux.ExecSQL; end; qempleados.Close; qempleados.Open; end; procedure TBASE.CheckBox1Click(Sender: TObject); begin if CheckBox2.Checked then CheckBox2.Checked := false else CheckBox2.Checked := true; if CheckBox3.Checked then CheckBox3.Checked := false else CheckBox3.Checked := true; if CheckBox4.Checked then CheckBox4.Checked := false else CheckBox4.Checked := true; if CheckBox5.Checked then CheckBox5.Checked := false else CheckBox5.Checked := true; if CheckBox6.Checked then CheckBox6.Checked := false else CheckBox6.Checked := true; end; procedure TBASE.CheckBox7Click(Sender: TObject); begin if CheckBox7.Checked then begin dm.qaux1.Close; dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add('update articulos set seleccionado=1'); dm.qaux1.ExecSQL; dm.qtipohoras2.Refresh; end else begin dm.qaux1.Close; dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add('update articulos set seleccionado=0'); dm.qaux1.ExecSQL; dm.qtipohoras2.Refresh; end; end; procedure TBASE.CheckBox8Click(Sender: TObject); begin if CheckBox8.Checked then begin dm.qaux1.Close; dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add('update trabajadores set seleccionado=1'); dm.qaux1.ExecSQL; dm.qtipohoras2.Refresh; end else begin dm.qaux1.Close; dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add('update trabajadores set seleccionado=0'); dm.qaux1.ExecSQL; dm.qtrabajadores2.Refresh; end; end; procedure TBASE.CheckBox9Click(Sender: TObject); begin if CheckBox9.Checked then begin dm.qaux1.Close; dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add('update tipo_trabajo set seleccionado=1'); dm.qaux1.ExecSQL; dm.qtipotrabajo2.Refresh; end else begin dm.qaux1.Close; dm.qaux1.SQL.Clear; dm.qaux1.SQL.Add('update tipo_trabajo set seleccionado=0'); dm.qaux1.ExecSQL; dm.qtipotrabajo2.Refresh; end; end; procedure TBASE.checktodosClick(Sender: TObject); var selectqempleados: string; begin selectqempleados := qempleados.SQL.Text; if checktodos.Checked then begin qaux.SQL.Clear; qaux.SQL.Add ('update trabajadores set seleccionado=1 where id in (select id from (' + selectqempleados + ') as emp)'); qaux.ExecSQL; end else begin qaux.SQL.Clear; qaux.SQL.Add ('update trabajadores set seleccionado=0 where id in (select id from (' + selectqempleados + ') as emp)'); qaux.ExecSQL; end; qempleados.Close; qempleados.Open; end; procedure TBASE.chktodashorasClick(Sender: TObject); begin if chktodashoras.Checked then begin dm.qtipohoras.Close; dm.qtipohoras.SQL.Clear; dm.qtipohoras.SQL.Add('select * from articulos order by codart'); dm.qtipohoras.Open; end else begin dm.qtipohoras.Close; dm.qtipohoras.SQL.Clear; dm.qtipohoras.SQL.Add ('select * from articulos where activo=1 order by codart'); dm.qtipohoras.Open; end; end; procedure TBASE.chktodasmateriasprimasClick(Sender: TObject); begin if chktodasmateriasprimas.Checked then begin dm.qmateriasprimas.Close; dm.qmateriasprimas.SQL.Clear; dm.qmateriasprimas.SQL.Add('select * from materias_primas order by id'); dm.qmateriasprimas.Open; end else begin dm.qmateriasprimas.Close; dm.qmateriasprimas.SQL.Clear; dm.qmateriasprimas.SQL.Add ('select * from materias_primas where activo=1 order by id'); dm.qmateriasprimas.Open; end; end; procedure TBASE.chktodosalmacenesClick(Sender: TObject); begin if chktodosalmacenes.Checked then begin dm.qalmacenes.Close; dm.qalmacenes.SQL.Clear; dm.qalmacenes.SQL.Add('select * from almacenes order by nombre'); dm.qalmacenes.Open; end else begin dm.qalmacenes.Close; dm.qalmacenes.SQL.Clear; dm.qalmacenes.SQL.Add ('select * from almacenes where activo=1 order by nombre'); dm.qalmacenes.Open; end; end; procedure TBASE.chktodoscentroscosteClick(Sender: TObject); begin if chktodoscentroscoste.Checked then begin dm.qparcelas.Close; dm.qparcelas.SQL.Clear; dm.qparcelas.SQL.Add('select * from parcelas order by nombre'); dm.qparcelas.Open; end else begin dm.qparcelas.Close; dm.qparcelas.SQL.Clear; dm.qparcelas.SQL.Add ('select * from parcelas where activo=1 order by nombre'); dm.qparcelas.Open; end; end; procedure TBASE.chktodosempleadosClick(Sender: TObject); begin qempleados.Close; qempleados.Open; end; procedure TBASE.chktodosenvasesalmacenClick(Sender: TObject); begin { if chktodosenvasesalmacen.Checked then begin dm.qarticulosalmacen.Close; dm.qarticulosalmacen.SQL.Clear; dm.qarticulosalmacen.SQL.Add('select * from articulos_almacen order by codigo'); dm.qarticulosalmacen.Open; end else begin dm.qarticulosalmacen.Close; dm.qarticulosalmacen.SQL.Clear; dm.qarticulosalmacen.SQL.Add('select * from articulos_almacen where activo=1 order by codigo'); dm.qarticulosalmacen.Open; end; } end; procedure TBASE.chktodosproductosClick(Sender: TObject); begin if chktodosproductos.Checked then begin dm.qproductos.Close; dm.qproductos.SQL.Clear; dm.qproductos.SQL.Add('select * from productos order by descripcion'); dm.qproductos.Open; end else begin dm.qproductos.Close; dm.qproductos.SQL.Clear; dm.qproductos.SQL.Add ('select * from productos where activo=1 order by descripcion'); dm.qproductos.Open; end; end; procedure TBASE.chktodostrabajosalmacenClick(Sender: TObject); begin if chktodostrabajosalmacen.Checked then begin dm.qtrabajosalmacen.Close; dm.qtrabajosalmacen.SQL.Clear; dm.qtrabajosalmacen.SQL.Add('select * from trabajos_almacen order by id'); dm.qtrabajosalmacen.Open; end else begin dm.qtrabajosalmacen.Close; dm.qtrabajosalmacen.SQL.Clear; dm.qtrabajosalmacen.SQL.Add ('select * from trabajos_almacen where activo=1 order by id'); dm.qtrabajosalmacen.Open; end; end; procedure TBASE.chktodostrabajosClick(Sender: TObject); begin if chktodostrabajos.Checked then begin dm.qtrabajos.Close; dm.qtrabajos.SQL.Clear; dm.qtrabajos.SQL.Add('select * from tipo_trabajo order by id'); dm.qtrabajos.Open; end else begin dm.qtrabajos.Close; dm.qtrabajos.SQL.Clear; dm.qtrabajos.SQL.Add ('select * from tipo_trabajo where activo=1 order by id'); dm.qtrabajos.Open; end; end; procedure TBASE.Clientes1Click(Sender: TObject); begin clientes := Tclientes.Create(nil); try clientes.ShowModal(); finally clientes.Free; end; end; procedure TBASE.comboprodmesasCloseUp(Sender: TObject); begin btprodaceptar.Click; end; procedure TBASE.comboprodmprimasCloseUp(Sender: TObject); begin btprodaceptar.Click; end; procedure TBASE.comboprodproductoCloseUp(Sender: TObject); begin btprodaceptar.Click; end; procedure TBASE.Compras1Click(Sender: TObject); begin impentradas := Timpentradas.Create(nil); try impentradas.ShowModal(); finally impentradas.Free; end; end; procedure TBASE.Comprobararticulosconstockbajo1Click(Sender: TObject); begin controlminimos := Tcontrolminimos.Create(nil); try controlminimos.ShowModal(); finally controlminimos.Free; end; end; procedure TBASE.CondicionesMeteorolgicas1Click(Sender: TObject); begin meteorologia := Tmeteorologia.Create(nil); try meteorologia.vempresa:=dm.tempresaid.AsInteger; meteorologia.ShowModal(); finally meteorologia.Free; end; end; procedure TBASE.ConectarconSistemPin1Click(Sender: TObject); begin importardesdepresenciapin := Timportardesdepresenciapin.Create(nil); try importardesdepresenciapin.ShowModal(); finally importardesdepresenciapin.Free; end; end; procedure TBASE.ConfiguracinAlmacen1Click(Sender: TObject); begin configuracionalmacen := Tconfiguracionalmacen.Create(nil); try configuracionalmacen.ShowModal(); finally configuracionalmacen.Free; end; end; procedure TBASE.Consumosdefitosanitarios1Click(Sender: TObject); begin consumosfitoparcelas := Tconsumosfitoparcelas.Create(nil); try consumosfitoparcelas.ShowModal(); finally consumosfitoparcelas.Free; end; end; procedure TBASE.Consumosdemateriales1Click(Sender: TObject); begin insumos := Tinsumos.Create(nil); try insumos.ShowModal(); finally insumos.Free; end; end; procedure TBASE.Consumosygastos2Click(Sender: TObject); begin consumos_gastos := Tconsumos_gastos.Create(nil); try consumos_gastos.ShowModal(); finally consumos_gastos.Free; end; end; procedure TBASE.Controladoresdecalidad1Click(Sender: TObject); begin cc_controlproducto := Tcc_controlproducto.Create(nil); try cc_controlproducto.ShowModal; finally cc_controlproducto.Free; end; end; procedure TBASE.Controlcmarasfrigorificas1Click(Sender: TObject); begin cc_camaras := Tcc_camaras.Create(nil); try cc_camaras.ShowModal; finally cc_camaras.Free; end; end; procedure TBASE.Controldebsculas1Click(Sender: TObject); begin cc_basculas := Tcc_basculas.Create(nil); try cc_basculas.ShowModal; finally cc_basculas.Free; end; end; procedure TBASE.ControldeProduccindeAlmacen1Click(Sender: TObject); begin controlproduccion := Tcontrolproduccion.Create(nil); try controlproduccion.ShowModal(); finally controlproduccion.Free; end; end; procedure TBASE.Controldeutensilios1Click(Sender: TObject); begin cc_utensilios := Tcc_utensilios.Create(nil); try cc_utensilios.ShowModal; finally cc_utensilios.Free; end; end; procedure TBASE.Controlhorario1Click(Sender: TObject); begin ticados := Tticados.Create(nil); try ticados.ShowModal(); // ticados.Show(); // ticados.SetFocus; finally ticados.Free; end; end; procedure TBASE.CuentasBancarias1Click(Sender: TObject); begin fcuentas_bancarias := Tfcuentas_bancarias.Create(nil); try fcuentas_bancarias.ShowModal; finally fcuentas_bancarias.Free; end; end; procedure TBASE.PageControl2Change(Sender: TObject); begin if PageControl2.TabIndex = 2 then begin cdesde.Date := dmestadisticas.qcampanyasfechainicio.AsDateTime; chasta.Date := dmestadisticas.qcampanyasfechafin.AsDateTime; end; end; procedure TBASE.PageDatosEmpresaChange(Sender: TObject); var i: Integer; begin if PageDatosEmpresa.TabIndex = 1 then begin Pagedatos.ActivePageIndex := 0; dm.qseries.Open; end; if PageDatosEmpresa.TabIndex = 2 then begin dm.qmateriasprimas2.Close; dm.qmprimascompuestas.Close; dm.qgenericas.Close; dm.qmateriasprimas2.Open; dm.qmprimascompuestas.Open; dm.qgenericas.Open; end; if PageDatosEmpresa.TabIndex = 3 then begin dm.qalmacenes.Close; dm.qalmacenesaux.Close; dm.qalmacenes.Open; dm.qalmacenesaux.Open; end; if PageDatosEmpresa.TabIndex = 4 then begin dm.qalmacenes.Open; dm.qalmacenesaux.Open; dm.talmacenes.Open; end; if PageDatosEmpresa.TabIndex = 5 then begin dmestadisticas.qcampanyas.Open; dm.qparcelas.Open; end; if PageDatosEmpresa.TabIndex = 6 then begin dmestadisticas.qcampanyas.Open; dm.qparcelas.close; dm.qparcelas.Open; dm.qparcelas.First; dmestadisticas.qproduccion.Open; dmproduccion.qproduccion_detalles.Open; dmestadisticas.qsalidas.Open; dmestadisticas.qsalidasdetalles.Open; dmestadisticas.qdesechos.Open; dmestadisticas.qdesechosdetalles.Open; qsocios2.Open; end; if PageDatosEmpresa.TabIndex = 7 then begin dm.qcampanyas.Refresh; dm.qcampanyas_aux.Open; dm.qcampanyas.Refresh; dm.qcampanyasparcela.Open; dm.qcampanyasparcela.Refresh; end; if PageDatosEmpresa.TabIndex = 8 then begin dm.qalmacenes.Open; dm.qalmacenesaux.Open; dm.talmacenes.Open; dm.ttipotrabajo.Open; end; if PageDatosEmpresa.TabIndex = 9 then begin dm.qarticulosalmacen.Open; dm.tarticulosalmacen.Open; end; end; procedure TBASE.PageDatosEmpresaEnter(Sender: TObject); begin if PageDatosEmpresa.TabIndex = 1 then begin Pagedatos.ActivePageIndex := 0; end; end; procedure TBASE.PageNominasChange(Sender: TObject); var fdesde, fhasta, filtro, filtro2, filtro3: string; anyo, mes, dia: word; begin if PageNominas.TabIndex = 6 then begin // decodedate(date,anyo,mes,dia); // nomfechahasta.Date:=date; // PTfecha_desde.Date:=date-30;//ssstttrtodate('01/01/'+floattostr(anyo)); // dm.TFirmas.Open; dm.qpartes_diarios.Open; dm.qFirmas2.SQL.Clear; dm.qFirmas2.SQL.Add('select * from firmas where id=-1'); dm.qFirmas2.Open; // dm.qfirmas.Close; // dm.qfirmas.MasterSource:=dm.dspartes_diarios; // dm.qfirmas.Open; end; if PageNominas.TabIndex = 4 then begin dm.qparcela2.Open; end; if PageNominas.TabIndex = 5 then begin filtro := ''; filtro2 := ''; filtro3 := ''; decodedate(nomlttdesde.Date, anyo, mes, dia); fdesde := floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia); filtro := ' where id in (select distinct(typework) from trabajo_diario where fecha>=' + '''' + fdesde + ''''; filtro2 := ' where id in (select distinct(idt) from trabajo_diario td,tipo_trabajo a where td.typework=a.id and a.seleccionado=1 and fecha>=' + '''' + fdesde + ''''; filtro3 := ' where td.idt=t.id and td.typework=a.id and a.seleccionado=1 and t.seleccionado=1 and fecha>=' + '''' + fdesde + ''''; decodedate(nomltthasta.Date, anyo, mes, dia); fhasta := floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia); filtro := filtro + ' and fecha<=' + '''' + fhasta + ''''; filtro := filtro + ') order by id'; filtro2 := filtro2 + ' and fecha<=' + '''' + fhasta + ''''; filtro2 := filtro2 + ') order by nombre'; filtro3 := filtro3 + ' and fecha<=' + '''' + fhasta + ''''; filtro3 := filtro3 + ' group by idt,trabajador,typework order by typework,trabajador'; dm.qparcela2.Close; dm.qparcela2.SQL.Clear; dm.qparcela2.SQL.Add('select * from parcelas order by codpar'); dm.qparcela2.Open; dm.qtipotrabajo2.Close; dm.qtipotrabajo2.SQL.Clear; dm.qtipotrabajo2.SQL.Add('select id,seleccionado from tipo_trabajo ' + filtro); dm.qtipotrabajo2.Open; dm.qtrabajadores3.Close; dm.qtrabajadores3.SQL.Clear; dm.qtrabajadores3.SQL.Add('select id,nombre,seleccionado from trabajadores ' + filtro2); dm.qtrabajadores3.Open; dm.qlistadotrabajos.Close; dm.qlistadotrabajos.SQL.Clear; dm.qlistadotrabajos.SQL.Add ('select idt,trabajador,typework,sum(qhoras) as horas,sum(qhoras*td.precio) as total from trabajo_diario td,tipo_trabajo a,trabajadores t ' + filtro3); dm.qlistadotrabajos.Open; end; if PageNominas.TabIndex = 4 then begin filtro := ''; filtro2 := ''; filtro3 := ''; decodedate(nomlhdesde.Date, anyo, mes, dia); fdesde := floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia); filtro := ' where codart in (select distinct(articulo) from trabajo_diario where fecha>=' + '''' + fdesde + ''''; filtro2 := ' where id in (select distinct(idt) from trabajo_diario td,articulos a where td.articulo=a.codart and a.seleccionado=1 and fecha>=' + '''' + fdesde + ''''; filtro3 := ' where td.idt=t.id and td.articulo=a.codart and a.seleccionado=1 and t.seleccionado=1 and fecha>=' + '''' + fdesde + ''''; decodedate(nomlhhasta.Date, anyo, mes, dia); fhasta := floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia); filtro := filtro + ' and fecha<=' + '''' + fhasta + ''''; filtro := filtro + ') order by codart'; filtro2 := filtro2 + ' and fecha<=' + '''' + fhasta + ''''; filtro2 := filtro2 + ') order by nombre'; filtro3 := filtro3 + ' and fecha<=' + '''' + fhasta + ''''; filtro3 := filtro3 + ' group by idt,trabajador,articulo order by articulo,trabajador'; dm.qtipohoras2.Close; dm.qtipohoras2.SQL.Clear; dm.qtipohoras2.SQL.Add('select codart,seleccionado from articulos ' + filtro); dm.qtipohoras2.Open; dm.qtrabajadores2.Close; dm.qtrabajadores2.SQL.Clear; dm.qtrabajadores2.SQL.Add('select id,nombre,seleccionado from trabajadores ' + filtro2); dm.qtrabajadores2.Open; dm.qlistadohoras.Close; dm.qlistadohoras.SQL.Clear; dm.qlistadohoras.SQL.Add ('select idt,trabajador,articulo,sum(qhoras) as horas,sum(qhoras*a.equivalenciahoras) as horas2,sum(qhoras*td.precio) as total,sum((qhoras/a.equivalenciahoras)*td.precio) as total2 from trabajo_diario td,articulos a,trabajadores t ' + filtro3); dm.qlistadohoras.Open; end; end; procedure TBASE.PageproduccionChange(Sender: TObject); var anyo, mes, dia: word; fdesde, fhasta, ffecha, vmesa, vmprima, vproducto: string; begin decodedate(fprodesde.Date, anyo, mes, dia); fdesde := inttostr(anyo) + '-' + inttostr(mes) + '-' + inttostr(dia); // decodedate(fprohasta.Date, anyo, mes, dia); // fhasta := inttostr(anyo) + '-' + inttostr(mes) + '-' + inttostr(dia); if Pageproduccion.TabIndex = 0 then begin Panel49.Visible := true; Timer1.Enabled := false; dm.qmesas.Close; dm.qmesas.SQL.Clear; dm.qmesas.SQL.Add('select distinct(mesa) from movimiento_mesas where fecha=' + '''' + fdesde + '''' + ' order by mesa'); dm.qmesas.Open; dm.qmovimientomesas.Close; dm.qmovimientomesas.SQL.Clear; dm.qmovimientomesas.SQL.Add('select * from movimiento_mesas where fecha=' + '''' + fdesde + '''' + ' order by trabajador,entrada_real'); dm.qmovimientomesas.Open; end; if Pageproduccion.TabIndex = 1 then begin Timer1.Enabled := false; Panel49.Visible := true; tjornales.Open; dm.qmesas.Close; dm.qmesas.SQL.Clear; dm.qmesas.SQL.Add('select distinct(mesa) from movimiento_mesas where fecha=' + '''' + fdesde + '''' + 'order by mesa'); dm.qmesas.Open; dm.qnominasproduccion.Close; dm.qnominasproduccion.SQL.Clear; dm.qnominasproduccion.SQL.Add('select * from trabajo_diario where fecha=' + '''' + fdesde + '''' + ' and idt in ('); dm.qnominasproduccion.SQL.Add('select idt from movimiento_mesas where mesa=' + '''' + dm.qmesasmesa.AsString + '''' + ' and fecha=' + '''' + fdesde + '''' + ') order by idt'); dm.qnominasproduccion.Open; { dm.qnominasproduccion.Close; dm.qnominasproduccion.sql.Clear; dm.qnominasproduccion.sql.Add('select td.idt,td.fecha,td.id,td.trabajador,td.typework,td.articulo,qhoras,estado,origen from trabajo_diario td, movimiento_mesas mm where td.fecha>='+''''+fdesde+''''+' and td.fecha<='+''''+fhasta+''''+' and td.idt=mm.idt'); dm.qnominasproduccion.sql.Add(' and mm.fecha>='+''''+fdesde+''''+' and mm.fecha<='+''''+fhasta+''''+' and mm.trabajador=td.trabajador order by idt'); dm.qnominasproduccion.open; } end; if Pageproduccion.TabIndex = 2 then begin Panel49.Visible := true; Timer1.Enabled := false; dm.qmesas.Close; dm.qmesas.SQL.Clear; dm.qmesas.SQL.Add('select distinct(mesa) from movimiento_mesas where fecha=' + '''' + fdesde + '''' + ' order by mesa'); dm.qmesas.Open; dm.qpersonasmesas.Close; dm.qpersonasmesas.SQL.Clear; dm.qpersonasmesas.SQL.Add ('select distinct(idt),trabajador,mesa from movimiento_mesas where fecha=' + '''' + fdesde + '''' + ' order by trabajador'); dm.qpersonasmesas.Open; dm.qpartes_diarios2.Open; dm.qpartes_diarios.Open; dm.qFirmas2.SQL.Clear; dm.qFirmas2.SQL.Add('select * from firmas where id=-1'); dm.qFirmas2.Open; // dm.qfirmas.Close; // dm.qfirmas.MasterSource:=dm.dsqpartesdiarios2; // dm.qfirmas.Open; end; if Pageproduccion.TabIndex = 3 then begin Panel49.Visible := false; Timer1.Enabled := true; dm.qproduccion.Close; dm.qproduccion.prepare; dm.qproduccion.ParamByName('fecha').AsDate:=fprodesde.Date; dm.qproduccion.Open; end; if Pageproduccion.TabIndex = 4 then begin Timer1.Enabled := true; Panel49.Visible := false; dm.qproduccionmesa2.Close; dm.qproduccionmesa2.Prepare; dm.qproduccionmesa2.ParamByName('FECHA').AsDate:=strtodate('01/01/1900');//fprodesde.Date; { dm.qproduccionmesa2.SQL.Clear; dm.qproduccionmesa2.SQL.Add ('select p.mesa,p.cantidad,h.horasmesa,p.cantidad/h.horasmesa as cantidadhora from (SELECT mesa,sum(peso_real-tara) as cantidad,idt,embasadora FROM produccion where fecha=' + '''' + fdesde + '''' + ' group by mesa order by mesa) as p '); dm.qproduccionmesa2.SQL.Add(' inner join '); dm.qproduccionmesa2.SQL.Add (' (select mesa,sum(horas) as horasmesa from ( select mesa,sum(timestampdiff(minute,entrada_real,SALIDA_REAL)/60) as horas from movimiento_mesas where fecha=' + '''' + fdesde + '''' + ' and SALIDA_REAL is NOT null group by mesa '); dm.qproduccionmesa2.SQL.Add(' union ALL '); dm.qproduccionmesa2.SQL.Add (' select mesa,sum(timestampdiff(minute,entrada_real,now())/60) as horas from movimiento_mesas where fecha=' + '''' + fdesde + '''' + ' and SALIDA_REAL is null group by mesa ) as grupo GROUP by mesa) as h'); dm.qproduccionmesa2.SQL.Add(' on p.mesa=h.mesa');} dm.qproduccionmesa2.Open; dm.qproduccionmesa2.Prepare; dm.qproduccionmesa2.ParamByName('FECHA').AsDate:=fprodesde.Date; dm.qproduccionmesa2.Refresh; end; if Pageproduccion.TabIndex = 5 then begin Timer1.Enabled := true; Panel49.Visible := false; qproduccionmesas.Close; qproduccionmesas.Prepare; qproduccionmesas.ParamByName('FECHA').AsDate := fprodesde.Date; qproduccionmesas.Open; qproduccionmatprima.Close; qproduccionmatprima.Prepare; qproduccionmatprima.ParamByName('FECHA').AsDate := fprodesde.Date; qproduccionmatprima.Open; qproduccionproducto.Close; qproduccionproducto.Prepare; qproduccionproducto.ParamByName('FECHA').AsDate := fprodesde.Date; qproduccionproducto.Open; if comboprodmesas.KeyValue = null then vmesa := '%' else vmesa := comboprodmesas.KeyValue; if comboprodmprimas.KeyValue = null then vmprima := '%' else vmprima := comboprodmprimas.KeyValue; if comboprodproducto.KeyValue = null then vproducto := '%' else vproducto := comboprodproducto.KeyValue; dm.qproduccionmesa.Close; dm.qproduccionmesa.Prepare; dm.qproduccionmesa.ParamByName('FECHA').AsDate := fprodesde.Date; dm.qproduccionmesa.ParamByName('MESA').AsString := vmesa; dm.qproduccionmesa.ParamByName('MPRIMA').AsString := vmprima; dm.qproduccionmesa.ParamByName('PRODUCTO').AsString := vproducto; dm.qproduccionmesa.ParamByName('HDESDE').Asinteger:=hdesde.ItemIndex; dm.qproduccionmesa.ParamByName('HHASTA').Asinteger:=hhasta.ItemIndex; dm.qproduccionmesa.Open; end; if Pageproduccion.TabIndex = 6 then begin Timer1.Enabled := true; Panel49.Visible := false; dm.qproduccionhora.Close; dm.qproduccionhora.SQL.Clear; dm.qproduccionhora.SQL.Add ('select hour(hora) as desde,hour(hora)+1 as hasta,sum(peso_real-tara) as cantidad from produccion where fecha>=' + '''' + fdesde + '''' + ' group by hour(hora)'); dm.qproduccionhora.Open; end; { if pageproduccion.TabIndex=7 then begin timer1.Enabled:=false; panel49.Visible:=false; end; } if Pageproduccion.TabIndex = 7 then begin Timer1.Enabled := false; Panel49.Visible := false; dm.qcontrolproduccion.Close; dm.qcontrolproduccion.Prepare; dm.qcontrolproduccion.ParamByName('fecha').AsDate:=fprodesde.Date; dm.qcontrolproduccion.Open; dmproduccion.qpartesdiarios.Open; dmproduccion.qrestos_dia.Open; end; if Pageproduccion.TabIndex = 8 then begin qlotesdia.Close; qlotesdia.Prepare; qlotesdia.ParamByName('fecha').AsDatetime:=dmproduccion.qpartesdiariosfecha.AsDateTime; qlotesdia.ParamByName('almacen').AsInteger:=dmproduccion.qpartesdiariosalmacen.AsInteger; qlotesdia.ParamByName('empresa').AsInteger:=dmproduccion.qpartesdiariosidempresa.AsInteger; qlotesdia.Open; Panel49.Visible := false; end; if Pageproduccion.TabIndex = 9 then begin Panel49.Visible := false; // dmproduccion.qentradasgrupo.Open; dmproduccion.qpartesdiarios.Open; dmproduccion.qentradas.Open; dmproduccion.qentradas2.Open; // dmproduccion.qsalidas.Open; dmproduccion.qsalidaslotes.Open; dmproduccion.qsalidas2.Open; end; end; procedure TBASE.PageproduccionEnter(Sender: TObject); begin // btprodaceptar.Click; if Pageproduccion.TabIndex = 9 then begin Panel49.Visible := false; dmproduccion.qpartesdiarios.Open; // dmproduccion.qentradas.Open; // dmproduccion.qentradas2.Open; // dmproduccion.qsalidaslotes.Open; // dmproduccion.qsalidas2.Open; end; end; procedure TBASE.pagnomfechadesdeChange(Sender: TObject); var anyo, mes, dia: word; filtro, fdesde, fhasta: string; begin filtro := ''; decodedate(pagnomfechadesde.Date, anyo, mes, dia); fdesde := floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia); filtro := ' where activo=1 and fecha>=' + '''' + fdesde + ''''; decodedate(pagnomfechahasta.Date, anyo, mes, dia); fhasta := floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia); filtro := filtro + ' and fecha<=' + '''' + fhasta + ''''; filtro := filtro + ' order by fecha desc'; dm.qnominas.Close; dm.qnominas.SQL.Clear; dm.qnominas.SQL.Add('select * from nominas ' + filtro); dm.qnominas.Open; end; procedure TBASE.pagnomfechahastaChange(Sender: TObject); var anyo, mes, dia: word; filtro, fdesde, fhasta: string; begin filtro := ''; decodedate(pagnomfechadesde.Date, anyo, mes, dia); fdesde := floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia); filtro := ' where activo=1 and fecha>=' + '''' + fdesde + ''''; decodedate(pagnomfechahasta.Date, anyo, mes, dia); fhasta := floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia); filtro := filtro + ' and fecha<=' + '''' + fhasta + ''''; filtro := filtro + ' order by fecha desc'; dm.qnominas.Close; dm.qnominas.SQL.Clear; dm.qnominas.SQL.Add('select * from nominas ' + filtro); dm.qnominas.Open; end; procedure TBASE.Panel71Click(Sender: TObject); var anyo, mes, dia: word; filtro, fdesde, fhasta: string; begin filtro := ''; decodedate(pagnomfechadesde.Date, anyo, mes, dia); fdesde := floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia); filtro := ' where activo=0 and fecha>=' + '''' + fdesde + ''''; decodedate(pagnomfechahasta.Date, anyo, mes, dia); fhasta := floattostr(anyo) + '-' + floattostr(mes) + '-' + floattostr(dia); filtro := filtro + ' and fecha<=' + '''' + fhasta + ''''; filtro := filtro + ' order by fecha asc'; dm.qnominas.Close; dm.qnominas.SQL.Clear; dm.qnominas.SQL.Add('select * from nominas ' + filtro); dm.qnominas.Open; end; procedure TBASE.PedidosClientes1Click(Sender: TObject); begin pedidos := Tpedidos.Create(nil); try pedidos.ShowModal(); finally pedidos.Free; end; end; procedure TBASE.PEmpleadosClick(Sender: TObject); var idt, filtrojornales, filtroanticipos: String; ianyo, imes, idia: word; begin decodedate(Date, ianyo, imes, idia); TMES.ItemIndex := imes; Tanyo.ItemIndex := ianyo - 2015 + 1; tmes2.ItemIndex := imes; tanyo2.ItemIndex := ianyo - 2015 + 1; qempleados.Open; 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); if TESTADO.ItemIndex <> 0 then filtrojornales := filtrojornales + ' and estado=' + TESTADO.Text; filtrojornales := filtrojornales + ' order by id desc'; qjornales.Close; qjornales.SQL.Clear; qjornales.SQL.Add('select * from trabajo_diario ' + filtrojornales); qjornales.Open; filtroanticipos := 'where idt=' + idt; if tanyo2.ItemIndex <> 0 then filtroanticipos := filtroanticipos + ' and year(fecha)=' + tanyo2.Text; if tmes2.ItemIndex <> 0 then filtroanticipos := filtroanticipos + ' and month(fecha)=' + inttostr(tmes2.ItemIndex); if testado2.ItemIndex <> 0 then filtroanticipos := filtroanticipos + ' and estado=' + testado2.Text; filtroanticipos := filtroanticipos + ' order by id desc'; dm.qanticipos.Close; dm.qanticipos.SQL.Clear; dm.qanticipos.SQL.Add('select * from anticipos ' + filtroanticipos); dm.qanticipos.Open; templeados.filter := 'id=' + idt; templeados.filtered := true; templeados.Open; PageEmpleados.ActivePageIndex := 0; vtactivo := 0; PDEmpleados.Visible := not PDEmpleados.Visible; PGeneral.Visible := false; qempleados.Open; dm.qparcelas.Open; dm.qtrabajos.Open; dm.qtipohoras.Open; falta.Date := Date; fbaja.Date := Date; end; procedure TBASE.Presentaciones1Click(Sender: TObject); begin presentaciones := Tpresentaciones.Create(nil); try presentaciones.ShowModal(); finally presentaciones.Free; end; end; procedure TBASE.Proveedores1Click(Sender: TObject); begin proveedores := Tproveedores.Create(nil); try proveedores.ShowModal(); finally proveedores.Free; end; end; procedure TBASE.Puestosdetrabajo1Click(Sender: TObject); begin fpuestos_trabajo := Tfpuestos_trabajo.Create(nil); try fpuestos_trabajo.ShowModal; finally fpuestos_trabajo.Free; end; end; procedure TBASE.qempleadosAfterOpen(DataSet: TDataSet); begin ltotalgrupo.Caption := 'Total grupo: ' + inttostr(qempleados.RecordCount); ltotalgrupo2.Caption := 'Total grupo: ' + inttostr(qempleados.RecordCount); end; procedure TBASE.qempleadosBeforeOpen(DataSet: TDataSet); var filtro: string; begin if filtrotrabajadores <> '' then begin if vtactivo <> 0 then begin filtro := filtro + ' where (nombre like(' + '''' + '%' + filtrotrabajadores + '%' + '''' + ') or (id=' + '''' + filtrotrabajadores + '''' + ')) and activo=' + inttostr(vtactivo) end else begin filtro := filtro + ' where (nombre like(' + '''' + '%' + filtrotrabajadores + '%' + '''' + ') or (id=' + '''' + filtrotrabajadores + '''' + '))'; end; if chktodosempleados.Checked then begin // filtro:=filtro+' and mostrar=1 '; end else begin filtro := filtro + ' and mostrar=1 '; end; end; if filtrotrabajadores = '' then begin if vtactivo <> 0 then begin filtro := filtro + ' where activo=' + inttostr(vtactivo); if chktodosempleados.Checked then begin // filtro:=filtro+' and mostrar=1 '; end else begin filtro := filtro + ' and mostrar=1 '; end; end else begin filtro := ''; if chktodosempleados.Checked then begin // filtro:=' where mostrar=1 '; end else begin filtro := ' where mostrar=1 '; end; end; end; qempleados.SQL.Clear; qempleados.SQL.Add('select ide,id,nombre,seleccionado,nif from trabajadores ' + filtro + ' order by nombre') end; procedure TBASE.ratamientos1Click(Sender: TObject); begin tratamientos := Ttratamientos.Create(nil); try tratamientos.ShowModal(); finally tratamientos.Free; end; end; procedure TBASE.tratamientosBase1Click(Sender: TObject); begin tratamientosbase := Ttratamientosbase.Create(nil); try tratamientosbase.ShowModal(); finally tratamientosbase.Free; end; end; procedure TBASE.RecalculoStocksdearticuloscomponentes1Click(Sender: TObject); begin recalculostock := Trecalculostock.Create(nil); try recalculostock.ShowModal(); finally recalculostock.Free; end; end; procedure TBASE.Regmenesdecotizacin1Click(Sender: TObject); begin fregimen_cotizacion := Tfregimen_cotizacion.Create(nil); try fregimen_cotizacion.ShowModal; finally fregimen_cotizacion.Free; end; end; procedure TBASE.Regularizarmaterialauxiliar1Click(Sender: TObject); var id, tmultiplicador, tara, costo: string; multiplicador: real; begin qaux.SQL.Clear; qaux.SQL.Add ('select DISTINCT(idempresa),id,idea,num_palets,id_palet,mprima,recuperar_envases from ea_pesadas where (idempresa,id,idea) not in (select DISTINCT(ide),idea,idea2 from ea_materiales) and fecha>=(select max(fecha) from control_stock) and iddestino '); qaux.SQL.Add(' in (select id from almacenes where final=1 or produccion=1)'); qaux.Open; if qaux.RecordCount > 0 then begin qregularizar.Prepare; while not qaux.Eof do begin qaux2.SQL.Clear; qaux2.SQL.Add('select compuesto from materias_primas where idempresa=' + qaux.Fields[0].AsString + ' and id=' + '''' + qaux.Fields[5] .AsString + ''''); qaux2.Open; if qaux2.Fields[0].AsInteger = 0 then multiplicador := 1 else multiplicador := 0.5; id := qaux.Fields[1].AsString; qaux2.Close; qaux2.SQL.Clear; qaux2.SQL.Add('delete from ea_materiales where ide=' + qaux.Fields[0] .AsString + ' and idea=' + qaux.Fields[1].AsString + ' and idea2=' + qaux.Fields[2].AsString); qaux2.ExecSQL; qaux2.Close; qaux2.SQL.Clear; qaux2.SQL.Add('select * from lotes_pesadas where ide=' + qaux.Fields[0] .AsString + ' and idea=' + qaux.Fields[1].AsString + ' and idea2=' + qaux.Fields[2].AsString); qaux2.Open; if qaux2.RecordCount > 0 then begin qregularizar.ParamByName('IDEMPRESA').AsInteger := qaux.Fields[0].AsInteger; qregularizar.ParamByName('ID').AsInteger := qaux.Fields[1].AsInteger; qregularizar.ParamByName('IDEA').AsInteger := qaux.Fields[2].AsInteger; qregularizar.ParamByName('NUMPALETS').AsInteger := qaux.Fields[3].AsInteger; qregularizar.ParamByName('IDPALET').AsString := qaux.Fields[4].AsString; qregularizar.ParamByName('MULTIPLICADOR').AsFloat := multiplicador; qregularizar.ExecSQL; { qregularizar.Close; qregularizar.SQL.Clear; qregularizar.SQL.Add('insert into ea_materiales '); qregularizar.SQL.Add('select idempresa,'+qpesadasid.AsString+' as idea,'+qpesadasidea.AsString+' as idea2,idarticulof,sum(cantidadtotal) as cantidadtotal,sum(pesototal) as pesototal,null,sum(preciototal) as preciototal,0 as recuperado from '); //// materiales de los envases qregularizar.SQL.Add('(SELECT ac.idempresa,ac.idarticuloalmacen,ac.idarticulof,(ac.cantidad*lp.cajas*'+tmultiplicador+') as cantidadtotal,(ac.peso*lp.cajas*'+tmultiplicador+') as pesototal,(ac.preciocoste*lp.cajas*'+tmultiplicador+') as preciototal '); qregularizar.SQL.Add(' FROM articulos_componentes ac,(SELECT lp.ide,lp.idea,lp.idea2,sum(cajas) as cajas,aa.id as id_envase FROM lotes_pesadas lp,articulos_almacen aa where aa.ide=lp.ide and aa.codigo=lp.id_envase '); qregularizar.SQL.Add(' and lp.ide='+qpesadasidempresa.AsString+' and lp.idea='+qpesadasid.AsString+' and lp.idea2='+qpesadasidea.AsString+' group by lp.id_envase ) as lp '); qregularizar.SQL.Add(' where ac.idempresa=lp.ide and ac.idarticuloalmacen=lp.id_envase '); qregularizar.SQL.Add(' union ALL'); // materiales de los formatos qregularizar.SQL.Add(' SELECT ac.ide,ac.idcfg,ac.idaf,(ac.cantidad*lp.cajas*'+tmultiplicador+') as cantidadtotal,(ac.peso*lp.cajas*'+tmultiplicador+') as pesototal,(ac.coste*lp.cajas*'+tmultiplicador+') as preciototal FROM '); qregularizar.SQL.Add(' configuraciones_detalle ac,(SELECT lp.ide,lp.idea,lp.idea2,sum(cajas) as cajas,aa.id as id_envase FROM lotes_pesadas lp, '); qregularizar.SQL.Add(' configuraciones aa where aa.ide=lp.ide and aa.id=lp.id_formato and lp.ide='+qpesadasidempresa.AsString+' and lp.idea='+qpesadasid.AsString+' and lp.idea2='+qpesadasidea.AsString+' group by lp.id_envase ) as lp '); qregularizar.SQL.Add(' where ac.ide=lp.ide and ac.idcfg=lp.id_envase '); qregularizar.SQL.Add(' union ALL'); //// materiales de los palets qregularizar.SQL.Add(' SELECT ac.idempresa,ac.idarticuloalmacen,ac.idarticulof,(ac.cantidad*'+qpesadasnum_palets.AsString+') as cantidadtotal,(ac.cantidad*ac.peso*'+qpesadasnum_palets.AsString+') as pesototal,(ac.cantidad*ac.preciocoste*'+qpesadasnum_palets.AsString+') as preciototal'); qregularizar.SQL.Add(' FROM articulos_componentes ac where ac.idempresa='+qpesadasidempresa.AsString+' and ac.idarticuloalmacen=(select id from articulos_almacen where codigo='+''''+qpesadasid_palet.AsString+''''+' )'); qregularizar.SQL.Add(' ) as ea_materiales_tmp group by idarticulof'); qregularizar.execsql; } end; if qaux.Fields[6].AsInteger = 1 then begin qaux2.SQL.Clear; qaux2.SQL.Add('update ea_materiales ea set recuperado=-1 where ea.ide=' + qaux.Fields[0].AsString + ' and ea.idea=' + qaux.Fields[1].AsString + ' and ea.idea2=' + qaux.Fields[2].AsString); qaux2.ExecSQL; end else begin qaux2.SQL.Clear; qaux2.SQL.Add('update ea_materiales ea set recuperado=0 where ea.ide=' + qaux.Fields[0].AsString + ' and ea.idea=' + qaux.Fields[1].AsString + ' and ea.idea2=' + qaux.Fields[2].AsString); qaux2.ExecSQL; end; qaux2.SQL.Clear; qaux2.SQL.Add('select sum(peso),sum(precio) from ea_materiales where ide=' + qaux.Fields[0].AsString + ' and idea=' + qaux.Fields[1].AsString + ' and idea2=' + qaux.Fields[2].AsString); qaux2.Open; tara := qaux2.Fields[0].AsString; costo := qaux2.Fields[1].AsString; tara := stringreplace(tara, ',', '.', [rfReplaceAll, rfIgnoreCase]); costo := stringreplace(costo, ',', '.', [rfReplaceAll, rfIgnoreCase]); qaux2.SQL.Clear; qaux2.SQL.Add('update ea_pesadas ea set id_palet2=' + '''' + 'TRIGGER_ON' + '''' + ',tara=' + tara + ',costo_materiales=' + costo + ' where ea.idempresa=' + qaux.Fields[0].AsString + ' and ea.id=' + qaux.Fields[1].AsString + ' and ea.idea=' + qaux.Fields[2].AsString); qaux2.ExecSQL; { if qpesadas.State in [dsbrowse] then qpesadas.Edit; qpesadasid_palet2.Value:='TRIGGER_ON'; qpesadastara.Value:=qaux.Fields[0].AsFloat; qpesadascosto_materiales.Value:=qaux.Fields[1].AsFloat; qpesadas.Post; } qaux.Next; end; end; end; procedure TBASE.Salir1Click(Sender: TObject); begin ExitProcess(0); end; procedure TBASE.SociosProductores1Click(Sender: TObject); begin sociosproductores := Tsociosproductores.Create(nil); try sociosproductores.ShowModal(); finally sociosproductores.Free; end; end; procedure TBASE.Stockdealmacen1Click(Sender: TObject); begin stocksalmacen := Tstocksalmacen.Create(nil); try stocksalmacen.ShowModal(); finally stocksalmacen.Free; end; end; procedure TBASE.Nominaspag4Enter(Sender: TObject); begin if not dm.qnominas.Active then begin dm.qnominas.Open; end else dm.qnominas.Refresh; if not dm.tnominasdetalle.Active then begin dm.tnominasdetalle.Open; end else dm.tnominasdetalle.Refresh; end; procedure TBASE.TabJornalesEnter(Sender: TObject); var idt, filtrojornales, filtroanticipos: string; begin Label46.Caption := templeadosnombre.AsString; if qempleados.RecordCount > 0 then begin idt := qempleadosid.AsString; // templeados.Close; // idt:=qempleadosid.asstring; // templeados.Filter:='id='+idt; // templeados.Filtered:=true; templeados.Locate('id', idt, [locaseinsensitive]); // templeados.Open; Label46.Caption := templeadosnombre.AsString; Label10.Caption := qempleadosnombre.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); if TESTADO.ItemIndex <> 0 then filtrojornales := filtrojornales + ' and estado=' + TESTADO.Text; filtrojornales := filtrojornales + ' order by fecha desc'; qjornales.Close; qjornales.SQL.Clear; qjornales.SQL.Add('select * from trabajo_diario ' + filtrojornales); qjornales.Open; filtroanticipos := 'where idt=' + idt; if tanyo2.ItemIndex <> 0 then filtroanticipos := filtroanticipos + ' and year(fecha)=' + tanyo2.Text; if tmes2.ItemIndex <> 0 then filtroanticipos := filtroanticipos + ' and month(fecha)=' + inttostr(tmes2.ItemIndex); if testado2.ItemIndex <> 0 then filtroanticipos := filtroanticipos + ' and estado=' + testado2.Text; filtroanticipos := filtroanticipos + ' order by fecha desc'; dm.qanticipos.Close; dm.qanticipos.SQL.Clear; dm.qanticipos.SQL.Add('select * from anticipos ' + filtroanticipos); dm.qanticipos.Open; end; end; procedure TBASE.TabSheet21Enter(Sender: TObject); begin qlistadoporgrupo.close; vfechadesdelg.Date:=date(); vfechahastalg.Date:=date(); end; procedure TBASE.TanyoChange(Sender: TObject); var idt, filtrojornales: string; begin qempleados.Open; 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); if TESTADO.ItemIndex <> 0 then filtrojornales := filtrojornales + ' and estado=' + TESTADO.Text; filtrojornales := filtrojornales + ' order by id desc'; qjornales.Close; qjornales.SQL.Clear; qjornales.SQL.Add('select * from trabajo_diario ' + filtrojornales); qjornales.Open; end; procedure TBASE.tbjornadasEnter(Sender: TObject); begin qticados.Close; vdesdejornadas.Date:=date(); vhastajornadas.Date:=date(); end; procedure TBASE.tbuscarChange(Sender: TObject); begin filtrotrabajadores := tbuscar.Text; qempleados.Close; qempleados.Open; end; procedure TBASE.bcaceptarClick(Sender: TObject); begin dm.qcampanyas.post; // dm.qparcelas.refresh; // dm.qparcelas.first; bcanadir.Enabled := true; bcmodificar.Enabled := true; bcborrar.Enabled := true; bccancelar.Enabled := false; bcaceptar.Enabled := false; dm.qcampanyasparcela.Refresh; dm.qlincampanyas.Refresh; dm.qcampanyas_aux.Refresh; end; procedure TBASE.bcanadirClick(Sender: TObject); begin dm.qcampanyas.Append; DBEdit89.SetFocus; bcanadir.Enabled := false; bcmodificar.Enabled := false; bcborrar.Enabled := false; bccancelar.Enabled := true; bcaceptar.Enabled := true; end; procedure TBASE.TESTADOChange(Sender: TObject); var idt, filtrojornales: string; begin qempleados.Open; 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); if TESTADO.ItemIndex <> 0 then filtrojornales := filtrojornales + ' and estado=' + TESTADO.Text; filtrojornales := filtrojornales + ' order by id desc'; qjornales.Close; qjornales.SQL.Clear; qjornales.SQL.Add('select * from trabajo_diario ' + filtrojornales); qjornales.Open; end; procedure TBASE.Timer1Timer(Sender: TObject); begin if Pageproduccion.TabIndex = 8 then begin { if dm.talmacenes.active then dm.talmacenes.Refresh; if dm.qalmacenes.active then dm.qalmacenes.Refresh; if dmestadisticas.qproduccion_almacen.active then dmestadisticas.qproduccion_almacen.Refresh; } end; if Pageproduccion.TabIndex = 0 then begin if dm.qmovimientomesas.Active then dm.qmovimientomesas.Refresh else dm.qmovimientomesas.Active := true; end; if Pageproduccion.TabIndex = 1 then begin if dm.qnominasproduccion.Active then dm.qnominasproduccion.Refresh else dm.qnominasproduccion.Active := true; end; if Pageproduccion.TabIndex = 3 then begin if dm.qproduccion.Active then dm.qproduccion.Refresh else dm.qproduccion.Active := true; end; if Pageproduccion.TabIndex = 4 then begin dm.qproduccionmesa2.Prepare; dm.qproduccionmesa2.ParamByName('FECHA').AsDate:=fprodesde.Date; dm.qproduccionmesa2.refresh; //dbchart1.RefreshData; end; if Pageproduccion.TabIndex = 5 then begin if dm.qproduccionmesa.Active then dm.qproduccionmesa.Refresh else dm.qproduccionmesa.Active := true; end; if Pageproduccion.TabIndex = 6 then begin if dm.qproduccionhora.Active then dm.qproduccionhora.Refresh else dm.qproduccionhora.Active := true; end; if Pageproduccion.TabIndex = 7 then begin end; if Pageproduccion.TabIndex = 8 then begin end; if Pageproduccion.TabIndex = 9 then begin end; if Pageproduccion.TabIndex = 10 then begin { if dmproduccion.qpartesdiarios.Active then dmproduccion.qpartesdiarios.Refresh; // if dmproduccion.qentradasgrupo.Active then dmproduccion.qentradasgrupo.Refresh; if dmproduccion.qentradas.Active then dmproduccion.qentradas.Refresh; if dmproduccion.qentradas2.Active then dmproduccion.qentradas2.Refresh; if dmproduccion.qsalidas.Active then dmproduccion.qsalidas.Refresh; if dmproduccion.qsalidas2.Active then dmproduccion.qsalidas2.Refresh; } end; if Pageproduccion.TabIndex = 11 then begin end; if Pageproduccion.TabIndex = 12 then begin end; end; procedure TBASE.Timer2Timer(Sender: TObject); begin if dm.tempresaavisarstock.AsInteger = 1 then begin controlminimos := Tcontrolminimos.Create(nil); try Timer2.Enabled := false; controlminimos.ShowModal(); finally controlminimos.Free; Timer2.Enabled := true; end; end; end; procedure TBASE.tmes2Change(Sender: TObject); var idt, filtroanticipos: string; begin qempleados.Open; idt := qempleadosid.AsString; filtroanticipos := 'where idt=' + idt; if tanyo2.ItemIndex <> 0 then filtroanticipos := filtroanticipos + ' and year(fecha)=' + tanyo2.Text; if tmes2.ItemIndex <> 0 then filtroanticipos := filtroanticipos + ' and month(fecha)=' + inttostr(tmes2.ItemIndex); if testado2.ItemIndex <> 0 then filtroanticipos := filtroanticipos + ' and estado=' + testado2.Text; filtroanticipos := filtroanticipos + ' order by id desc'; dm.qanticipos.Close; dm.qanticipos.SQL.Clear; dm.qanticipos.SQL.Add('select * from anticipos ' + filtroanticipos); dm.qanticipos.Open; end; procedure TBASE.TMESChange(Sender: TObject); var idt, filtrojornales: string; begin qempleados.Open; 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); if TESTADO.ItemIndex <> 0 then filtrojornales := filtrojornales + ' and estado=' + TESTADO.Text; filtrojornales := filtrojornales + ' order by id desc'; qjornales.Close; qjornales.SQL.Clear; qjornales.SQL.Add('select * from trabajo_diario ' + filtrojornales); qjornales.Open; end; procedure TBASE.Utensilios1Click(Sender: TObject); begin utensilios := Tutensilios.Create(nil); try utensilios.ShowModal; finally utensilios.Free; end; end; procedure TBASE.VaciarClick(Sender: TObject); begin DBEdit7.Text := ''; end; procedure TBASE.Vidacomercial1Click(Sender: TObject); begin cc_vidacomercial := Tcc_vidacomercial.Create(nil); try cc_vidacomercial.ShowModal; finally cc_vidacomercial.Free; end; end; procedure TBASE.ZReadOnlyQuery1BeforeOpen(DataSet: TDataSet); var filtro: string; begin if filtrotrabajadores <> '' then begin if vtactivo <> 0 then begin filtro := filtro + ' where nombre like(' + '''' + filtrotrabajadores + '''' + ') or id like(' + '''' + filtrotrabajadores + '''' + ') and activo=' + inttostr(vtactivo); end else begin filtro := filtro + ' where nombre like(' + '''' + filtrotrabajadores + '''' + ') or id like(' + '''' + filtrotrabajadores + '''' + ')'; end; end; if filtrotrabajadores = '' then begin if vtactivo <> 0 then filtro := filtro + ' where activo=' + inttostr(vtactivo) else filtro := ''; end; qempleados.SQL.Clear; qempleados.SQL.Add('select id, nombre from trabajadores ' + filtro + ' order by nombre') end; procedure TBASE.AbonadosBase1Click(Sender: TObject); begin productosfitosanitarios := Tproductosfitosanitarios.Create(nil); try productosfitosanitarios.ShowModal(); finally productosfitosanitarios.Free; end; end; procedure TBASE.AlbaranesClientes1Click(Sender: TObject); begin albaranes := Talbaranes.Create(nil); try albaranes.ShowModal(); finally albaranes.Free; end; end; procedure TBASE.AppMessage(var Msg: Tmsg; Var Handled: Boolean); var actual: TWincontrol; begin if Msg.Message = WM_KEYDOWN then begin // esto es para controlar que con la flecha abajo se desplegen las // listas if Msg.wParam = VK_DOWN then begin actual := Screen.activecontrol; if actual is TDBLookupComboBox then if not TDBLookupComboBox(Screen.ActiveForm.activecontrol).listVisible then TDBLookupComboBox(Screen.ActiveForm.activecontrol).DropDown; // si utilizas las RX { if Actual is TRxDBLookupCombo then if not TRxDBLookupCombo(Screen.ActiveForm.ActiveControl).listVisible then TRxDBLookupCombo(Screen.ActiveForm.ActiveControl).DropDown; } if actual is TComboBox then SendMessage(TComboBox(Screen.ActiveForm.activecontrol).Handle, CB_SHOWDROPDOWN, -1, 0); if (actual is TCustomEdit) then Msg.wParam := VK_TAB; // se pueden añadir mas controles.... end; // y aqui es el control del intro. if Msg.wParam = VK_RETURN THEN begin actual := Screen.activecontrol; // para los edit. if (actual is TCustomEdit) and not(actual is TCustomMemo) then Msg.wParam := VK_TAB; // para los memo. Con ctrl + enter se salta de linea dentro del // memo, si solo es intro salta al siguiente control if (actual is TCustomMemo) and (HiWord(GetKeyState(VK_CONTROL)) = 0) then Msg.wParam := VK_TAB; // para los lookup if actual is TDBLookupComboBox then if not TDBLookupComboBox(actual).listVisible then Msg.wParam := VK_TAB; // Si utilizas las RX { if Actual is TRxDBLookupCombo then if not TRxDBLookupCombo(Actual).listVisible then Msg.wParam := VK_TAB; } // Los combobox if actual is TCustomComboBox then if not TCustomComboBox(actual).DroppedDown then Msg.wParam := VK_TAB; // el radiobutton if actual is TRadioButton then Msg.wParam := VK_TAB; // en el grid if actual is TDBGrid then if (TDBGrid(actual).ReadOnly) or (HiWord(GetKeyState(VK_CONTROL)) = 1) then Msg.wParam := VK_TAB; // o esto otro Con Ctrl + intro siguiente celda con // ctrl + shift + intro celda anterior // es complicado pero es por no liar con el intro solo // que siempre pasa de un control a otro. if actual is TDBGrid then begin if (TDBGrid(actual).ReadOnly) or (HiWord(GetKeyState(VK_CONTROL)) = 0) then Msg.wParam := VK_TAB else if not(HiWord(GetKeyState(VK_SHIFT)) = 0) then begin if TDBGrid(actual).SelectedIndex > 0 then { increment the field } TDBGrid(actual).SelectedIndex := TDBGrid(actual).SelectedIndex - 1 else TDBGrid(actual).SelectedIndex := TDBGrid(actual).FieldCount - 1; end else begin if TDBGrid(actual).SelectedIndex < (TDBGrid(actual).FieldCount - 1) then { increment the field } TDBGrid(actual).SelectedIndex := TDBGrid(actual).SelectedIndex + 1 else TDBGrid(actual).SelectedIndex := 0; end; end; // ListBox if actual is TCustomListBox then Msg.wParam := VK_TAB; // TabControl if actual is TCustomTabControl then Msg.wParam := VK_TAB; // Aqui se pondrían todos los controles que usamos en la // aplicación y necesitamos cambiar el tab por intro. // de esta forma te despreocupas de cuantos añades y es más // limpio el código end; end; end; procedure TBASE.aquillas1Click(Sender: TObject); begin taquillas := Ttaquillas.Create(nil); try taquillas.ShowModal; finally taquillas.Free; end; end; end. ======================================== FICHERO: puestos_trabajo.pas ======================================== unit puestos_trabajo; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,Vcl.StdCtrls, Vcl.DBCtrls, Vcl.Mask, Vcl.ComCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, datos, ZAbstractDataset, ZDataset, Data.DB, ZAbstractRODataset, ZAbstractTable,Excel2000, ComObj; type Tfpuestos_trabajo = class(TForm) Panel7: TPanel; btAcancelar: TButton; btAmodificar: TButton; btAborrar: TButton; btAnuevo: TButton; btAguardar: TButton; qaux: TZQuery; Panel1: TPanel; Panel2: TPanel; DBGrid1: TDBGrid; dsqimpuestos: TDataSource; qpuestos_trabajo: TZQuery; gcrpagado: TDBCheckBox; qpuestos_trabajoid: TIntegerField; qpuestos_trabajodescripcion: TWideStringField; qpuestos_trabajoactivo: TIntegerField; procedure btAnuevoClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DBGrid1CellClick(Column: TColumn); procedure dsqimpuestosStateChange(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure btAmodificarClick(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure AppMessage(var Msg: Tmsg; var Handled:Boolean); end; var fpuestos_trabajo: Tfpuestos_trabajo; implementation {$R *.dfm} procedure Tfpuestos_trabajo.AppMessage(var Msg: TMSg; Var Handled:Boolean); var actual : TWincontrol; begin if Msg.message = WM_KEYDOWN then begin // esto es para controlar que con la flecha abajo se desplegen las // listas if Msg.wParam = VK_DOWN then begin Actual := Screen.ActiveControl; if Actual is TDBLookupComboBox then if not TDBLookupComboBox(Screen.ActiveForm.ActiveControl).listVisible then TDBLookupComboBox(Screen.ActiveForm.ActiveControl).DropDown; // si utilizas las RX { if Actual is TRxDBLookupCombo then if not TRxDBLookupCombo(Screen.ActiveForm.ActiveControl).listVisible then TRxDBLookupCombo(Screen.ActiveForm.ActiveControl).DropDown; } if Actual is TComboBox then SendMessage(TComboBox(Screen.ActiveForm.ActiveControl).Handle,CB_SHOWDROPDOWN,-1,0); if (Actual is TCustomEdit) then Msg.wParam := VK_TAB; // se pueden añadir mas controles.... end; // y aqui es el control del intro. if Msg.wParam = VK_RETURN THEN begin Actual := Screen.ActiveControl; // para los edit. if (Actual is TCustomEdit) and not (Actual is TCustomMemo) then Msg.wParam := VK_TAB; // para los memo. Con ctrl + enter se salta de linea dentro del // memo, si solo es intro salta al siguiente control if (Actual is TCustomMemo) and (HiWord(GetKeyState(VK_CONTROL)) = 0)then Msg.wParam := VK_TAB; // para los lookup if Actual is TDBLookupComboBox then if not TDBLookupComboBox(Actual).listVisible then Msg.wParam := VK_TAB; // Si utilizas las RX { if Actual is TRxDBLookupCombo then if not TRxDBLookupCombo(Actual).listVisible then Msg.wParam := VK_TAB; } // Los combobox if Actual is TCustomComboBox then if not TCustomComboBox(Actual).DroppedDown then Msg.wParam := VK_TAB; // el radiobutton if Actual is TRadioButton then Msg.wParam := VK_TAB; // en el grid if Actual is TDBGrid then if (TDBGrid(Actual).ReadOnly) or (HiWord(GetKeyState(VK_CONTROL)) = 1)then Msg.wParam := VK_TAB; // o esto otro Con Ctrl + intro siguiente celda con // ctrl + shift + intro celda anterior // es complicado pero es por no liar con el intro solo // que siempre pasa de un control a otro. if Actual is TDBGrid then begin if (TDBGrid(Actual).ReadOnly) or (HiWord(GetKeyState(VK_CONTROL)) = 0) then Msg.wParam := VK_TAB else if not(HiWord(GetKeyState(VK_SHIFT)) = 0) then begin if TDBGrid(Actual).selectedindex > 0 then { increment the field } TDBGrid(Actual).selectedindex := TDBGrid(Actual).selectedindex -1 else TDBGrid(Actual).selectedindex := TDBGrid(Actual).fieldcount -1; end else begin if TDBGrid(Actual).selectedindex < (TDBGrid(Actual).fieldcount -1) then { increment the field } TDBGrid(Actual).selectedindex := TDBGrid(Actual).selectedindex +1 else TDBGrid(Actual).selectedindex := 0; end; end; // ListBox if Actual is TCustomListBox then Msg.wParam := VK_TAB; // TabControl if Actual is TCustomTabControl then Msg.wParam := VK_TAB; // Aqui se pondrían todos los controles que usamos en la // aplicación y necesitamos cambiar el tab por intro. // de esta forma te despreocupas de cuantos añades y es más // limpio el código end; end; end; procedure Tfpuestos_trabajo.btAborrarClick(Sender: TObject); begin qpuestos_trabajo.Delete; end; procedure Tfpuestos_trabajo.btAcancelarClick(Sender: TObject); begin qpuestos_trabajo.cancel; end; procedure Tfpuestos_trabajo.btAguardarClick(Sender: TObject); begin qpuestos_trabajo.Post; end; procedure Tfpuestos_trabajo.btAmodificarClick(Sender: TObject); begin qpuestos_trabajo.Edit; end; procedure Tfpuestos_trabajo.btAnuevoClick(Sender: TObject); begin qaux.Close; qaux.sql.clear; qaux.SQL.Add('select max(id)+1 from puestos_trabajo'); qaux.Open; qpuestos_trabajo.append; if qaux.Fields[0].AsInteger<0 then qpuestos_trabajoid.Value:=0 else qpuestos_trabajoid.Value:=qaux.Fields[0].AsInteger; dbgrid1.setfocus; end; procedure Tfpuestos_trabajo.DBGrid1CellClick(Column: TColumn); begin if column.Field.FieldName ='activo' then begin if qpuestos_trabajoactivo.asinteger=1 then begin qpuestos_trabajo.Edit; qpuestos_trabajoactivo.Value:=0; qpuestos_trabajo.Post; dbgrid1.selectedIndex:=1; end else begin qpuestos_trabajo.Edit; qpuestos_trabajoactivo.Value:=1; qpuestos_trabajo.Post; qpuestos_trabajo.Refresh; dbgrid1.SelectedIndex:=1; end; end; end; procedure Tfpuestos_trabajo.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); const IsChecked : array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED); var DrawState: Integer; DrawRect: TRect; begin if (gdFocused in State) then begin if (Column.Field.FieldName = 'activo') then begin gcrpagado.Left := Rect.Left + DBgrid1.Left + 2; gcrpagado.Top := Rect.Top + DBgrid1.top + 2; gcrpagado.Width := Rect.Right - Rect.Left; gcrpagado.Height := Rect.Bottom - Rect.Top; gcrpagado.Visible := True; end; end else begin if (Column.Field.FieldName = 'activo') then begin DrawRect:=Rect; InflateRect(DrawRect,-1,-1); if column.Field.Asinteger=0 then DrawState := ischecked[false]; if column.Field.Asinteger=1 then DrawState := ischecked[true]; // DrawState := ISChecked[Column.Field.Asboolean]; DBgrid1.Canvas.FillRect(Rect); DrawFrameControl(DBgrid1.Canvas.Handle, DrawRect, DFC_BUTTON, DrawState); end; end; end; procedure Tfpuestos_trabajo.dsqimpuestosStateChange(Sender: TObject); begin if qpuestos_trabajo.State in [dsedit,dsinsert] then begin btanuevo.Enabled:=false; btamodificar.Enabled:=false; btaborrar.Enabled:=false; btacancelar.Enabled:=true; btaguardar.Enabled:=true; end else begin btanuevo.Enabled:=true; btamodificar.Enabled:=true; btaborrar.Enabled:=true; btacancelar.Enabled:=false; btaguardar.Enabled:=false; end; end; procedure Tfpuestos_trabajo.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tfpuestos_trabajo.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tfpuestos_trabajo.FormShow(Sender: TObject); begin qpuestos_trabajo.Close; qpuestos_trabajo.Open; end; end. ======================================== FICHERO: regimen_cotizacion.pas ======================================== unit regimen_cotizacion; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls; type Tfregimen_cotizacion = class(TForm) Panel13: TPanel; Panel17: TPanel; DBGrid3: TDBGrid; Panel7: TPanel; btAcancelar: TButton; btAmodificar: TButton; btAborrar: TButton; btAnuevo: TButton; btAguardar: TButton; Panel1: TPanel; Panel2: TPanel; DBGrid1: TDBGrid; dsqregimen: TDataSource; qaux: TZQuery; qregimen: TZQuery; qregimenid: TIntegerField; qregimendescripcion: TWideStringField; qregimenirpf: TFloatField; qregimendesempleo: TFloatField; qregimenformacion: TFloatField; qregimencontingencias: TFloatField; procedure dsqregimenStateChange(Sender: TObject); procedure btAnuevoClick(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure btAmodificarClick(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } end; var fregimen_cotizacion: Tfregimen_cotizacion; implementation {$R *.dfm} procedure Tfregimen_cotizacion.btAborrarClick(Sender: TObject); begin qregimen.delete; end; procedure Tfregimen_cotizacion.btAcancelarClick(Sender: TObject); begin qregimen.cancel; end; procedure Tfregimen_cotizacion.btAguardarClick(Sender: TObject); begin qregimen.post; end; procedure Tfregimen_cotizacion.btAmodificarClick(Sender: TObject); begin qregimen.edit; end; procedure Tfregimen_cotizacion.btAnuevoClick(Sender: TObject); begin qaux.sql.clear; qaux.SQL.Add('select max(id)+1 from regimenes_cotizacion'); qaux.Open; qregimen.append; dbgrid1.setfocus; qregimenid.Value:=qaux.Fields[0].AsInteger; end; procedure Tfregimen_cotizacion.dsqregimenStateChange(Sender: TObject); begin if qregimen.State in [dsedit,dsinsert] then begin btanuevo.Enabled:=false; btamodificar.Enabled:=false; btaborrar.Enabled:=false; btacancelar.Enabled:=true; btaguardar.Enabled:=true; end else begin btanuevo.Enabled:=true; btamodificar.Enabled:=true; btaborrar.Enabled:=true; btacancelar.Enabled:=false; btaguardar.Enabled:=false; end; end; procedure Tfregimen_cotizacion.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tfregimen_cotizacion.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tfregimen_cotizacion.FormShow(Sender: TObject); begin qregimen.Close; qregimen.Open; end; end. ======================================== FICHERO: SignatureForm.pas ======================================== { SignatureForm.pas Allow user to input a signature on an STU and reproduce it on a Window on the PC. Saves signature to a file on disk Copyright (c) 2015 Wacom GmbH. All rights reserved. } unit SignatureForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, wgssSTU_TLB, ExtCtrls, ActiveX, Math; type TMyPenData = class public rdy: WordBool; sw: Byte; pressure: Word; x: Word; y: Word; Constructor Create(penData: IPenData); end; type TVFirmas = class(TForm) Image1: TImage; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure Image1Click(Sender: TObject); private procedure onPenData(ASender: TObject; const pPenData: IPenData); procedure onGetReportException(ASender: TObject; const pException: ITabletEventsException); procedure clearScreen(); function tabletToScreen(penData: TMyPenData) : TPoint; function contains(bounds: TRect; point: TPoint) : boolean; procedure clickAccept(); procedure clickClear(); procedure clickCancel(); procedure DrawAntialisedLine(Canvas: TCanvas; const AX1, AY1, AX2, AY2: real; const LineColor: TColor); procedure saveImage(); procedure freePoints(); public procedure connect(usbDevice: IUsbDevice); end; TOnClickButton = procedure() of object; type TMyButton = class public Bounds : TRect; Text : String; Click : TOnClickButton; end; var VFirmas: TVFirmas; Tablet: TTablet; Capability: ICapability; Information: IInformation; screenBmp : TBitmap; bitmapData : PSafeArray; Buttons: Array of TMyButton; encodingMode : byte; m_isDown : Integer; points : TList; implementation {$R *.dfm} procedure TVFirmas.connect(usbDevice: IUsbDevice); var errorCode : IErrorCode; w1, w2, w3 : Integer; x, y, h, w : Integer; h1, h2, h3 : Integer; i : Integer; ProtocolHelper: IProtocolHelper; bArray : Array of Byte; ms : TMemoryStream; useColor : boolean; fontSize : Integer; begin errorCode := Tablet.usbConnect(usbDevice, True); if (errorCode.value = 0) then begin Capability := Tablet.getCapability(); Information := Tablet.getInformation(); VFirmas.AutoSize := true; Image1.Width := Capability.screenWidth; Image1.Height := Capability.screenHeight; // Add the delagate that receives pen data. Tablet.OnonPenData := onPenData; Tablet.OnonGetReportException := onGetReportException; SetLength(Buttons, 3); for i := 0 to 2 do Buttons[i] := TMyButton.Create; if (usbDevice.idProduct <> $000a2) then begin w2 := Capability.screenWidth div 3; w3 := Capability.screenWidth div 3; w1 := Capability.screenWidth - w2 - w3; y := Capability.screenHeight * 6 div 7; h := Capability.screenHeight - y; Buttons[0].Bounds := Rect(0, y, w1, y + h); Buttons[1].Bounds := Rect(w1, y, w1 + w2, y + h); Buttons[2].Bounds := Rect(w1 + w2, y, w1 + w2 + w3, y + h); fontSize := 10; end else begin // The STU-300 is very shallow, so it is better to utilise // the buttons to the side of the display instead. x := Capability.screenWidth * 3 div 4; w := Capability.screenWidth - x; h2 := Capability.screenHeight div 3; h3 := Capability.screenHeight div 3; h1 := Capability.screenHeight - h2 - h3; Buttons[0].Bounds := Rect(x, 0, x + w, h1); Buttons[1].Bounds := Rect(x, h1, x + w, h1 + h2); Buttons[2].Bounds := Rect(x, h1 + h2, x + w, h1 + h2 + h3); fontSize := 10; end; Buttons[0].Text := 'Ok'; Buttons[1].Text := 'Borrar'; Buttons[2].Text := 'Cancelar'; Buttons[0].Click := clickAccept; Buttons[1].Click := clickClear; Buttons[2].Click := clickCancel; useColor := (usbDevice.idProduct = $a3); // Only the STU-520A supports colour! // Disable color if the STU-520 bulk driver isn't installed. // This isn't necessary, but uploading colour images with out the driver // is very slow. useColor := useColor and Tablet.supportsWrite(); // Calculate the encodingMode that will be used to update the image if (useColor) then begin if (Tablet.supportsWrite()) then begin encodingMode := (EncodingMode_16bit_565 or EncodingMode_Bulk); end else begin encodingMode := (EncodingMode_16bit_565 or EncodingMode_Raw); end end else begin encodingMode := EncodingMode_Raw; end; screenBmp := TBitmap.Create; screenBmp.PixelFormat := pf24bit; screenBmp.Width := Capability.screenWidth; screenBmp.Height := Capability.screenHeight; screenBmp.Canvas.Font.Name := 'Courier New'; screenBmp.Canvas.Font.Color := clBlack; screenBmp.Canvas.Font.Size := fontSize; with screenBmp.Canvas do begin Brush.Color := clWhite; FillRect(Rect(0, 0, Capability.screenWidth, Capability.screenHeight)); for i := 0 to 2 do begin if (useColor) then begin Brush.Color := clSilver; end; rectangle(Buttons[i].Bounds); DrawText(Handle, PChar(Buttons[i].Text), Length(Buttons[i].Text), Buttons[i].Bounds, DT_SINGLELINE or DT_CENTER or DT_VCENTER); end; end; // Finally, use this bitmap for the window background. Image1.Picture.Bitmap := screenBmp; // Now the bitmap has been created, it needs to be converted to device-native // format. ProtocolHelper := CoProtocolHelper.Create; // Unfortunately it is not possible for the native COM component to // understand Delphi bitmaps. We have therefore convert the Delphi bitmap // into a memory blob that will be understood by COM. ms := TMemoryStream.Create; try screenBmp.SaveToStream(ms); ms.Seek(0, 0); SetLength(bArray, ms.Size); ms.ReadBuffer(bArray[0], Length(bArray)); finally ms.Free; end; bitmapData := ProtocolHelper.resizeAndFlatten(bArray, 0, 0, screenBmp.Width, screenBmp.Height, Capability.screenWidth, Capability.screenHeight, useColor, Scale_Fit, 0, 0); protocolHelper := nil; // Initialize the screen clearScreen(); // Enable the pen data on the screen (if not already) Tablet.setInkingMode(1); end else raise Exception.Create(errorCode.message); end; procedure TVFirmas.FormCreate(Sender: TObject); begin DoubleBuffered := true; Tablet := TTablet.Create(self); m_isDown := 0; points := TList.Create; end; procedure TVFirmas.onPenData(ASender: TObject; const pPenData: IPenData); var pt : TPoint; prev : TPoint; btn : Integer; i : Integer; isDown : boolean; begin btn := 0; // will be +ve if the pen is over a button. pt := tabletToScreen(TMyPenData.Create(pPenData)); for i := 0 to 2 do begin if (contains(Buttons[i].Bounds, pt)) then begin btn := i+1; Break; end; end; isDown := (pPenData.sw <> 0); // This code uses a model of four states the pen can be in: // down or up, and whether this is the first sample of that state. if (isDown) then begin if (m_isDown = 0) then begin // transition to down if (btn > 0) then begin // We have put the pen down on a button. // Track the pen without inking on the client. m_isDown := btn; end else begin m_isDown := -1; end; end else begin // already down, keep doing what we're doing! end; // draw if ((points.Count > 0) and (m_isDown = -1)) then begin // Draw a line from the previous down point to this down point. // This is the simplist thing you can do; a more sophisticated program // can perform higher quality rendering than this! if (pPenData.sw > 0) then begin prev := tabletToScreen(TMyPenData(points.Last())); DrawAntialisedLine(Image1.Canvas, prev.X, prev.Y, pt.X, pt.Y, clBlack); end; end; // The pen is down, store it for use later. if (m_isDown = -1) then begin points.Add(TMyPenData.Create(pPenData)); end; end else begin if (m_isDown <> 0) then begin // transition to up if (btn > 0) then begin // The pen is over a button if (btn = m_isDown) then begin // The pen was pressed down over the same button as is was lifted now. // Consider that as a click! Buttons[btn - 1].Click(); end; end; m_isDown := 0; end else begin // still up end; // Add up data once we have collected some down data. if (points.Count > 0) then points.Add(TMyPenData.Create(pPenData)); end; end; procedure TVFirmas.clearScreen(); begin // note: There is no need to clear the tablet screen prior to writing an image. Tablet.writeImage(encodingMode, bitmapData); Image1.Picture.Bitmap := screenBmp; freePoints(); end; function TVFirmas.tabletToScreen(penData: TMyPenData) : TPoint; begin Result := Point(penData.x * Capability.screenWidth div Capability.tabletMaxX, penData.y * Capability.screenHeight div Capability.tabletMaxY); end; function TVFirmas.contains(bounds: TRect; point: TPoint) : boolean; begin if (((point.X >= bounds.Left) and (point.X <= bounds.Right)) and ((point.Y >= bounds.Top) and (point.Y <= bounds.Bottom))) then begin Result := true; end else begin Result := false; end end; procedure TVFirmas.clickAccept(); begin // You probably want to add additional processing here. if (points.Count > 0) then begin saveImage(); VFirmas.Close; end; end; procedure TVFirmas.clickClear(); begin if (points.Count > 0) then begin clearScreen(); end; end; procedure TVFirmas.clickCancel(); begin // You probably want to add additional processing here. VFirmas.Close; end; procedure TVFirmas.FormClose(Sender: TObject; var Action: TCloseAction); begin screenBmp.Free; freePoints(); try begin tablet.setClearScreen; tablet.disconnect1; end; except on e : Exception do ShowMessage(e.Message); end; end; procedure TVFirmas.onGetReportException(ASender: TObject; const pException: ITabletEventsException); begin try pException.getException; except on e : Exception do begin VFirmas.Close(); end; end; end; Constructor TMyPenData.Create(penData: IPenData); begin self.rdy := penData.rdy; self.sw := penData.sw; self.pressure := penData.pressure; self.x := penData.x; self.y := penData.y; end; procedure TVFirmas.DrawAntialisedLine(Canvas: TCanvas; const AX1, AY1, AX2, AY2: real; const LineColor: TColor); var swapped: boolean; procedure plot(const x, y, c: real); var resclr: TColor; begin if swapped then resclr := Canvas.Pixels[round(y), round(x)] else resclr := Canvas.Pixels[round(x), round(y)]; resclr := RGB(round(GetRValue(resclr) * (1-c) + GetRValue(LineColor) * c), round(GetGValue(resclr) * (1-c) + GetGValue(LineColor) * c), round(GetBValue(resclr) * (1-c) + GetBValue(LineColor) * c)); if swapped then Canvas.Pixels[round(y), round(x)] := resclr else Canvas.Pixels[round(x), round(y)] := resclr; end; function rfrac(const x: real): real; begin rfrac := 1 - frac(x); end; procedure swap(var a, b: real); var tmp: real; begin tmp := a; a := b; b := tmp; end; var x1, x2, y1, y2, dx, dy, gradient, xend, yend, xgap, xpxl1, ypxl1, xpxl2, ypxl2, intery: real; x: integer; begin x1 := AX1; x2 := AX2; y1 := AY1; y2 := AY2; dx := x2 - x1; dy := y2 - y1; swapped := abs(dx) < abs(dy); if swapped then begin swap(x1, y1); swap(x2, y2); swap(dx, dy); end; if x2 < x1 then begin swap(x1, x2); swap(y1, y2); end; if (dx <> 0) then begin gradient := dy / dx; end else begin gradient := 0; end; xend := round(x1); yend := y1 + gradient * (xend - x1); xgap := rfrac(x1 + 0.5); xpxl1 := xend; ypxl1 := floor(yend); plot(xpxl1, ypxl1, rfrac(yend) * xgap); plot(xpxl1, ypxl1 + 1, frac(yend) * xgap); intery := yend + gradient; xend := round(x2); yend := y2 + gradient * (xend - x2); xgap := frac(x2 + 0.5); xpxl2 := xend; ypxl2 := floor(yend); plot(xpxl2, ypxl2, rfrac(yend) * xgap); plot(xpxl2, ypxl2 + 1, frac(yend) * xgap); for x := round(xpxl1) + 1 to round(xpxl2) - 1 do begin plot(x, floor(intery), rfrac(intery)); plot(x, floor(intery) + 1, frac(intery)); intery := intery + gradient; end; end; procedure TVFirmas.saveImage(); var i: Integer; act, prev: TMyPenData; bmp: TBitmap; point1, point2: TPoint; begin with bmp do begin bmp := TBitmap.Create; bmp.PixelFormat := pf24bit; bmp.Width := Capability.screenWidth; bmp.Height := Capability.screenHeight; bmp.Canvas.Font.Color := clBlack; end; with bmp.Canvas do begin Brush.Color := clWhite; FillRect(Rect(0, 0, Capability.screenWidth, Capability.screenHeight)); end; for i := 1 to points.Count do begin prev := TMyPenData(points[i-1]); if (prev.sw <> 0) then begin act := TMyPenData(points[i]); point1 := tabletToScreen(prev); point2 := tabletToScreen(act); DrawAntialisedLine(bmp.Canvas, point1.x, point1.y, point2.x, point2.y, clBlack); end; end; bmp.SaveToFile('c:\agrigest\tmp\firma.bmp'); bmp.Free; end; procedure TVFirmas.freePoints(); var i: Integer; begin for i := 1 to points.Count do begin TMyPenData(points[i-1]).Free; end; points.Clear(); end; procedure TVFirmas.FormDestroy(Sender: TObject); begin tablet.Free; points.Free; end; procedure TVFirmas.Image1Click(Sender: TObject); var pt1, pt2 : TPoint; i : Integer; begin pt1 := Mouse.CursorPos; pt2 := Point(pt1.x - Image1.ClientOrigin.x,pt1.y - Image1.ClientOrigin.y); for i := 0 to 2 do begin if (contains(Buttons[i].Bounds, pt2)) then begin Buttons[i].Click(); Break; end; end; end; end. ======================================== FICHERO: tipos_impuestos.pas ======================================== unit tipos_impuestos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,Vcl.StdCtrls, Vcl.DBCtrls, Vcl.Mask, Vcl.ComCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, datos, ZAbstractDataset, ZDataset, Data.DB, ZAbstractRODataset, ZAbstractTable; type Tftipos_impuestos = class(TForm) Panel13: TPanel; Panel17: TPanel; DBGrid3: TDBGrid; Panel7: TPanel; btAcancelar: TButton; btAmodificar: TButton; btAborrar: TButton; btAnuevo: TButton; btAguardar: TButton; dsqimpuestos: TDataSource; qimpuestos: TZQuery; qimpuestosid: TIntegerField; qimpuestosdescripcion: TWideStringField; qimpuestostipo: TIntegerField; qimpuestostipo_req: TFloatField; qaux: TZQuery; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure btAnuevoClick(Sender: TObject); procedure dsqimpuestosStateChange(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure btAmodificarClick(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; var ftipos_impuestos: Tftipos_impuestos; implementation {$R *.dfm} procedure Tftipos_impuestos.btAborrarClick(Sender: TObject); begin qimpuestos.delete; end; procedure Tftipos_impuestos.btAcancelarClick(Sender: TObject); begin qimpuestos.cancel; end; procedure Tftipos_impuestos.btAguardarClick(Sender: TObject); begin qimpuestos.post; end; procedure Tftipos_impuestos.btAmodificarClick(Sender: TObject); begin qimpuestos.edit; end; procedure Tftipos_impuestos.btAnuevoClick(Sender: TObject); begin qaux.sql.clear; qaux.SQL.Add('select max(id)+1 from tipos_iva'); qaux.Open; qimpuestos.append; dbgrid3.setfocus; qimpuestosid.Value:=qaux.Fields[0].AsInteger; end; procedure Tftipos_impuestos.dsqimpuestosStateChange(Sender: TObject); begin if qimpuestos.State in [dsedit,dsinsert] then begin btanuevo.Enabled:=false; btamodificar.Enabled:=false; btaborrar.Enabled:=false; btacancelar.Enabled:=true; btaguardar.Enabled:=true; end else begin btanuevo.Enabled:=true; btamodificar.Enabled:=true; btaborrar.Enabled:=true; btacancelar.Enabled:=false; btaguardar.Enabled:=false; end; end; procedure Tftipos_impuestos.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tftipos_impuestos.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbedit) then begin if (activecontrol as tdbedit).Field.DataType in [ftfloat,ftCurrency,ftbcd,ftfmtbcd] then key:=',' end; if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; procedure Tftipos_impuestos.FormShow(Sender: TObject); begin qimpuestos.Close; qimpuestos.Open; end; end. ======================================== FICHERO: Unit2.pas ======================================== unit Unit2; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.ExtCtrls; type Tfcuentas_bancarias = class(TForm) Panel7: TPanel; btAcancelar: TButton; btAmodificar: TButton; btAborrar: TButton; btAnuevo: TButton; btAguardar: TButton; Panel1: TPanel; Panel2: TPanel; DBGrid1: TDBGrid; Panel3: TPanel; Panel4: TPanel; DBGrid2: TDBGrid; dsqcuentasbancarias: TDataSource; qaux: TZQuery; qcuentas_bancarias: TZQuery; qcuentas_bancariaside: TIntegerField; qcuentas_bancariasid: TIntegerField; qcuentas_bancariasbanco: TWideStringField; qcuentas_bancariascciban: TWideStringField; qcuentas_bancariasccentidad: TWideStringField; qcuentas_bancariasccoficina: TWideStringField; qcuentas_bancariasccdc: TWideStringField; qcuentas_bancariascccc: TWideStringField; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure btAnuevoClick(Sender: TObject); procedure btAborrarClick(Sender: TObject); procedure btAmodificarClick(Sender: TObject); procedure btAguardarClick(Sender: TObject); procedure btAcancelarClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var fcuentas_bancarias: Tfcuentas_bancarias; implementation {$R *.dfm} procedure Tfcuentas_bancarias.btAborrarClick(Sender: TObject); begin qcuentas_bancarias.Delete; end; procedure Tfcuentas_bancarias.btAcancelarClick(Sender: TObject); begin qcuentas_bancarias.cancel; end; procedure Tfcuentas_bancarias.btAguardarClick(Sender: TObject); begin qcuentas_bancarias.post; end; procedure Tfcuentas_bancarias.btAmodificarClick(Sender: TObject); begin qcuentas_bancarias.edit end; procedure Tfcuentas_bancarias.btAnuevoClick(Sender: TObject); begin qaux.Close; qaux.sql.clear; qaux.SQL.Add('select max(id)+1 from cuentas_bancarias'); qaux.Open; qcuentas_bancarias.append; if qaux.Fields[0].AsInteger<0 then qcuentas_bancariasid.Value:=0 else qcuentas_bancariasid.Value:=qaux.Fields[0].AsInteger; dbgrid1.setfocus; end; procedure Tfcuentas_bancarias.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (activecontrol is tdbgrid) then begin if Key = 13 then Key :=9; end; end; procedure Tfcuentas_bancarias.FormKeyPress(Sender: TObject; var Key: Char); var formatos:tformatsettings; punto:string; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatos); punto:=formatos.DecimalSeparator; if punto=',' then begin key:=upcase(key); if (key='.') and (activecontrol is tdbgrid) then begin key:=',' end; end; if (activecontrol is tdbgrid) then begin if Key = #13 then Key :=#9; end; if (key=#13) then begin Perform(WM_NextDLGCtl,0,0); key:=#0; end; end; end. ======================================== FICHERO: wgssSTU_TLB.pas ======================================== unit wgssSTU_TLB; // ************************************************************************ // // WARNING // ------- // The types declared in this file were generated from data read from a // Type Library. If this type library is explicitly or indirectly (via // another type library referring to this type library) re-imported, or the // 'Refresh' command of the Type Library Editor activated while editing the // Type Library, the contents of this file will be regenerated and all // manual modifications will be lost. // ************************************************************************ // // PASTLWTR : 1.2 // File generated on 12/08/2013 9:47:10 from Type Library described below. // ************************************************************************ // // Type Lib: C:\Program Files (x86)\Wacom STU SDK\COM\bin\Win32\wgssSTU.dll (1) // LIBID: {20007867-2524-410F-A904-CF6A6A976D89} // LCID: 0 // Helpfile: // HelpString: Wacom STU SDK 1.0 Type Library // DepndLst: // (1) v2.0 stdole, (C:\Windows\SysWOW64\stdole2.tlb) // Errors: // Hint: Member 'Interface' of 'IProtocol' changed to 'Interface_' // Hint: Member 'set' of 'IInterface' changed to 'set_' // Error creating palette bitmap of (TUsbInterface) : Server C:\Program Files (x86)\Wacom STU SDK\COM\bin\Win32\wgssSTU.dll contains no icons // Error creating palette bitmap of (TSerialInterface) : Server C:\Program Files (x86)\Wacom STU SDK\COM\bin\Win32\wgssSTU.dll contains no icons // Error creating palette bitmap of (TUsbDevices) : Server C:\Program Files (x86)\Wacom STU SDK\COM\bin\Win32\wgssSTU.dll contains no icons // Error creating palette bitmap of (TJScript) : Server C:\Program Files (x86)\Wacom STU SDK\COM\bin\Win32\wgssSTU.dll contains no icons // Error creating palette bitmap of (TProtocolHelper) : Server C:\Program Files (x86)\Wacom STU SDK\COM\bin\Win32\wgssSTU.dll contains no icons // Error creating palette bitmap of (TReportHandler) : Server C:\Program Files (x86)\Wacom STU SDK\COM\bin\Win32\wgssSTU.dll contains no icons // Error creating palette bitmap of (TTablet) : Server C:\Program Files (x86)\Wacom STU SDK\COM\bin\Win32\wgssSTU.dll contains no icons // Error creating palette bitmap of (TComponent) : Server C:\Program Files (x86)\Wacom STU SDK\COM\bin\Win32\wgssSTU.dll contains no icons // ************************************************************************ // // *************************************************************************// // NOTE: // Items guarded by $IFDEF_LIVE_SERVER_AT_DESIGN_TIME are used by properties // which return objects that may need to be explicitly created via a function // call prior to any access via the property. These items have been disabled // in order to prevent accidental use from within the object inspector. You // may enable them by defining LIVE_SERVER_AT_DESIGN_TIME or by selectively // removing them from the $IFDEF blocks. However, such items must still be // programmatically created via a method of the appropriate CoClass before // they can be used. {$TYPEDADDRESS OFF} // Unit must be compiled without type-checked pointers. {$WARN SYMBOL_PLATFORM OFF} {$WRITEABLECONST ON} {$VARPROPSETTER ON} interface uses Windows, ActiveX, Classes, Graphics, OleServer, StdVCL, Variants; // *********************************************************************// // GUIDS declared in the TypeLibrary. Following prefixes are used: // Type Libraries : LIBID_xxxx // CoClasses : CLASS_xxxx // DISPInterfaces : DIID_xxxx // Non-DISP interfaces: IID_xxxx // *********************************************************************// const // TypeLibrary Major and minor versions wgssSTUMajorVersion = 1; wgssSTUMinorVersion = 0; LIBID_wgssSTU: TGUID = '{20007867-2524-410F-A904-CF6A6A976D89}'; IID_IProtocol: TGUID = '{20003973-823A-4431-A479-3AA86D58A633}'; IID_IInterface: TGUID = '{200016D1-CBE2-4625-9F64-9685A2C09838}'; IID_IInterfaceQueue: TGUID = '{20001FFA-3449-4592-8772-C7C00D46499B}'; IID_IPredicate: TGUID = '{20008863-5B2A-40BE-8E69-4D2F20303732}'; IID_IStatus: TGUID = '{2000F706-6451-4F84-BA53-EA90D9BD52DB}'; IID_IInformation: TGUID = '{200021D5-E224-4C70-A8CB-A62E90183DA9}'; IID_ICapability: TGUID = '{200028BD-1A2E-4C77-BEBB-EBEF8989EFEA}'; IID_IInkThreshold: TGUID = '{20003425-E218-45D6-B3E2-961C74364617}'; IID_IHandwritingThicknessColor: TGUID = '{20004323-9CF7-4375-B7C3-DEFDF8588FAD}'; IID_IHandwritingDisplayArea: TGUID = '{2000518C-05F0-4D88-B867-C5C9D58C04C5}'; IID_IUsbDevice: TGUID = '{20006935-F639-4B1E-845F-5B6A6E590E7F}'; IID_IUsbDevices: TGUID = '{20008CC2-6576-4665-8411-99291CF18387}'; IID_IErrorCode: TGUID = '{20001A79-3839-4E67-9855-075A7312AA0D}'; IID_IUsbInterface: TGUID = '{2000C1D7-8270-490B-A8F3-766258E6BAB9}'; IID_ISerialInterface: TGUID = '{20003D0C-A047-4487-8FE0-0CF9AB05E48C}'; IID_IPenData: TGUID = '{20003BCE-8DD9-43AD-819B-F746171CA1EC}'; IID_IPenDataOption: TGUID = '{200041E8-CBEC-4414-A64D-B6600A4D3FF6}'; IID_IPenDataEncrypted: TGUID = '{20007929-8A2A-49DF-8B6D-38B71F8991AB}'; IID_IPenDataEncryptedOption: TGUID = '{200088A2-DC76-4716-8879-6E6115A1BBE8}'; IID_IProtocolHelper: TGUID = '{2000550B-EFC5-4D5F-8969-45C9A67CC93C}'; IID_IReport: TGUID = '{2000122F-B55F-40DE-9284-277D32AEE77F}'; IID_IDecrypt: TGUID = '{20007FDA-B1C5-44F2-A8F8-AFCD4E6A76C2}'; IID_IReportHandler: TGUID = '{2000446E-736E-4513-9751-A9B69648863E}'; IID_ITabletEncryptionHandler: TGUID = '{2000B2ED-AEDA-4E86-8A69-BB987FA3B238}'; IID_ITablet: TGUID = '{20005C27-7729-492F-8106-540F2E04DC66}'; IID_IJScript: TGUID = '{200072FE-6F48-44D0-8C0A-4ABAE07EDFF6}'; IID_IComponentFile: TGUID = '{20005C8A-5280-4C4D-8565-DED24A3672F5}'; IID_IComponentFiles: TGUID = '{2000A6E2-D773-4829-9B61-78DAC3CCAD82}'; IID_IComponent: TGUID = '{20001D33-3D2C-4E4D-AFE8-5E5D446637FD}'; DIID_IInterfaceEvents: TGUID = '{2000A1EE-8F0B-4027-B84E-A8172950CF0C}'; DIID_IReportHandlerEvents: TGUID = '{20004D65-E291-4B63-8062-7E99EBD21BDF}'; IID_ITabletEventsException: TGUID = '{20005380-DA13-492A-A97F-EE5811B49B1C}'; DIID_ITabletEvents: TGUID = '{2000C72A-E338-477E-B359-D6D00006D29E}'; CLASS_UsbInterface: TGUID = '{2000BC66-5735-45C7-9521-93FAAFE8C3BB}'; CLASS_SerialInterface: TGUID = '{20001CFF-184E-4E32-9FC4-A617533D342E}'; CLASS_UsbDevices: TGUID = '{2000D7A5-64F7-4826-B56E-85ACC618E4D6}'; CLASS_JScript: TGUID = '{2000D408-6AFE-4CBA-BDB1-DA087DA66B05}'; CLASS_ProtocolHelper: TGUID = '{2000CF89-E182-40AD-A8C2-5694987EA5DF}'; CLASS_ReportHandler: TGUID = '{20008BA5-8133-45BA-91A5-AB54A1F70E13}'; CLASS_Tablet: TGUID = '{20002178-1165-4D38-A7F5-B169DE2045C1}'; CLASS_Component: TGUID = '{20000000-5D96-46B0-895F-B0CC7295E44D}'; // *********************************************************************// // Declaration of Enumerations defined in Type Library // *********************************************************************// // Constants for enum statusCode type statusCode = TOleEnum; const StatusCode_Ready = $00000000; StatusCode_Image = $00000001; StatusCode_Capture = $00000002; StatusCode_Calculation = $00000003; // Constants for enum ErrorCode type ErrorCode = TOleEnum; const ErrorCode_None = $00000000; ErrorCode_WrongReportId = $00000001; ErrorCode_WrongState = $00000002; ErrorCode_CRC = $00000003; ErrorCode_GraphicsWrongEncodingType = $00000010; ErrorCode_GraphicsImageTooLong = $00000011; ErrorCode_GraphicsZlibError = $00000012; // Constants for enum resetFlag type resetFlag = TOleEnum; const ResetFlag_Software = $00000000; ResetFlag_Hardware = $00000001; // Constants for enum inkingMode type inkingMode = TOleEnum; const InkingMode_Off = $00000000; InkingMode_On = $00000001; // Constants for enum ReportId type ReportId = TOleEnum; const ReportId_PenData = $00000001; ReportId_Status = $00000003; ReportId_Reset = $00000004; ReportId_Information = $00000008; ReportId_Capability = $00000009; ReportId_Uid = $0000000A; ReportId_PenDataEncrypted = $00000010; ReportId_HostPublicKey = $00000013; ReportId_DevicePublicKey = $00000014; ReportId_StartCapture = $00000015; ReportId_EndCapture = $00000016; ReportId_DHprime = $0000001A; ReportId_DHbase = $0000001B; ReportId_ClearScreen = $00000020; ReportId_InkingMode = $00000021; ReportId_InkThreshold = $00000022; ReportId_StartImageData = $00000025; ReportId_ImageDataBlock = $00000026; ReportId_EndImageData = $00000027; ReportId_HandwritingThicknessColor = $00000028; ReportId_BackgroundColor = $00000029; ReportId_HandwritingDisplayArea = $0000002A; ReportId_BacklightBrightness = $0000002B; ReportId_PenDataOption = $00000030; ReportId_PenDataEncryptedOption = $00000031; ReportId_PenDataOptionMode = $00000032; ReportId_GetReport = $00000080; ReportId_SetResult = $00000081; // Constants for enum encodingMode type encodingMode = TOleEnum; const EncodingMode_Raw = $00000000; EncodingMode_Zlib = $00000001; EncodingMode_16bit_565 = $00000002; EncodingMode_Bulk = $00000010; // Constants for enum penDataOptionMode type penDataOptionMode = TOleEnum; const PenDataOptionMode_None = $00000000; PenDataOptionMode_TimeCount = $00000001; PenDataOptionMode_SequenceNumber = $00000002; // Constants for enum Scale type Scale = TOleEnum; const Scale_Stretch = $00000000; Scale_Fit = $00000001; Scale_Clip = $00000002; // Constants for enum Clip type Clip = TOleEnum; const Clip_Left = $00000000; Clip_Center = $00000001; Clip_Right = $00000002; Clip_Top = $00000000; Clip_Middle = $00000010; Clip_Bottom = $00000020; // Constants for enum OpDirection type OpDirection = TOleEnum; const OpDirection_Get = $00000100; OpDirection_Set = $00000200; type // *********************************************************************// // Forward declaration of types defined in TypeLibrary // *********************************************************************// IProtocol = interface; IProtocolDisp = dispinterface; IInterface = interface; IInterfaceDisp = dispinterface; IInterfaceQueue = interface; IInterfaceQueueDisp = dispinterface; IPredicate = interface; IPredicateDisp = dispinterface; IStatus = interface; IStatusDisp = dispinterface; IInformation = interface; IInformationDisp = dispinterface; ICapability = interface; ICapabilityDisp = dispinterface; IInkThreshold = interface; IInkThresholdDisp = dispinterface; IHandwritingThicknessColor = interface; IHandwritingThicknessColorDisp = dispinterface; IHandwritingDisplayArea = interface; IHandwritingDisplayAreaDisp = dispinterface; IUsbDevice = interface; IUsbDeviceDisp = dispinterface; IUsbDevices = interface; IUsbDevicesDisp = dispinterface; IErrorCode = interface; IErrorCodeDisp = dispinterface; IUsbInterface = interface; IUsbInterfaceDisp = dispinterface; ISerialInterface = interface; ISerialInterfaceDisp = dispinterface; IPenData = interface; IPenDataDisp = dispinterface; IPenDataOption = interface; IPenDataOptionDisp = dispinterface; IPenDataEncrypted = interface; IPenDataEncryptedDisp = dispinterface; IPenDataEncryptedOption = interface; IPenDataEncryptedOptionDisp = dispinterface; IProtocolHelper = interface; IProtocolHelperDisp = dispinterface; IReport = interface; IReportDisp = dispinterface; IDecrypt = interface; IDecryptDisp = dispinterface; IReportHandler = interface; IReportHandlerDisp = dispinterface; ITabletEncryptionHandler = interface; ITabletEncryptionHandlerDisp = dispinterface; ITablet = interface; ITabletDisp = dispinterface; IJScript = interface; IJScriptDisp = dispinterface; IComponentFile = interface; IComponentFileDisp = dispinterface; IComponentFiles = interface; IComponentFilesDisp = dispinterface; IComponent = interface; IComponentDisp = dispinterface; IInterfaceEvents = dispinterface; IReportHandlerEvents = dispinterface; ITabletEventsException = interface; ITabletEventsExceptionDisp = dispinterface; ITabletEvents = dispinterface; // *********************************************************************// // Declaration of CoClasses defined in Type Library // (NOTE: Here we map each CoClass to its Default Interface) // *********************************************************************// UsbInterface = IUsbInterface; SerialInterface = ISerialInterface; UsbDevices = IUsbDevices; JScript = IJScript; ProtocolHelper = IProtocolHelper; ReportHandler = IReportHandler; Tablet = ITablet; Component = IComponent; // *********************************************************************// // Declaration of structures, unions and aliases. // *********************************************************************// PPSafeArray1 = ^PSafeArray; {*} PWordBool1 = ^WordBool; {*} // *********************************************************************// // Interface: IProtocol // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20003973-823A-4431-A479-3AA86D58A633} // *********************************************************************// IProtocol = interface(IDispatch) ['{20003973-823A-4431-A479-3AA86D58A633}'] function Get_Interface_: IInterface; safecall; function getStatus: IStatus; safecall; procedure setReset(resetFlag: Byte); safecall; function getInformation: IInformation; safecall; function getCapability: ICapability; safecall; function getUid: SYSUINT; safecall; procedure setUid(uid: SYSUINT); safecall; function getHostPublicKey: PSafeArray; safecall; procedure setHostPublicKey(publicKey: PSafeArray); safecall; function getDevicePublicKey: PSafeArray; safecall; procedure setStartCapture(sessionId: SYSUINT); safecall; procedure setEndCapture; safecall; function getDHprime: PSafeArray; safecall; procedure setDHprime(dhPrime: PSafeArray); safecall; function getDHbase: PSafeArray; safecall; procedure setDHbase(dhBase: PSafeArray); safecall; procedure setClearScreen; safecall; function getInkingMode: Byte; safecall; procedure setInkingMode(inkingMode: Byte); safecall; function getInkThreshold: IInkThreshold; safecall; procedure setInkThreshold(const inkThreshold: IInkThreshold); safecall; procedure setStartImageData(encodingMode: Byte); safecall; procedure setImageDataBlock(imageDataBlock: PSafeArray); safecall; procedure setEndImageData; safecall; function getHandwritingThicknessColor: IHandwritingThicknessColor; safecall; procedure setHandwritingThicknessColor(const HandwritingThicknessColor: IHandwritingThicknessColor); safecall; function getBackgroundColor: Word; safecall; procedure setBackgroundColor(backgroundColor: Word); safecall; function getHandwritingDisplayArea: IHandwritingDisplayArea; safecall; procedure setHandwritingDisplayArea(const handwritingDisplayArea: IHandwritingDisplayArea); safecall; function getBacklightBrightness: Word; safecall; procedure setBacklightBrightness(backlightBrightness: Word); safecall; function getPenDataOptionMode: Byte; safecall; procedure setPenDataOptionMode(penDataOptionMode: Byte); safecall; property Interface_: IInterface read Get_Interface_; end; // *********************************************************************// // DispIntf: IProtocolDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20003973-823A-4431-A479-3AA86D58A633} // *********************************************************************// IProtocolDisp = dispinterface ['{20003973-823A-4431-A479-3AA86D58A633}'] property Interface_: IInterface readonly dispid 2305; function getStatus: IStatus; dispid 2306; procedure setReset(resetFlag: Byte); dispid 2307; function getInformation: IInformation; dispid 2308; function getCapability: ICapability; dispid 2309; function getUid: SYSUINT; dispid 2310; procedure setUid(uid: SYSUINT); dispid 2311; function getHostPublicKey: {??PSafeArray}OleVariant; dispid 2312; procedure setHostPublicKey(publicKey: {??PSafeArray}OleVariant); dispid 2313; function getDevicePublicKey: {??PSafeArray}OleVariant; dispid 2314; procedure setStartCapture(sessionId: SYSUINT); dispid 2315; procedure setEndCapture; dispid 2316; function getDHprime: {??PSafeArray}OleVariant; dispid 2317; procedure setDHprime(dhPrime: {??PSafeArray}OleVariant); dispid 2318; function getDHbase: {??PSafeArray}OleVariant; dispid 2319; procedure setDHbase(dhBase: {??PSafeArray}OleVariant); dispid 2320; procedure setClearScreen; dispid 2321; function getInkingMode: Byte; dispid 2322; procedure setInkingMode(inkingMode: Byte); dispid 2323; function getInkThreshold: IInkThreshold; dispid 2324; procedure setInkThreshold(const inkThreshold: IInkThreshold); dispid 2325; procedure setStartImageData(encodingMode: Byte); dispid 2326; procedure setImageDataBlock(imageDataBlock: {??PSafeArray}OleVariant); dispid 2327; procedure setEndImageData; dispid 2328; function getHandwritingThicknessColor: IHandwritingThicknessColor; dispid 2329; procedure setHandwritingThicknessColor(const HandwritingThicknessColor: IHandwritingThicknessColor); dispid 2330; function getBackgroundColor: {??Word}OleVariant; dispid 2331; procedure setBackgroundColor(backgroundColor: {??Word}OleVariant); dispid 2332; function getHandwritingDisplayArea: IHandwritingDisplayArea; dispid 2333; procedure setHandwritingDisplayArea(const handwritingDisplayArea: IHandwritingDisplayArea); dispid 2334; function getBacklightBrightness: {??Word}OleVariant; dispid 2335; procedure setBacklightBrightness(backlightBrightness: {??Word}OleVariant); dispid 2336; function getPenDataOptionMode: Byte; dispid 2337; procedure setPenDataOptionMode(penDataOptionMode: Byte); dispid 2338; end; // *********************************************************************// // Interface: IInterface // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {200016D1-CBE2-4625-9F64-9685A2C09838} // *********************************************************************// IInterface = interface(IDispatch) ['{200016D1-CBE2-4625-9F64-9685A2C09838}'] procedure disconnect; safecall; function isConnected: WordBool; safecall; procedure get(data: PSafeArray); safecall; procedure set_(data: PSafeArray); safecall; function supportsWrite: WordBool; safecall; procedure write(data: PSafeArray); safecall; function interfaceQueue: IInterfaceQueue; safecall; procedure queueNotifyAll; safecall; function getReportCountLengths: PSafeArray; safecall; function Get_Protocol: IProtocol; safecall; property Protocol: IProtocol read Get_Protocol; end; // *********************************************************************// // DispIntf: IInterfaceDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {200016D1-CBE2-4625-9F64-9685A2C09838} // *********************************************************************// IInterfaceDisp = dispinterface ['{200016D1-CBE2-4625-9F64-9685A2C09838}'] procedure disconnect; dispid 769; function isConnected: WordBool; dispid 770; procedure get(data: {??PSafeArray}OleVariant); dispid 771; procedure set_(data: {??PSafeArray}OleVariant); dispid 772; function supportsWrite: WordBool; dispid 773; procedure write(data: {??PSafeArray}OleVariant); dispid 774; function interfaceQueue: IInterfaceQueue; dispid 775; procedure queueNotifyAll; dispid 776; function getReportCountLengths: {??PSafeArray}OleVariant; dispid 777; property Protocol: IProtocol readonly dispid 778; end; // *********************************************************************// // Interface: IInterfaceQueue // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20001FFA-3449-4592-8772-C7C00D46499B} // *********************************************************************// IInterfaceQueue = interface(IDispatch) ['{20001FFA-3449-4592-8772-C7C00D46499B}'] procedure clear; safecall; function empty: WordBool; safecall; procedure notify; safecall; procedure notifyAll; safecall; function tryGetReport(out report: PSafeArray): WordBool; safecall; function waitGetReportPredicate(const predicate: IPredicate): PSafeArray; safecall; end; // *********************************************************************// // DispIntf: IInterfaceQueueDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20001FFA-3449-4592-8772-C7C00D46499B} // *********************************************************************// IInterfaceQueueDisp = dispinterface ['{20001FFA-3449-4592-8772-C7C00D46499B}'] procedure clear; dispid 513; function empty: WordBool; dispid 514; procedure notify; dispid 515; procedure notifyAll; dispid 516; function tryGetReport(out report: {??PSafeArray}OleVariant): WordBool; dispid 517; function waitGetReportPredicate(const predicate: IPredicate): {??PSafeArray}OleVariant; dispid 518; end; // *********************************************************************// // Interface: IPredicate // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20008863-5B2A-40BE-8E69-4D2F20303732} // *********************************************************************// IPredicate = interface(IDispatch) ['{20008863-5B2A-40BE-8E69-4D2F20303732}'] function predicate: WordBool; safecall; end; // *********************************************************************// // DispIntf: IPredicateDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20008863-5B2A-40BE-8E69-4D2F20303732} // *********************************************************************// IPredicateDisp = dispinterface ['{20008863-5B2A-40BE-8E69-4D2F20303732}'] function predicate: WordBool; dispid 257; end; // *********************************************************************// // Interface: IStatus // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {2000F706-6451-4F84-BA53-EA90D9BD52DB} // *********************************************************************// IStatus = interface(IDispatch) ['{2000F706-6451-4F84-BA53-EA90D9BD52DB}'] function Get_statusCode: Byte; safecall; function Get_lastResultCode: Byte; safecall; function Get_statusWord: Word; safecall; property statusCode: Byte read Get_statusCode; property lastResultCode: Byte read Get_lastResultCode; property statusWord: Word read Get_statusWord; end; // *********************************************************************// // DispIntf: IStatusDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {2000F706-6451-4F84-BA53-EA90D9BD52DB} // *********************************************************************// IStatusDisp = dispinterface ['{2000F706-6451-4F84-BA53-EA90D9BD52DB}'] property statusCode: Byte readonly dispid 2561; property lastResultCode: Byte readonly dispid 2562; property statusWord: {??Word}OleVariant readonly dispid 2563; end; // *********************************************************************// // Interface: IInformation // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {200021D5-E224-4C70-A8CB-A62E90183DA9} // *********************************************************************// IInformation = interface(IDispatch) ['{200021D5-E224-4C70-A8CB-A62E90183DA9}'] function Get_modelName: WideString; safecall; function Get_firmwareMajorVersion: Byte; safecall; function Get_firmwareMinorVersion: Byte; safecall; function Get_secureIc: Byte; safecall; function Get_secureIcVersion: SYSUINT; safecall; property modelName: WideString read Get_modelName; property firmwareMajorVersion: Byte read Get_firmwareMajorVersion; property firmwareMinorVersion: Byte read Get_firmwareMinorVersion; property secureIc: Byte read Get_secureIc; property secureIcVersion: SYSUINT read Get_secureIcVersion; end; // *********************************************************************// // DispIntf: IInformationDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {200021D5-E224-4C70-A8CB-A62E90183DA9} // *********************************************************************// IInformationDisp = dispinterface ['{200021D5-E224-4C70-A8CB-A62E90183DA9}'] property modelName: WideString readonly dispid 2817; property firmwareMajorVersion: Byte readonly dispid 2818; property firmwareMinorVersion: Byte readonly dispid 2819; property secureIc: Byte readonly dispid 2820; property secureIcVersion: SYSUINT readonly dispid 2821; end; // *********************************************************************// // Interface: ICapability // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {200028BD-1A2E-4C77-BEBB-EBEF8989EFEA} // *********************************************************************// ICapability = interface(IDispatch) ['{200028BD-1A2E-4C77-BEBB-EBEF8989EFEA}'] function Get_tabletMaxX: Word; safecall; function Get_tabletMaxY: Word; safecall; function Get_tabletMaxPressure: Word; safecall; function Get_screenWidth: Word; safecall; function Get_screenHeight: Word; safecall; function Get_maxReportRate: Byte; safecall; function Get_resolution: Word; safecall; function Get_zlibColorSupport: Byte; safecall; property tabletMaxX: Word read Get_tabletMaxX; property tabletMaxY: Word read Get_tabletMaxY; property tabletMaxPressure: Word read Get_tabletMaxPressure; property screenWidth: Word read Get_screenWidth; property screenHeight: Word read Get_screenHeight; property maxReportRate: Byte read Get_maxReportRate; property resolution: Word read Get_resolution; property zlibColorSupport: Byte read Get_zlibColorSupport; end; // *********************************************************************// // DispIntf: ICapabilityDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {200028BD-1A2E-4C77-BEBB-EBEF8989EFEA} // *********************************************************************// ICapabilityDisp = dispinterface ['{200028BD-1A2E-4C77-BEBB-EBEF8989EFEA}'] property tabletMaxX: {??Word}OleVariant readonly dispid 3073; property tabletMaxY: {??Word}OleVariant readonly dispid 3074; property tabletMaxPressure: {??Word}OleVariant readonly dispid 3075; property screenWidth: {??Word}OleVariant readonly dispid 3076; property screenHeight: {??Word}OleVariant readonly dispid 3077; property maxReportRate: Byte readonly dispid 3078; property resolution: {??Word}OleVariant readonly dispid 3079; property zlibColorSupport: Byte readonly dispid 3080; end; // *********************************************************************// // Interface: IInkThreshold // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20003425-E218-45D6-B3E2-961C74364617} // *********************************************************************// IInkThreshold = interface(IDispatch) ['{20003425-E218-45D6-B3E2-961C74364617}'] procedure Set_onPressureMark(pRetVal: Word); safecall; function Get_onPressureMark: Word; safecall; procedure Set_offPressureMark(pRetVal: Word); safecall; function Get_offPressureMark: Word; safecall; property onPressureMark: Word read Get_onPressureMark write Set_onPressureMark; property offPressureMark: Word read Get_offPressureMark write Set_offPressureMark; end; // *********************************************************************// // DispIntf: IInkThresholdDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20003425-E218-45D6-B3E2-961C74364617} // *********************************************************************// IInkThresholdDisp = dispinterface ['{20003425-E218-45D6-B3E2-961C74364617}'] property onPressureMark: {??Word}OleVariant dispid 4353; property offPressureMark: {??Word}OleVariant dispid 4354; end; // *********************************************************************// // Interface: IHandwritingThicknessColor // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20004323-9CF7-4375-B7C3-DEFDF8588FAD} // *********************************************************************// IHandwritingThicknessColor = interface(IDispatch) ['{20004323-9CF7-4375-B7C3-DEFDF8588FAD}'] procedure Set_penColor(pRetVal: Word); safecall; function Get_penColor: Word; safecall; procedure Set_penThickness(pRetVal: Byte); safecall; function Get_penThickness: Byte; safecall; property penColor: Word read Get_penColor write Set_penColor; property penThickness: Byte read Get_penThickness write Set_penThickness; end; // *********************************************************************// // DispIntf: IHandwritingThicknessColorDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20004323-9CF7-4375-B7C3-DEFDF8588FAD} // *********************************************************************// IHandwritingThicknessColorDisp = dispinterface ['{20004323-9CF7-4375-B7C3-DEFDF8588FAD}'] property penColor: {??Word}OleVariant dispid 4609; property penThickness: Byte dispid 4610; end; // *********************************************************************// // Interface: IHandwritingDisplayArea // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {2000518C-05F0-4D88-B867-C5C9D58C04C5} // *********************************************************************// IHandwritingDisplayArea = interface(IDispatch) ['{2000518C-05F0-4D88-B867-C5C9D58C04C5}'] procedure Set_upperLeftXPixel(pRetVal: Word); safecall; function Get_upperLeftXPixel: Word; safecall; procedure Set_upperLeftYPixel(pRetVal: Word); safecall; function Get_upperLeftYPixel: Word; safecall; procedure Set_lowerRightXPixel(pRetVal: Word); safecall; function Get_lowerRightXPixel: Word; safecall; procedure Set_lowerRightYPixel(pRetVal: Word); safecall; function Get_lowerRightYPixel: Word; safecall; property upperLeftXPixel: Word read Get_upperLeftXPixel write Set_upperLeftXPixel; property upperLeftYPixel: Word read Get_upperLeftYPixel write Set_upperLeftYPixel; property lowerRightXPixel: Word read Get_lowerRightXPixel write Set_lowerRightXPixel; property lowerRightYPixel: Word read Get_lowerRightYPixel write Set_lowerRightYPixel; end; // *********************************************************************// // DispIntf: IHandwritingDisplayAreaDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {2000518C-05F0-4D88-B867-C5C9D58C04C5} // *********************************************************************// IHandwritingDisplayAreaDisp = dispinterface ['{2000518C-05F0-4D88-B867-C5C9D58C04C5}'] property upperLeftXPixel: {??Word}OleVariant dispid 4865; property upperLeftYPixel: {??Word}OleVariant dispid 4866; property lowerRightXPixel: {??Word}OleVariant dispid 4867; property lowerRightYPixel: {??Word}OleVariant dispid 4868; end; // *********************************************************************// // Interface: IUsbDevice // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20006935-F639-4B1E-845F-5B6A6E590E7F} // *********************************************************************// IUsbDevice = interface(IDispatch) ['{20006935-F639-4B1E-845F-5B6A6E590E7F}'] function Get_idVendor: Word; safecall; function Get_idProduct: Word; safecall; function Get_bcdDevice: Word; safecall; function Get_fileName: WideString; safecall; function Get_bulkFileName: WideString; safecall; property idVendor: Word read Get_idVendor; property idProduct: Word read Get_idProduct; property bcdDevice: Word read Get_bcdDevice; property fileName: WideString read Get_fileName; property bulkFileName: WideString read Get_bulkFileName; end; // *********************************************************************// // DispIntf: IUsbDeviceDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20006935-F639-4B1E-845F-5B6A6E590E7F} // *********************************************************************// IUsbDeviceDisp = dispinterface ['{20006935-F639-4B1E-845F-5B6A6E590E7F}'] property idVendor: {??Word}OleVariant readonly dispid 2049; property idProduct: {??Word}OleVariant readonly dispid 2050; property bcdDevice: {??Word}OleVariant readonly dispid 2051; property fileName: WideString readonly dispid 2052; property bulkFileName: WideString readonly dispid 2053; end; // *********************************************************************// // Interface: IUsbDevices // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20008CC2-6576-4665-8411-99291CF18387} // *********************************************************************// IUsbDevices = interface(IDispatch) ['{20008CC2-6576-4665-8411-99291CF18387}'] function Get__NewEnum: IUnknown; safecall; function Get_Item(index: OleVariant): IUsbDevice; safecall; function Get_Count: Integer; safecall; property _NewEnum: IUnknown read Get__NewEnum; property Item[index: OleVariant]: IUsbDevice read Get_Item; default; property Count: Integer read Get_Count; end; // *********************************************************************// // DispIntf: IUsbDevicesDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20008CC2-6576-4665-8411-99291CF18387} // *********************************************************************// IUsbDevicesDisp = dispinterface ['{20008CC2-6576-4665-8411-99291CF18387}'] property _NewEnum: IUnknown readonly dispid -4; property Item[index: OleVariant]: IUsbDevice readonly dispid 0; default; property Count: Integer readonly dispid 1793; end; // *********************************************************************// // Interface: IErrorCode // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20001A79-3839-4E67-9855-075A7312AA0D} // *********************************************************************// IErrorCode = interface(IDispatch) ['{20001A79-3839-4E67-9855-075A7312AA0D}'] function Get_value: SYSINT; safecall; function Get_category: WideString; safecall; function Get_message: WideString; safecall; property value: SYSINT read Get_value; property category: WideString read Get_category; property message: WideString read Get_message; end; // *********************************************************************// // DispIntf: IErrorCodeDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20001A79-3839-4E67-9855-075A7312AA0D} // *********************************************************************// IErrorCodeDisp = dispinterface ['{20001A79-3839-4E67-9855-075A7312AA0D}'] property value: SYSINT readonly dispid 0; property category: WideString readonly dispid 7681; property message: WideString readonly dispid 7682; end; // *********************************************************************// // Interface: IUsbInterface // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {2000C1D7-8270-490B-A8F3-766258E6BAB9} // *********************************************************************// IUsbInterface = interface(IInterface) ['{2000C1D7-8270-490B-A8F3-766258E6BAB9}'] function connect(const usbDevice: IUsbDevice; exclusiveLock: WordBool): IErrorCode; safecall; function connect2(const fileName: WideString; const bulkFileName: WideString; exclusiveLock: WordBool): IErrorCode; safecall; end; // *********************************************************************// // DispIntf: IUsbInterfaceDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {2000C1D7-8270-490B-A8F3-766258E6BAB9} // *********************************************************************// IUsbInterfaceDisp = dispinterface ['{2000C1D7-8270-490B-A8F3-766258E6BAB9}'] function connect(const usbDevice: IUsbDevice; exclusiveLock: WordBool): IErrorCode; dispid 1025; function connect2(const fileName: WideString; const bulkFileName: WideString; exclusiveLock: WordBool): IErrorCode; dispid 1026; procedure disconnect; dispid 769; function isConnected: WordBool; dispid 770; procedure get(data: {??PSafeArray}OleVariant); dispid 771; procedure set_(data: {??PSafeArray}OleVariant); dispid 772; function supportsWrite: WordBool; dispid 773; procedure write(data: {??PSafeArray}OleVariant); dispid 774; function interfaceQueue: IInterfaceQueue; dispid 775; procedure queueNotifyAll; dispid 776; function getReportCountLengths: {??PSafeArray}OleVariant; dispid 777; property Protocol: IProtocol readonly dispid 778; end; // *********************************************************************// // Interface: ISerialInterface // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20003D0C-A047-4487-8FE0-0CF9AB05E48C} // *********************************************************************// ISerialInterface = interface(IInterface) ['{20003D0C-A047-4487-8FE0-0CF9AB05E48C}'] function connect(const fileName: WideString; useCrc: WordBool): IErrorCode; safecall; end; // *********************************************************************// // DispIntf: ISerialInterfaceDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20003D0C-A047-4487-8FE0-0CF9AB05E48C} // *********************************************************************// ISerialInterfaceDisp = dispinterface ['{20003D0C-A047-4487-8FE0-0CF9AB05E48C}'] function connect(const fileName: WideString; useCrc: WordBool): IErrorCode; dispid 5889; procedure disconnect; dispid 769; function isConnected: WordBool; dispid 770; procedure get(data: {??PSafeArray}OleVariant); dispid 771; procedure set_(data: {??PSafeArray}OleVariant); dispid 772; function supportsWrite: WordBool; dispid 773; procedure write(data: {??PSafeArray}OleVariant); dispid 774; function interfaceQueue: IInterfaceQueue; dispid 775; procedure queueNotifyAll; dispid 776; function getReportCountLengths: {??PSafeArray}OleVariant; dispid 777; property Protocol: IProtocol readonly dispid 778; end; // *********************************************************************// // Interface: IPenData // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20003BCE-8DD9-43AD-819B-F746171CA1EC} // *********************************************************************// IPenData = interface(IDispatch) ['{20003BCE-8DD9-43AD-819B-F746171CA1EC}'] function Get_rdy: WordBool; safecall; function Get_sw: Byte; safecall; function Get_pressure: Word; safecall; function Get_x: Word; safecall; function Get_y: Word; safecall; property rdy: WordBool read Get_rdy; property sw: Byte read Get_sw; property pressure: Word read Get_pressure; property x: Word read Get_x; property y: Word read Get_y; end; // *********************************************************************// // DispIntf: IPenDataDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20003BCE-8DD9-43AD-819B-F746171CA1EC} // *********************************************************************// IPenDataDisp = dispinterface ['{20003BCE-8DD9-43AD-819B-F746171CA1EC}'] property rdy: WordBool readonly dispid 3329; property sw: Byte readonly dispid 3330; property pressure: {??Word}OleVariant readonly dispid 3331; property x: {??Word}OleVariant readonly dispid 3332; property y: {??Word}OleVariant readonly dispid 3333; end; // *********************************************************************// // Interface: IPenDataOption // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {200041E8-CBEC-4414-A64D-B6600A4D3FF6} // *********************************************************************// IPenDataOption = interface(IPenData) ['{200041E8-CBEC-4414-A64D-B6600A4D3FF6}'] function Get_option: Word; safecall; property option: Word read Get_option; end; // *********************************************************************// // DispIntf: IPenDataOptionDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {200041E8-CBEC-4414-A64D-B6600A4D3FF6} // *********************************************************************// IPenDataOptionDisp = dispinterface ['{200041E8-CBEC-4414-A64D-B6600A4D3FF6}'] property option: {??Word}OleVariant readonly dispid 3585; property rdy: WordBool readonly dispid 3329; property sw: Byte readonly dispid 3330; property pressure: {??Word}OleVariant readonly dispid 3331; property x: {??Word}OleVariant readonly dispid 3332; property y: {??Word}OleVariant readonly dispid 3333; end; // *********************************************************************// // Interface: IPenDataEncrypted // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20007929-8A2A-49DF-8B6D-38B71F8991AB} // *********************************************************************// IPenDataEncrypted = interface(IDispatch) ['{20007929-8A2A-49DF-8B6D-38B71F8991AB}'] function Get_sessionId: SYSUINT; safecall; function Get_penData1: IPenData; safecall; function Get_penData2: IPenData; safecall; property sessionId: SYSUINT read Get_sessionId; property penData1: IPenData read Get_penData1; property penData2: IPenData read Get_penData2; end; // *********************************************************************// // DispIntf: IPenDataEncryptedDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20007929-8A2A-49DF-8B6D-38B71F8991AB} // *********************************************************************// IPenDataEncryptedDisp = dispinterface ['{20007929-8A2A-49DF-8B6D-38B71F8991AB}'] property sessionId: SYSUINT readonly dispid 3841; property penData1: IPenData readonly dispid 3842; property penData2: IPenData readonly dispid 3843; end; // *********************************************************************// // Interface: IPenDataEncryptedOption // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {200088A2-DC76-4716-8879-6E6115A1BBE8} // *********************************************************************// IPenDataEncryptedOption = interface(IPenDataEncrypted) ['{200088A2-DC76-4716-8879-6E6115A1BBE8}'] function Get_option1: Word; safecall; function Get_option2: Word; safecall; property option1: Word read Get_option1; property option2: Word read Get_option2; end; // *********************************************************************// // DispIntf: IPenDataEncryptedOptionDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {200088A2-DC76-4716-8879-6E6115A1BBE8} // *********************************************************************// IPenDataEncryptedOptionDisp = dispinterface ['{200088A2-DC76-4716-8879-6E6115A1BBE8}'] property option1: {??Word}OleVariant readonly dispid 4097; property option2: {??Word}OleVariant readonly dispid 4098; property sessionId: SYSUINT readonly dispid 3841; property penData1: IPenData readonly dispid 3842; property penData2: IPenData readonly dispid 3843; end; // *********************************************************************// // Interface: IProtocolHelper // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {2000550B-EFC5-4D5F-8969-45C9A67CC93C} // *********************************************************************// IProtocolHelper = interface(IDispatch) ['{2000550B-EFC5-4D5F-8969-45C9A67CC93C}'] function statusCanSend(statusCode: Byte; ReportId: Byte; OpDirection: OpDirection): WordBool; safecall; procedure waitForStatusToSend(const Protocol: IProtocol; ReportId: Byte; OpDirection: OpDirection; retries: SYSUINT; sleepBetweenRetries: SYSUINT); safecall; procedure waitForStatus(const Protocol: IProtocol; statusCode: Byte; retries: SYSUINT; sleepBetweenRetries: SYSUINT); safecall; function supportsEncryption(const Protocol: IProtocol): WordBool; safecall; function supportsEncryption_DHprime(dhPrime: PSafeArray): WordBool; safecall; function setHostPublicKeyAndPollForDevicePublicKey(const Protocol: IProtocol; hostPublicKey: PSafeArray; retries: SYSUINT; sleepBetweenRetries: SYSUINT): PSafeArray; safecall; procedure writeImage(const Protocol: IProtocol; encodingMode: Byte; imageData: PSafeArray; retries: SYSUINT; sleepBetweenRetries: SYSUINT); safecall; function flattenMonochrome(image: OleVariant; screenWidth: Word; screenHeight: Word): PSafeArray; safecall; function flattenColor16_565(image: OleVariant; screenWidth: Word; screenHeight: Word): PSafeArray; safecall; function flatten(image: OleVariant; screenWidth: Word; screenHeight: Word; isColor: WordBool): PSafeArray; safecall; function resizeAndFlatten(image: OleVariant; offsetX: SYSUINT; offsetY: SYSUINT; bitmapWidth: SYSUINT; bitmapHeight: SYSUINT; screenWidth: Word; screenHeight: Word; isColor: WordBool; Scale: Scale; backgroundColor: OleVariant; Clip: Byte): PSafeArray; safecall; end; // *********************************************************************// // DispIntf: IProtocolHelperDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {2000550B-EFC5-4D5F-8969-45C9A67CC93C} // *********************************************************************// IProtocolHelperDisp = dispinterface ['{2000550B-EFC5-4D5F-8969-45C9A67CC93C}'] function statusCanSend(statusCode: Byte; ReportId: Byte; OpDirection: OpDirection): WordBool; dispid 6145; procedure waitForStatusToSend(const Protocol: IProtocol; ReportId: Byte; OpDirection: OpDirection; retries: SYSUINT; sleepBetweenRetries: SYSUINT); dispid 6146; procedure waitForStatus(const Protocol: IProtocol; statusCode: Byte; retries: SYSUINT; sleepBetweenRetries: SYSUINT); dispid 6147; function supportsEncryption(const Protocol: IProtocol): WordBool; dispid 6148; function supportsEncryption_DHprime(dhPrime: {??PSafeArray}OleVariant): WordBool; dispid 6149; function setHostPublicKeyAndPollForDevicePublicKey(const Protocol: IProtocol; hostPublicKey: {??PSafeArray}OleVariant; retries: SYSUINT; sleepBetweenRetries: SYSUINT): {??PSafeArray}OleVariant; dispid 6150; procedure writeImage(const Protocol: IProtocol; encodingMode: Byte; imageData: {??PSafeArray}OleVariant; retries: SYSUINT; sleepBetweenRetries: SYSUINT); dispid 6152; function flattenMonochrome(image: OleVariant; screenWidth: {??Word}OleVariant; screenHeight: {??Word}OleVariant): {??PSafeArray}OleVariant; dispid 6153; function flattenColor16_565(image: OleVariant; screenWidth: {??Word}OleVariant; screenHeight: {??Word}OleVariant): {??PSafeArray}OleVariant; dispid 6154; function flatten(image: OleVariant; screenWidth: {??Word}OleVariant; screenHeight: {??Word}OleVariant; isColor: WordBool): {??PSafeArray}OleVariant; dispid 6155; function resizeAndFlatten(image: OleVariant; offsetX: SYSUINT; offsetY: SYSUINT; bitmapWidth: SYSUINT; bitmapHeight: SYSUINT; screenWidth: {??Word}OleVariant; screenHeight: {??Word}OleVariant; isColor: WordBool; Scale: Scale; backgroundColor: OleVariant; Clip: Byte): {??PSafeArray}OleVariant; dispid 6156; end; // *********************************************************************// // Interface: IReport // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {2000122F-B55F-40DE-9284-277D32AEE77F} // *********************************************************************// IReport = interface(IDispatch) ['{2000122F-B55F-40DE-9284-277D32AEE77F}'] function Get_data: PSafeArray; safecall; property data: PSafeArray read Get_data; end; // *********************************************************************// // DispIntf: IReportDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {2000122F-B55F-40DE-9284-277D32AEE77F} // *********************************************************************// IReportDisp = dispinterface ['{2000122F-B55F-40DE-9284-277D32AEE77F}'] property data: {??PSafeArray}OleVariant readonly dispid 1281; end; // *********************************************************************// // Interface: IDecrypt // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20007FDA-B1C5-44F2-A8F8-AFCD4E6A76C2} // *********************************************************************// IDecrypt = interface(IDispatch) ['{20007FDA-B1C5-44F2-A8F8-AFCD4E6A76C2}'] function Get_data: PSafeArray; safecall; procedure Set_data(pRetVal: PSafeArray); safecall; property data: PSafeArray read Get_data write Set_data; end; // *********************************************************************// // DispIntf: IDecryptDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20007FDA-B1C5-44F2-A8F8-AFCD4E6A76C2} // *********************************************************************// IDecryptDisp = dispinterface ['{20007FDA-B1C5-44F2-A8F8-AFCD4E6A76C2}'] property data: {??PSafeArray}OleVariant dispid 5633; end; // *********************************************************************// // Interface: IReportHandler // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {2000446E-736E-4513-9751-A9B69648863E} // *********************************************************************// IReportHandler = interface(IDispatch) ['{2000446E-736E-4513-9751-A9B69648863E}'] function handleReport(data: PSafeArray): WordBool; safecall; end; // *********************************************************************// // DispIntf: IReportHandlerDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {2000446E-736E-4513-9751-A9B69648863E} // *********************************************************************// IReportHandlerDisp = dispinterface ['{2000446E-736E-4513-9751-A9B69648863E}'] function handleReport(data: {??PSafeArray}OleVariant): WordBool; dispid 5121; end; // *********************************************************************// // Interface: ITabletEncryptionHandler // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {2000B2ED-AEDA-4E86-8A69-BB987FA3B238} // *********************************************************************// ITabletEncryptionHandler = interface(IDispatch) ['{2000B2ED-AEDA-4E86-8A69-BB987FA3B238}'] procedure reset; safecall; procedure clearKeys; safecall; function requireDH: WordBool; safecall; procedure setDH(dhPrime: PSafeArray; dhBase: PSafeArray); safecall; function generateHostPublicKey: PSafeArray; safecall; procedure computeSharedKey(devicePublicKey: PSafeArray); safecall; function decrypt(data: PSafeArray): PSafeArray; safecall; end; // *********************************************************************// // DispIntf: ITabletEncryptionHandlerDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {2000B2ED-AEDA-4E86-8A69-BB987FA3B238} // *********************************************************************// ITabletEncryptionHandlerDisp = dispinterface ['{2000B2ED-AEDA-4E86-8A69-BB987FA3B238}'] procedure reset; dispid 7169; procedure clearKeys; dispid 7170; function requireDH: WordBool; dispid 7171; procedure setDH(dhPrime: {??PSafeArray}OleVariant; dhBase: {??PSafeArray}OleVariant); dispid 7172; function generateHostPublicKey: {??PSafeArray}OleVariant; dispid 7173; procedure computeSharedKey(devicePublicKey: {??PSafeArray}OleVariant); dispid 7174; function decrypt(data: {??PSafeArray}OleVariant): {??PSafeArray}OleVariant; dispid 7175; end; // *********************************************************************// // Interface: ITablet // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20005C27-7729-492F-8106-540F2E04DC66} // *********************************************************************// ITablet = interface(IDispatch) ['{20005C27-7729-492F-8106-540F2E04DC66}'] function Get_encryptionHandler: ITabletEncryptionHandler; safecall; procedure Set_encryptionHandler(const pRetVal: ITabletEncryptionHandler); safecall; function usbConnect(const usbDevice: IUsbDevice; exclusiveLock: WordBool): IErrorCode; safecall; function usbConnect2(const fileName: WideString; const bulkFileName: WideString; exclusiveLock: WordBool): IErrorCode; safecall; function serialConnect(const fileName: WideString; useCrc: WordBool): IErrorCode; safecall; function Get_Protocol: IProtocol; safecall; function isEmpty: WordBool; safecall; function isConnected: WordBool; safecall; procedure disconnect; safecall; function interfaceQueue: IInterfaceQueue; safecall; procedure queueNotifyAll; safecall; function supportsWrite: WordBool; safecall; procedure getReportCountLengths(var pRetVal: PSafeArray); safecall; procedure isSupported(ReportId: Byte; var pRetVal: WordBool); safecall; function getStatus: IStatus; safecall; procedure reset; safecall; function getInformation: IInformation; safecall; function getCapability: ICapability; safecall; function getUid: SYSUINT; safecall; procedure setUid(uid: SYSUINT); safecall; function getHostPublicKey: PSafeArray; safecall; function getDevicePublicKey: PSafeArray; safecall; procedure startCapture(sessionId: SYSUINT); safecall; procedure endCapture; safecall; function getDHprime: PSafeArray; safecall; procedure setDHprime(dhPrime: PSafeArray); safecall; function getDHbase: PSafeArray; safecall; procedure setDHbase(dhBase: PSafeArray); safecall; procedure setClearScreen; safecall; function getInkingMode: Byte; safecall; procedure setInkingMode(inkingMode: Byte); safecall; function getInkThreshold: IInkThreshold; safecall; procedure setInkThreshold(const inkThreshold: IInkThreshold); safecall; procedure writeImage(encodingMode: Byte; imageData: PSafeArray); safecall; procedure endImageData; safecall; function getHandwritingThicknessColor: IHandwritingThicknessColor; safecall; procedure setHandwritingThicknessColor(const HandwritingThicknessColor: IHandwritingThicknessColor); safecall; function getBackgroundColor: Word; safecall; procedure setBackgroundColor(backgroundColor: Word); safecall; function getHandwritingDisplayArea: IHandwritingDisplayArea; safecall; procedure setHandwritingDisplayArea(const handwritingDisplayArea: IHandwritingDisplayArea); safecall; function getBacklightBrightness: Word; safecall; procedure setBacklightBrightness(backlightBrightness: Word); safecall; function getPenDataOptionMode: Byte; safecall; procedure setPenDataOptionMode(penDataOptionMode: Byte); safecall; property encryptionHandler: ITabletEncryptionHandler read Get_encryptionHandler write Set_encryptionHandler; property Protocol: IProtocol read Get_Protocol; end; // *********************************************************************// // DispIntf: ITabletDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20005C27-7729-492F-8106-540F2E04DC66} // *********************************************************************// ITabletDisp = dispinterface ['{20005C27-7729-492F-8106-540F2E04DC66}'] property encryptionHandler: ITabletEncryptionHandler dispid 6657; function usbConnect(const usbDevice: IUsbDevice; exclusiveLock: WordBool): IErrorCode; dispid 6658; function usbConnect2(const fileName: WideString; const bulkFileName: WideString; exclusiveLock: WordBool): IErrorCode; dispid 6659; function serialConnect(const fileName: WideString; useCrc: WordBool): IErrorCode; dispid 6660; property Protocol: IProtocol readonly dispid 6661; function isEmpty: WordBool; dispid 6662; function isConnected: WordBool; dispid 6663; procedure disconnect; dispid 6664; function interfaceQueue: IInterfaceQueue; dispid 6665; procedure queueNotifyAll; dispid 6666; function supportsWrite: WordBool; dispid 6667; procedure getReportCountLengths(var pRetVal: {??PSafeArray}OleVariant); dispid 6668; procedure isSupported(ReportId: Byte; var pRetVal: WordBool); dispid 6669; function getStatus: IStatus; dispid 6670; procedure reset; dispid 6671; function getInformation: IInformation; dispid 6672; function getCapability: ICapability; dispid 6673; function getUid: SYSUINT; dispid 6674; procedure setUid(uid: SYSUINT); dispid 6675; function getHostPublicKey: {??PSafeArray}OleVariant; dispid 6676; function getDevicePublicKey: {??PSafeArray}OleVariant; dispid 6677; procedure startCapture(sessionId: SYSUINT); dispid 6678; procedure endCapture; dispid 6679; function getDHprime: {??PSafeArray}OleVariant; dispid 6680; procedure setDHprime(dhPrime: {??PSafeArray}OleVariant); dispid 6681; function getDHbase: {??PSafeArray}OleVariant; dispid 6682; procedure setDHbase(dhBase: {??PSafeArray}OleVariant); dispid 6683; procedure setClearScreen; dispid 6684; function getInkingMode: Byte; dispid 6685; procedure setInkingMode(inkingMode: Byte); dispid 6686; function getInkThreshold: IInkThreshold; dispid 6687; procedure setInkThreshold(const inkThreshold: IInkThreshold); dispid 6688; procedure writeImage(encodingMode: Byte; imageData: {??PSafeArray}OleVariant); dispid 6689; procedure endImageData; dispid 6690; function getHandwritingThicknessColor: IHandwritingThicknessColor; dispid 6691; procedure setHandwritingThicknessColor(const HandwritingThicknessColor: IHandwritingThicknessColor); dispid 6692; function getBackgroundColor: {??Word}OleVariant; dispid 6693; procedure setBackgroundColor(backgroundColor: {??Word}OleVariant); dispid 6694; function getHandwritingDisplayArea: IHandwritingDisplayArea; dispid 6695; procedure setHandwritingDisplayArea(const handwritingDisplayArea: IHandwritingDisplayArea); dispid 6696; function getBacklightBrightness: {??Word}OleVariant; dispid 6697; procedure setBacklightBrightness(backlightBrightness: {??Word}OleVariant); dispid 6698; function getPenDataOptionMode: Byte; dispid 6699; procedure setPenDataOptionMode(penDataOptionMode: Byte); dispid 6700; end; // *********************************************************************// // Interface: IJScript // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {200072FE-6F48-44D0-8C0A-4ABAE07EDFF6} // *********************************************************************// IJScript = interface(IDispatch) ['{200072FE-6F48-44D0-8C0A-4ABAE07EDFF6}'] function toArray(value: PSafeArray): IDispatch; safecall; function toVBArray(const value: IDispatch): PSafeArray; safecall; function toTabletEncryptionHandler(const value: IDispatch): ITabletEncryptionHandler; safecall; end; // *********************************************************************// // DispIntf: IJScriptDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {200072FE-6F48-44D0-8C0A-4ABAE07EDFF6} // *********************************************************************// IJScriptDisp = dispinterface ['{200072FE-6F48-44D0-8C0A-4ABAE07EDFF6}'] function toArray(value: {??PSafeArray}OleVariant): IDispatch; dispid 6401; function toVBArray(const value: IDispatch): {??PSafeArray}OleVariant; dispid 6402; function toTabletEncryptionHandler(const value: IDispatch): ITabletEncryptionHandler; dispid 6403; end; // *********************************************************************// // Interface: IComponentFile // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20005C8A-5280-4C4D-8565-DED24A3672F5} // *********************************************************************// IComponentFile = interface(IDispatch) ['{20005C8A-5280-4C4D-8565-DED24A3672F5}'] function Get_name: WideString; safecall; function Get_version: WideString; safecall; property name: WideString read Get_name; property version: WideString read Get_version; end; // *********************************************************************// // DispIntf: IComponentFileDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20005C8A-5280-4C4D-8565-DED24A3672F5} // *********************************************************************// IComponentFileDisp = dispinterface ['{20005C8A-5280-4C4D-8565-DED24A3672F5}'] property name: WideString readonly dispid 8449; property version: WideString readonly dispid 8450; end; // *********************************************************************// // Interface: IComponentFiles // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {2000A6E2-D773-4829-9B61-78DAC3CCAD82} // *********************************************************************// IComponentFiles = interface(IDispatch) ['{2000A6E2-D773-4829-9B61-78DAC3CCAD82}'] function Get__NewEnum: IUnknown; safecall; function Get_Item(index: OleVariant): IComponentFile; safecall; function Get_Count: Integer; safecall; property _NewEnum: IUnknown read Get__NewEnum; property Item[index: OleVariant]: IComponentFile read Get_Item; default; property Count: Integer read Get_Count; end; // *********************************************************************// // DispIntf: IComponentFilesDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {2000A6E2-D773-4829-9B61-78DAC3CCAD82} // *********************************************************************// IComponentFilesDisp = dispinterface ['{2000A6E2-D773-4829-9B61-78DAC3CCAD82}'] property _NewEnum: IUnknown readonly dispid -4; property Item[index: OleVariant]: IComponentFile readonly dispid 0; default; property Count: Integer readonly dispid 8193; end; // *********************************************************************// // Interface: IComponent // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20001D33-3D2C-4E4D-AFE8-5E5D446637FD} // *********************************************************************// IComponent = interface(IDispatch) ['{20001D33-3D2C-4E4D-AFE8-5E5D446637FD}'] function getProperty(const name: WideString): OleVariant; safecall; procedure setProperty(const name: WideString; value: OleVariant); safecall; function componentFiles: IComponentFiles; safecall; function diagnosticInformation(flag: SYSUINT): WideString; safecall; end; // *********************************************************************// // DispIntf: IComponentDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20001D33-3D2C-4E4D-AFE8-5E5D446637FD} // *********************************************************************// IComponentDisp = dispinterface ['{20001D33-3D2C-4E4D-AFE8-5E5D446637FD}'] function getProperty(const name: WideString): OleVariant; dispid 7937; procedure setProperty(const name: WideString; value: OleVariant); dispid 7938; function componentFiles: IComponentFiles; dispid 7939; function diagnosticInformation(flag: SYSUINT): WideString; dispid 7940; end; // *********************************************************************// // DispIntf: IInterfaceEvents // Flags: (4224) NonExtensible Dispatchable // GUID: {2000A1EE-8F0B-4027-B84E-A8172950CF0C} // *********************************************************************// IInterfaceEvents = dispinterface ['{2000A1EE-8F0B-4027-B84E-A8172950CF0C}'] procedure onReport(const pData: IReport); dispid 1537; end; // *********************************************************************// // DispIntf: IReportHandlerEvents // Flags: (4224) NonExtensible Dispatchable // GUID: {20004D65-E291-4B63-8062-7E99EBD21BDF} // *********************************************************************// IReportHandlerEvents = dispinterface ['{20004D65-E291-4B63-8062-7E99EBD21BDF}'] procedure onPenData(const pPenData: IPenData); dispid 5377; procedure onPenDataOption(const pPenDataOption: IPenDataOption); dispid 5378; procedure onPenDataEncrypted(const pPenDataEncrypted: IPenDataEncrypted); dispid 5379; procedure onPenDataEncryptedOption(const pPenDataEncryptedOption: IPenDataEncryptedOption); dispid 5380; procedure onDevicePublicKey(pDevicePublicKey: {??PSafeArray}OleVariant); dispid 5381; procedure onDecrypt(const pData: IDecrypt); dispid 5382; end; // *********************************************************************// // Interface: ITabletEventsException // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20005380-DA13-492A-A97F-EE5811B49B1C} // *********************************************************************// ITabletEventsException = interface(IDispatch) ['{20005380-DA13-492A-A97F-EE5811B49B1C}'] procedure getException; safecall; end; // *********************************************************************// // DispIntf: ITabletEventsExceptionDisp // Flags: (4544) Dual NonExtensible OleAutomation Dispatchable // GUID: {20005380-DA13-492A-A97F-EE5811B49B1C} // *********************************************************************// ITabletEventsExceptionDisp = dispinterface ['{20005380-DA13-492A-A97F-EE5811B49B1C}'] procedure getException; dispid 7425; end; // *********************************************************************// // DispIntf: ITabletEvents // Flags: (4224) NonExtensible Dispatchable // GUID: {2000C72A-E338-477E-B359-D6D00006D29E} // *********************************************************************// ITabletEvents = dispinterface ['{2000C72A-E338-477E-B359-D6D00006D29E}'] procedure onGetReportException(const pException: ITabletEventsException); dispid 6913; procedure onUnhandledReportData(pData: {??PSafeArray}OleVariant); dispid 6914; procedure onPenData(const pPenData: IPenData); dispid 6915; procedure onPenDataOption(const pPenDataOption: IPenDataOption); dispid 6916; procedure onPenDataEncrypted(const pPenDataEncrypted: IPenDataEncrypted); dispid 6917; procedure onPenDataEncryptedOption(const pPenDataEncryptedOption: IPenDataEncryptedOption); dispid 6918; procedure onDevicePublicKey(pDevicePublicKey: {??PSafeArray}OleVariant); dispid 6919; end; // *********************************************************************// // The Class CoUsbInterface provides a Create and CreateRemote method to // create instances of the default interface IUsbInterface exposed by // the CoClass UsbInterface. The functions are intended to be used by // clients wishing to automate the CoClass objects exposed by the // server of this typelibrary. // *********************************************************************// CoUsbInterface = class class function Create: IUsbInterface; class function CreateRemote(const MachineName: string): IUsbInterface; end; TUsbInterfaceonReport = procedure(ASender: TObject; const pData: IReport) of object; // *********************************************************************// // OLE Server Proxy class declaration // Server Object : TUsbInterface // Help String : // Default Interface: IUsbInterface // Def. Intf. DISP? : No // Event Interface: IInterfaceEvents // TypeFlags : (2) CanCreate // *********************************************************************// {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} TUsbInterfaceProperties= class; {$ENDIF} TUsbInterface = class(TOleServer) private FOnonReport: TUsbInterfaceonReport; FIntf: IUsbInterface; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps: TUsbInterfaceProperties; function GetServerProperties: TUsbInterfaceProperties; {$ENDIF} function GetDefaultInterface: IUsbInterface; protected procedure InitServerData; override; procedure InvokeEvent(DispID: TDispID; var Params: TVariantArray); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Connect; override; procedure ConnectTo(svrIntf: IUsbInterface); procedure Disconnect; override; function connect1(const usbDevice: IUsbDevice; exclusiveLock: WordBool): IErrorCode; function connect2(const fileName: WideString; const bulkFileName: WideString; exclusiveLock: WordBool): IErrorCode; property DefaultInterface: IUsbInterface read GetDefaultInterface; published {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} property Server: TUsbInterfaceProperties read GetServerProperties; {$ENDIF} property OnonReport: TUsbInterfaceonReport read FOnonReport write FOnonReport; end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} // *********************************************************************// // OLE Server Properties Proxy Class // Server Object : TUsbInterface // (This object is used by the IDE's Property Inspector to allow editing // of the properties of this server) // *********************************************************************// TUsbInterfaceProperties = class(TPersistent) private FServer: TUsbInterface; function GetDefaultInterface: IUsbInterface; constructor Create(AServer: TUsbInterface); protected public property DefaultInterface: IUsbInterface read GetDefaultInterface; published end; {$ENDIF} // *********************************************************************// // The Class CoSerialInterface provides a Create and CreateRemote method to // create instances of the default interface ISerialInterface exposed by // the CoClass SerialInterface. The functions are intended to be used by // clients wishing to automate the CoClass objects exposed by the // server of this typelibrary. // *********************************************************************// CoSerialInterface = class class function Create: ISerialInterface; class function CreateRemote(const MachineName: string): ISerialInterface; end; TSerialInterfaceonReport = procedure(ASender: TObject; const pData: IReport) of object; // *********************************************************************// // OLE Server Proxy class declaration // Server Object : TSerialInterface // Help String : // Default Interface: ISerialInterface // Def. Intf. DISP? : No // Event Interface: IInterfaceEvents // TypeFlags : (2) CanCreate // *********************************************************************// {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} TSerialInterfaceProperties= class; {$ENDIF} TSerialInterface = class(TOleServer) private FOnonReport: TSerialInterfaceonReport; FIntf: ISerialInterface; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps: TSerialInterfaceProperties; function GetServerProperties: TSerialInterfaceProperties; {$ENDIF} function GetDefaultInterface: ISerialInterface; protected procedure InitServerData; override; procedure InvokeEvent(DispID: TDispID; var Params: TVariantArray); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Connect; override; procedure ConnectTo(svrIntf: ISerialInterface); procedure Disconnect; override; function connect1(const fileName: WideString; useCrc: WordBool): IErrorCode; property DefaultInterface: ISerialInterface read GetDefaultInterface; published {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} property Server: TSerialInterfaceProperties read GetServerProperties; {$ENDIF} property OnonReport: TSerialInterfaceonReport read FOnonReport write FOnonReport; end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} // *********************************************************************// // OLE Server Properties Proxy Class // Server Object : TSerialInterface // (This object is used by the IDE's Property Inspector to allow editing // of the properties of this server) // *********************************************************************// TSerialInterfaceProperties = class(TPersistent) private FServer: TSerialInterface; function GetDefaultInterface: ISerialInterface; constructor Create(AServer: TSerialInterface); protected public property DefaultInterface: ISerialInterface read GetDefaultInterface; published end; {$ENDIF} // *********************************************************************// // The Class CoUsbDevices provides a Create and CreateRemote method to // create instances of the default interface IUsbDevices exposed by // the CoClass UsbDevices. The functions are intended to be used by // clients wishing to automate the CoClass objects exposed by the // server of this typelibrary. // *********************************************************************// CoUsbDevices = class class function Create: IUsbDevices; class function CreateRemote(const MachineName: string): IUsbDevices; end; // *********************************************************************// // OLE Server Proxy class declaration // Server Object : TUsbDevices // Help String : // Default Interface: IUsbDevices // Def. Intf. DISP? : No // Event Interface: // TypeFlags : (2) CanCreate // *********************************************************************// {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} TUsbDevicesProperties= class; {$ENDIF} TUsbDevices = class(TOleServer) private FIntf: IUsbDevices; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps: TUsbDevicesProperties; function GetServerProperties: TUsbDevicesProperties; {$ENDIF} function GetDefaultInterface: IUsbDevices; protected procedure InitServerData; override; function Get__NewEnum: IUnknown; function Get_Item(index: OleVariant): IUsbDevice; function Get_Count: Integer; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Connect; override; procedure ConnectTo(svrIntf: IUsbDevices); procedure Disconnect; override; property DefaultInterface: IUsbDevices read GetDefaultInterface; property _NewEnum: IUnknown read Get__NewEnum; property Item[index: OleVariant]: IUsbDevice read Get_Item; default; property Count: Integer read Get_Count; published {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} property Server: TUsbDevicesProperties read GetServerProperties; {$ENDIF} end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} // *********************************************************************// // OLE Server Properties Proxy Class // Server Object : TUsbDevices // (This object is used by the IDE's Property Inspector to allow editing // of the properties of this server) // *********************************************************************// TUsbDevicesProperties = class(TPersistent) private FServer: TUsbDevices; function GetDefaultInterface: IUsbDevices; constructor Create(AServer: TUsbDevices); protected function Get__NewEnum: IUnknown; function Get_Item(index: OleVariant): IUsbDevice; function Get_Count: Integer; public property DefaultInterface: IUsbDevices read GetDefaultInterface; published end; {$ENDIF} // *********************************************************************// // The Class CoJScript provides a Create and CreateRemote method to // create instances of the default interface IJScript exposed by // the CoClass JScript. The functions are intended to be used by // clients wishing to automate the CoClass objects exposed by the // server of this typelibrary. // *********************************************************************// CoJScript = class class function Create: IJScript; class function CreateRemote(const MachineName: string): IJScript; end; // *********************************************************************// // OLE Server Proxy class declaration // Server Object : TJScript // Help String : // Default Interface: IJScript // Def. Intf. DISP? : No // Event Interface: // TypeFlags : (2) CanCreate // *********************************************************************// {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} TJScriptProperties= class; {$ENDIF} TJScript = class(TOleServer) private FIntf: IJScript; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps: TJScriptProperties; function GetServerProperties: TJScriptProperties; {$ENDIF} function GetDefaultInterface: IJScript; protected procedure InitServerData; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Connect; override; procedure ConnectTo(svrIntf: IJScript); procedure Disconnect; override; function toArray(value: PSafeArray): IDispatch; function toVBArray(const value: IDispatch): PSafeArray; function toTabletEncryptionHandler(const value: IDispatch): ITabletEncryptionHandler; property DefaultInterface: IJScript read GetDefaultInterface; published {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} property Server: TJScriptProperties read GetServerProperties; {$ENDIF} end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} // *********************************************************************// // OLE Server Properties Proxy Class // Server Object : TJScript // (This object is used by the IDE's Property Inspector to allow editing // of the properties of this server) // *********************************************************************// TJScriptProperties = class(TPersistent) private FServer: TJScript; function GetDefaultInterface: IJScript; constructor Create(AServer: TJScript); protected public property DefaultInterface: IJScript read GetDefaultInterface; published end; {$ENDIF} // *********************************************************************// // The Class CoProtocolHelper provides a Create and CreateRemote method to // create instances of the default interface IProtocolHelper exposed by // the CoClass ProtocolHelper. The functions are intended to be used by // clients wishing to automate the CoClass objects exposed by the // server of this typelibrary. // *********************************************************************// CoProtocolHelper = class class function Create: IProtocolHelper; class function CreateRemote(const MachineName: string): IProtocolHelper; end; // *********************************************************************// // OLE Server Proxy class declaration // Server Object : TProtocolHelper // Help String : // Default Interface: IProtocolHelper // Def. Intf. DISP? : No // Event Interface: // TypeFlags : (2) CanCreate // *********************************************************************// {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} TProtocolHelperProperties= class; {$ENDIF} TProtocolHelper = class(TOleServer) private FIntf: IProtocolHelper; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps: TProtocolHelperProperties; function GetServerProperties: TProtocolHelperProperties; {$ENDIF} function GetDefaultInterface: IProtocolHelper; protected procedure InitServerData; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Connect; override; procedure ConnectTo(svrIntf: IProtocolHelper); procedure Disconnect; override; function statusCanSend(statusCode: Byte; ReportId: Byte; OpDirection: OpDirection): WordBool; procedure waitForStatusToSend(const Protocol: IProtocol; ReportId: Byte; OpDirection: OpDirection; retries: SYSUINT; sleepBetweenRetries: SYSUINT); procedure waitForStatus(const Protocol: IProtocol; statusCode: Byte; retries: SYSUINT; sleepBetweenRetries: SYSUINT); function supportsEncryption(const Protocol: IProtocol): WordBool; function supportsEncryption_DHprime(dhPrime: PSafeArray): WordBool; function setHostPublicKeyAndPollForDevicePublicKey(const Protocol: IProtocol; hostPublicKey: PSafeArray; retries: SYSUINT; sleepBetweenRetries: SYSUINT): PSafeArray; procedure writeImage(const Protocol: IProtocol; encodingMode: Byte; imageData: PSafeArray; retries: SYSUINT; sleepBetweenRetries: SYSUINT); function flattenMonochrome(image: OleVariant; screenWidth: Word; screenHeight: Word): PSafeArray; function flattenColor16_565(image: OleVariant; screenWidth: Word; screenHeight: Word): PSafeArray; function flatten(image: OleVariant; screenWidth: Word; screenHeight: Word; isColor: WordBool): PSafeArray; function resizeAndFlatten(image: OleVariant; offsetX: SYSUINT; offsetY: SYSUINT; bitmapWidth: SYSUINT; bitmapHeight: SYSUINT; screenWidth: Word; screenHeight: Word; isColor: WordBool; Scale: Scale; backgroundColor: OleVariant; Clip: Byte): PSafeArray; property DefaultInterface: IProtocolHelper read GetDefaultInterface; published {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} property Server: TProtocolHelperProperties read GetServerProperties; {$ENDIF} end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} // *********************************************************************// // OLE Server Properties Proxy Class // Server Object : TProtocolHelper // (This object is used by the IDE's Property Inspector to allow editing // of the properties of this server) // *********************************************************************// TProtocolHelperProperties = class(TPersistent) private FServer: TProtocolHelper; function GetDefaultInterface: IProtocolHelper; constructor Create(AServer: TProtocolHelper); protected public property DefaultInterface: IProtocolHelper read GetDefaultInterface; published end; {$ENDIF} // *********************************************************************// // The Class CoReportHandler provides a Create and CreateRemote method to // create instances of the default interface IReportHandler exposed by // the CoClass ReportHandler. The functions are intended to be used by // clients wishing to automate the CoClass objects exposed by the // server of this typelibrary. // *********************************************************************// CoReportHandler = class class function Create: IReportHandler; class function CreateRemote(const MachineName: string): IReportHandler; end; TReportHandleronPenData = procedure(ASender: TObject; const pPenData: IPenData) of object; TReportHandleronPenDataOption = procedure(ASender: TObject; const pPenDataOption: IPenDataOption) of object; TReportHandleronPenDataEncrypted = procedure(ASender: TObject; const pPenDataEncrypted: IPenDataEncrypted) of object; TReportHandleronPenDataEncryptedOption = procedure(ASender: TObject; const pPenDataEncryptedOption: IPenDataEncryptedOption) of object; TReportHandleronDevicePublicKey = procedure(ASender: TObject; pDevicePublicKey: {??PSafeArray}OleVariant) of object; TReportHandleronDecrypt = procedure(ASender: TObject; const pData: IDecrypt) of object; // *********************************************************************// // OLE Server Proxy class declaration // Server Object : TReportHandler // Help String : // Default Interface: IReportHandler // Def. Intf. DISP? : No // Event Interface: IReportHandlerEvents // TypeFlags : (2) CanCreate // *********************************************************************// {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} TReportHandlerProperties= class; {$ENDIF} TReportHandler = class(TOleServer) private FOnonPenData: TReportHandleronPenData; FOnonPenDataOption: TReportHandleronPenDataOption; FOnonPenDataEncrypted: TReportHandleronPenDataEncrypted; FOnonPenDataEncryptedOption: TReportHandleronPenDataEncryptedOption; FOnonDevicePublicKey: TReportHandleronDevicePublicKey; FOnonDecrypt: TReportHandleronDecrypt; FIntf: IReportHandler; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps: TReportHandlerProperties; function GetServerProperties: TReportHandlerProperties; {$ENDIF} function GetDefaultInterface: IReportHandler; protected procedure InitServerData; override; procedure InvokeEvent(DispID: TDispID; var Params: TVariantArray); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Connect; override; procedure ConnectTo(svrIntf: IReportHandler); procedure Disconnect; override; function handleReport(data: PSafeArray): WordBool; property DefaultInterface: IReportHandler read GetDefaultInterface; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} property Server: TReportHandlerProperties read GetServerProperties; {$ENDIF} property OnonPenData: TReportHandleronPenData read FOnonPenData write FOnonPenData; property OnonPenDataOption: TReportHandleronPenDataOption read FOnonPenDataOption write FOnonPenDataOption; property OnonPenDataEncrypted: TReportHandleronPenDataEncrypted read FOnonPenDataEncrypted write FOnonPenDataEncrypted; property OnonPenDataEncryptedOption: TReportHandleronPenDataEncryptedOption read FOnonPenDataEncryptedOption write FOnonPenDataEncryptedOption; property OnonDevicePublicKey: TReportHandleronDevicePublicKey read FOnonDevicePublicKey write FOnonDevicePublicKey; property OnonDecrypt: TReportHandleronDecrypt read FOnonDecrypt write FOnonDecrypt; end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} // *********************************************************************// // OLE Server Properties Proxy Class // Server Object : TReportHandler // (This object is used by the IDE's Property Inspector to allow editing // of the properties of this server) // *********************************************************************// TReportHandlerProperties = class(TPersistent) private FServer: TReportHandler; function GetDefaultInterface: IReportHandler; constructor Create(AServer: TReportHandler); protected public property DefaultInterface: IReportHandler read GetDefaultInterface; published end; {$ENDIF} // *********************************************************************// // The Class CoTablet provides a Create and CreateRemote method to // create instances of the default interface ITablet exposed by // the CoClass Tablet. The functions are intended to be used by // clients wishing to automate the CoClass objects exposed by the // server of this typelibrary. // *********************************************************************// CoTablet = class class function Create: ITablet; class function CreateRemote(const MachineName: string): ITablet; end; TTabletonGetReportException = procedure(ASender: TObject; const pException: ITabletEventsException) of object; TTabletonUnhandledReportData = procedure(ASender: TObject; pData: {??PSafeArray}OleVariant) of object; TTabletonPenData = procedure(ASender: TObject; const pPenData: IPenData) of object; TTabletonPenDataOption = procedure(ASender: TObject; const pPenDataOption: IPenDataOption) of object; TTabletonPenDataEncrypted = procedure(ASender: TObject; const pPenDataEncrypted: IPenDataEncrypted) of object; TTabletonPenDataEncryptedOption = procedure(ASender: TObject; const pPenDataEncryptedOption: IPenDataEncryptedOption) of object; TTabletonDevicePublicKey = procedure(ASender: TObject; pDevicePublicKey: {??PSafeArray}OleVariant) of object; // *********************************************************************// // OLE Server Proxy class declaration // Server Object : TTablet // Help String : // Default Interface: ITablet // Def. Intf. DISP? : No // Event Interface: ITabletEvents // TypeFlags : (2) CanCreate // *********************************************************************// {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} TTabletProperties= class; {$ENDIF} TTablet = class(TOleServer) private FOnonGetReportException: TTabletonGetReportException; FOnonUnhandledReportData: TTabletonUnhandledReportData; FOnonPenData: TTabletonPenData; FOnonPenDataOption: TTabletonPenDataOption; FOnonPenDataEncrypted: TTabletonPenDataEncrypted; FOnonPenDataEncryptedOption: TTabletonPenDataEncryptedOption; FOnonDevicePublicKey: TTabletonDevicePublicKey; FIntf: ITablet; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps: TTabletProperties; function GetServerProperties: TTabletProperties; {$ENDIF} function GetDefaultInterface: ITablet; protected procedure InitServerData; override; procedure InvokeEvent(DispID: TDispID; var Params: TVariantArray); override; function Get_encryptionHandler: ITabletEncryptionHandler; procedure Set_encryptionHandler(const pRetVal: ITabletEncryptionHandler); function Get_Protocol: IProtocol; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Connect; override; procedure ConnectTo(svrIntf: ITablet); procedure Disconnect; override; function usbConnect(const usbDevice: IUsbDevice; exclusiveLock: WordBool): IErrorCode; function usbConnect2(const fileName: WideString; const bulkFileName: WideString; exclusiveLock: WordBool): IErrorCode; function serialConnect(const fileName: WideString; useCrc: WordBool): IErrorCode; function isEmpty: WordBool; function isConnected: WordBool; procedure disconnect1; function interfaceQueue: IInterfaceQueue; procedure queueNotifyAll; function supportsWrite: WordBool; procedure getReportCountLengths(var pRetVal: PSafeArray); procedure isSupported(ReportId: Byte; var pRetVal: WordBool); function getStatus: IStatus; procedure reset; function getInformation: IInformation; function getCapability: ICapability; function getUid: SYSUINT; procedure setUid(uid: SYSUINT); function getHostPublicKey: PSafeArray; function getDevicePublicKey: PSafeArray; procedure startCapture(sessionId: SYSUINT); procedure endCapture; function getDHprime: PSafeArray; procedure setDHprime(dhPrime: PSafeArray); function getDHbase: PSafeArray; procedure setDHbase(dhBase: PSafeArray); procedure setClearScreen; function getInkingMode: Byte; procedure setInkingMode(inkingMode: Byte); function getInkThreshold: IInkThreshold; procedure setInkThreshold(const inkThreshold: IInkThreshold); procedure writeImage(encodingMode: Byte; imageData: PSafeArray); procedure endImageData; function getHandwritingThicknessColor: IHandwritingThicknessColor; procedure setHandwritingThicknessColor(const HandwritingThicknessColor: IHandwritingThicknessColor); function getBackgroundColor: Word; procedure setBackgroundColor(backgroundColor: Word); function getHandwritingDisplayArea: IHandwritingDisplayArea; procedure setHandwritingDisplayArea(const handwritingDisplayArea: IHandwritingDisplayArea); function getBacklightBrightness: Word; procedure setBacklightBrightness(backlightBrightness: Word); function getPenDataOptionMode: Byte; procedure setPenDataOptionMode(penDataOptionMode: Byte); property DefaultInterface: ITablet read GetDefaultInterface; property Protocol: IProtocol read Get_Protocol; property encryptionHandler: ITabletEncryptionHandler read Get_encryptionHandler write Set_encryptionHandler; published {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} property Server: TTabletProperties read GetServerProperties; {$ENDIF} property OnonGetReportException: TTabletonGetReportException read FOnonGetReportException write FOnonGetReportException; property OnonUnhandledReportData: TTabletonUnhandledReportData read FOnonUnhandledReportData write FOnonUnhandledReportData; property OnonPenData: TTabletonPenData read FOnonPenData write FOnonPenData; property OnonPenDataOption: TTabletonPenDataOption read FOnonPenDataOption write FOnonPenDataOption; property OnonPenDataEncrypted: TTabletonPenDataEncrypted read FOnonPenDataEncrypted write FOnonPenDataEncrypted; property OnonPenDataEncryptedOption: TTabletonPenDataEncryptedOption read FOnonPenDataEncryptedOption write FOnonPenDataEncryptedOption; property OnonDevicePublicKey: TTabletonDevicePublicKey read FOnonDevicePublicKey write FOnonDevicePublicKey; end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} // *********************************************************************// // OLE Server Properties Proxy Class // Server Object : TTablet // (This object is used by the IDE's Property Inspector to allow editing // of the properties of this server) // *********************************************************************// TTabletProperties = class(TPersistent) private FServer: TTablet; function GetDefaultInterface: ITablet; constructor Create(AServer: TTablet); protected function Get_encryptionHandler: ITabletEncryptionHandler; procedure Set_encryptionHandler(const pRetVal: ITabletEncryptionHandler); function Get_Protocol: IProtocol; public property DefaultInterface: ITablet read GetDefaultInterface; published property encryptionHandler: ITabletEncryptionHandler read Get_encryptionHandler write Set_encryptionHandler; end; {$ENDIF} // *********************************************************************// // The Class CoComponent provides a Create and CreateRemote method to // create instances of the default interface IComponent exposed by // the CoClass Component. The functions are intended to be used by // clients wishing to automate the CoClass objects exposed by the // server of this typelibrary. // *********************************************************************// CoComponent = class class function Create: IComponent; class function CreateRemote(const MachineName: string): IComponent; end; // *********************************************************************// // OLE Server Proxy class declaration // Server Object : TComponent // Help String : // Default Interface: IComponent // Def. Intf. DISP? : No // Event Interface: // TypeFlags : (2) CanCreate // *********************************************************************// {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} TComponentProperties= class; {$ENDIF} TComponent2 = class(TOleServer) private FIntf: IComponent; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps: TComponentProperties; function GetServerProperties: TComponentProperties; {$ENDIF} function GetDefaultInterface: IComponent; protected procedure InitServerData; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Connect; override; procedure ConnectTo(svrIntf: IComponent); procedure Disconnect; override; function getProperty(const name: WideString): OleVariant; procedure setProperty(const name: WideString; value: OleVariant); function componentFiles: IComponentFiles; function diagnosticInformation(flag: SYSUINT): WideString; property DefaultInterface: IComponent read GetDefaultInterface; published {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} property Server: TComponentProperties read GetServerProperties; {$ENDIF} end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} // *********************************************************************// // OLE Server Properties Proxy Class // Server Object : TComponent // (This object is used by the IDE's Property Inspector to allow editing // of the properties of this server) // *********************************************************************// TComponentProperties = class(TPersistent) private FServer: TComponent; function GetDefaultInterface: IComponent; constructor Create(AServer: TComponent); protected public property DefaultInterface: IComponent read GetDefaultInterface; published end; {$ENDIF} procedure Register; resourcestring dtlServerPage = 'ActiveX'; dtlOcxPage = 'ActiveX'; implementation uses ComObj; class function CoUsbInterface.Create: IUsbInterface; begin Result := CreateComObject(CLASS_UsbInterface) as IUsbInterface; end; class function CoUsbInterface.CreateRemote(const MachineName: string): IUsbInterface; begin Result := CreateRemoteComObject(MachineName, CLASS_UsbInterface) as IUsbInterface; end; procedure TUsbInterface.InitServerData; const CServerData: TServerData = ( ClassID: '{2000BC66-5735-45C7-9521-93FAAFE8C3BB}'; IntfIID: '{2000C1D7-8270-490B-A8F3-766258E6BAB9}'; EventIID: '{2000A1EE-8F0B-4027-B84E-A8172950CF0C}'; LicenseKey: nil; Version: 500); begin ServerData := @CServerData; end; procedure TUsbInterface.Connect; var punk: IUnknown; begin if FIntf = nil then begin punk := GetServer; ConnectEvents(punk); Fintf:= punk as IUsbInterface; end; end; procedure TUsbInterface.ConnectTo(svrIntf: IUsbInterface); begin Disconnect; FIntf := svrIntf; ConnectEvents(FIntf); end; procedure TUsbInterface.DisConnect; begin if Fintf <> nil then begin DisconnectEvents(FIntf); FIntf := nil; end; end; function TUsbInterface.GetDefaultInterface: IUsbInterface; begin if FIntf = nil then Connect; Assert(FIntf <> nil, 'DefaultInterface is NULL. Component is not connected to Server. You must call ''Connect'' or ''ConnectTo'' before this operation'); Result := FIntf; end; constructor TUsbInterface.Create(AOwner: TComponent); begin inherited Create(AOwner); {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps := TUsbInterfaceProperties.Create(Self); {$ENDIF} end; destructor TUsbInterface.Destroy; begin {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps.Free; {$ENDIF} inherited Destroy; end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} function TUsbInterface.GetServerProperties: TUsbInterfaceProperties; begin Result := FProps; end; {$ENDIF} procedure TUsbInterface.InvokeEvent(DispID: TDispID; var Params: TVariantArray); begin case DispID of -1: Exit; // DISPID_UNKNOWN 1537: if Assigned(FOnonReport) then FOnonReport(Self, IUnknown(TVarData(Params[0]).VPointer) as IReport {const IReport}); end; {case DispID} end; function TUsbInterface.connect1(const usbDevice: IUsbDevice; exclusiveLock: WordBool): IErrorCode; begin Result := DefaultInterface.connect(usbDevice, exclusiveLock); end; function TUsbInterface.connect2(const fileName: WideString; const bulkFileName: WideString; exclusiveLock: WordBool): IErrorCode; begin Result := DefaultInterface.connect2(fileName, bulkFileName, exclusiveLock); end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} constructor TUsbInterfaceProperties.Create(AServer: TUsbInterface); begin inherited Create; FServer := AServer; end; function TUsbInterfaceProperties.GetDefaultInterface: IUsbInterface; begin Result := FServer.DefaultInterface; end; {$ENDIF} class function CoSerialInterface.Create: ISerialInterface; begin Result := CreateComObject(CLASS_SerialInterface) as ISerialInterface; end; class function CoSerialInterface.CreateRemote(const MachineName: string): ISerialInterface; begin Result := CreateRemoteComObject(MachineName, CLASS_SerialInterface) as ISerialInterface; end; procedure TSerialInterface.InitServerData; const CServerData: TServerData = ( ClassID: '{20001CFF-184E-4E32-9FC4-A617533D342E}'; IntfIID: '{20003D0C-A047-4487-8FE0-0CF9AB05E48C}'; EventIID: '{2000A1EE-8F0B-4027-B84E-A8172950CF0C}'; LicenseKey: nil; Version: 500); begin ServerData := @CServerData; end; procedure TSerialInterface.Connect; var punk: IUnknown; begin if FIntf = nil then begin punk := GetServer; ConnectEvents(punk); Fintf:= punk as ISerialInterface; end; end; procedure TSerialInterface.ConnectTo(svrIntf: ISerialInterface); begin Disconnect; FIntf := svrIntf; ConnectEvents(FIntf); end; procedure TSerialInterface.DisConnect; begin if Fintf <> nil then begin DisconnectEvents(FIntf); FIntf := nil; end; end; function TSerialInterface.GetDefaultInterface: ISerialInterface; begin if FIntf = nil then Connect; Assert(FIntf <> nil, 'DefaultInterface is NULL. Component is not connected to Server. You must call ''Connect'' or ''ConnectTo'' before this operation'); Result := FIntf; end; constructor TSerialInterface.Create(AOwner: TComponent); begin inherited Create(AOwner); {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps := TSerialInterfaceProperties.Create(Self); {$ENDIF} end; destructor TSerialInterface.Destroy; begin {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps.Free; {$ENDIF} inherited Destroy; end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} function TSerialInterface.GetServerProperties: TSerialInterfaceProperties; begin Result := FProps; end; {$ENDIF} procedure TSerialInterface.InvokeEvent(DispID: TDispID; var Params: TVariantArray); begin case DispID of -1: Exit; // DISPID_UNKNOWN 1537: if Assigned(FOnonReport) then FOnonReport(Self, IUnknown(TVarData(Params[0]).VPointer) as IReport {const IReport}); end; {case DispID} end; function TSerialInterface.connect1(const fileName: WideString; useCrc: WordBool): IErrorCode; begin Result := DefaultInterface.connect(fileName, useCrc); end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} constructor TSerialInterfaceProperties.Create(AServer: TSerialInterface); begin inherited Create; FServer := AServer; end; function TSerialInterfaceProperties.GetDefaultInterface: ISerialInterface; begin Result := FServer.DefaultInterface; end; {$ENDIF} class function CoUsbDevices.Create: IUsbDevices; begin Result := CreateComObject(CLASS_UsbDevices) as IUsbDevices; end; class function CoUsbDevices.CreateRemote(const MachineName: string): IUsbDevices; begin Result := CreateRemoteComObject(MachineName, CLASS_UsbDevices) as IUsbDevices; end; procedure TUsbDevices.InitServerData; const CServerData: TServerData = ( ClassID: '{2000D7A5-64F7-4826-B56E-85ACC618E4D6}'; IntfIID: '{20008CC2-6576-4665-8411-99291CF18387}'; EventIID: ''; LicenseKey: nil; Version: 500); begin ServerData := @CServerData; end; procedure TUsbDevices.Connect; var punk: IUnknown; begin if FIntf = nil then begin punk := GetServer; Fintf:= punk as IUsbDevices; end; end; procedure TUsbDevices.ConnectTo(svrIntf: IUsbDevices); begin Disconnect; FIntf := svrIntf; end; procedure TUsbDevices.DisConnect; begin if Fintf <> nil then begin FIntf := nil; end; end; function TUsbDevices.GetDefaultInterface: IUsbDevices; begin if FIntf = nil then Connect; Assert(FIntf <> nil, 'DefaultInterface is NULL. Component is not connected to Server. You must call ''Connect'' or ''ConnectTo'' before this operation'); Result := FIntf; end; constructor TUsbDevices.Create(AOwner: TComponent); begin inherited Create(AOwner); {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps := TUsbDevicesProperties.Create(Self); {$ENDIF} end; destructor TUsbDevices.Destroy; begin {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps.Free; {$ENDIF} inherited Destroy; end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} function TUsbDevices.GetServerProperties: TUsbDevicesProperties; begin Result := FProps; end; {$ENDIF} function TUsbDevices.Get__NewEnum: IUnknown; begin Result := DefaultInterface._NewEnum; end; function TUsbDevices.Get_Item(index: OleVariant): IUsbDevice; begin Result := DefaultInterface.Item[index]; end; function TUsbDevices.Get_Count: Integer; begin Result := DefaultInterface.Count; end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} constructor TUsbDevicesProperties.Create(AServer: TUsbDevices); begin inherited Create; FServer := AServer; end; function TUsbDevicesProperties.GetDefaultInterface: IUsbDevices; begin Result := FServer.DefaultInterface; end; function TUsbDevicesProperties.Get__NewEnum: IUnknown; begin Result := DefaultInterface._NewEnum; end; function TUsbDevicesProperties.Get_Item(index: OleVariant): IUsbDevice; begin Result := DefaultInterface.Item[index]; end; function TUsbDevicesProperties.Get_Count: Integer; begin Result := DefaultInterface.Count; end; {$ENDIF} class function CoJScript.Create: IJScript; begin Result := CreateComObject(CLASS_JScript) as IJScript; end; class function CoJScript.CreateRemote(const MachineName: string): IJScript; begin Result := CreateRemoteComObject(MachineName, CLASS_JScript) as IJScript; end; procedure TJScript.InitServerData; const CServerData: TServerData = ( ClassID: '{2000D408-6AFE-4CBA-BDB1-DA087DA66B05}'; IntfIID: '{200072FE-6F48-44D0-8C0A-4ABAE07EDFF6}'; EventIID: ''; LicenseKey: nil; Version: 500); begin ServerData := @CServerData; end; procedure TJScript.Connect; var punk: IUnknown; begin if FIntf = nil then begin punk := GetServer; Fintf:= punk as IJScript; end; end; procedure TJScript.ConnectTo(svrIntf: IJScript); begin Disconnect; FIntf := svrIntf; end; procedure TJScript.DisConnect; begin if Fintf <> nil then begin FIntf := nil; end; end; function TJScript.GetDefaultInterface: IJScript; begin if FIntf = nil then Connect; Assert(FIntf <> nil, 'DefaultInterface is NULL. Component is not connected to Server. You must call ''Connect'' or ''ConnectTo'' before this operation'); Result := FIntf; end; constructor TJScript.Create(AOwner: TComponent); begin inherited Create(AOwner); {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps := TJScriptProperties.Create(Self); {$ENDIF} end; destructor TJScript.Destroy; begin {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps.Free; {$ENDIF} inherited Destroy; end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} function TJScript.GetServerProperties: TJScriptProperties; begin Result := FProps; end; {$ENDIF} function TJScript.toArray(value: PSafeArray): IDispatch; begin Result := DefaultInterface.toArray(value); end; function TJScript.toVBArray(const value: IDispatch): PSafeArray; begin Result := DefaultInterface.toVBArray(value); end; function TJScript.toTabletEncryptionHandler(const value: IDispatch): ITabletEncryptionHandler; begin Result := DefaultInterface.toTabletEncryptionHandler(value); end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} constructor TJScriptProperties.Create(AServer: TJScript); begin inherited Create; FServer := AServer; end; function TJScriptProperties.GetDefaultInterface: IJScript; begin Result := FServer.DefaultInterface; end; {$ENDIF} class function CoProtocolHelper.Create: IProtocolHelper; begin Result := CreateComObject(CLASS_ProtocolHelper) as IProtocolHelper; end; class function CoProtocolHelper.CreateRemote(const MachineName: string): IProtocolHelper; begin Result := CreateRemoteComObject(MachineName, CLASS_ProtocolHelper) as IProtocolHelper; end; procedure TProtocolHelper.InitServerData; const CServerData: TServerData = ( ClassID: '{2000CF89-E182-40AD-A8C2-5694987EA5DF}'; IntfIID: '{2000550B-EFC5-4D5F-8969-45C9A67CC93C}'; EventIID: ''; LicenseKey: nil; Version: 500); begin ServerData := @CServerData; end; procedure TProtocolHelper.Connect; var punk: IUnknown; begin if FIntf = nil then begin punk := GetServer; Fintf:= punk as IProtocolHelper; end; end; procedure TProtocolHelper.ConnectTo(svrIntf: IProtocolHelper); begin Disconnect; FIntf := svrIntf; end; procedure TProtocolHelper.DisConnect; begin if Fintf <> nil then begin FIntf := nil; end; end; function TProtocolHelper.GetDefaultInterface: IProtocolHelper; begin if FIntf = nil then Connect; Assert(FIntf <> nil, 'DefaultInterface is NULL. Component is not connected to Server. You must call ''Connect'' or ''ConnectTo'' before this operation'); Result := FIntf; end; constructor TProtocolHelper.Create(AOwner: TComponent); begin inherited Create(AOwner); {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps := TProtocolHelperProperties.Create(Self); {$ENDIF} end; destructor TProtocolHelper.Destroy; begin {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps.Free; {$ENDIF} inherited Destroy; end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} function TProtocolHelper.GetServerProperties: TProtocolHelperProperties; begin Result := FProps; end; {$ENDIF} function TProtocolHelper.statusCanSend(statusCode: Byte; ReportId: Byte; OpDirection: OpDirection): WordBool; begin Result := DefaultInterface.statusCanSend(statusCode, ReportId, OpDirection); end; procedure TProtocolHelper.waitForStatusToSend(const Protocol: IProtocol; ReportId: Byte; OpDirection: OpDirection; retries: SYSUINT; sleepBetweenRetries: SYSUINT); begin DefaultInterface.waitForStatusToSend(Protocol, ReportId, OpDirection, retries, sleepBetweenRetries); end; procedure TProtocolHelper.waitForStatus(const Protocol: IProtocol; statusCode: Byte; retries: SYSUINT; sleepBetweenRetries: SYSUINT); begin DefaultInterface.waitForStatus(Protocol, statusCode, retries, sleepBetweenRetries); end; function TProtocolHelper.supportsEncryption(const Protocol: IProtocol): WordBool; begin Result := DefaultInterface.supportsEncryption(Protocol); end; function TProtocolHelper.supportsEncryption_DHprime(dhPrime: PSafeArray): WordBool; begin Result := DefaultInterface.supportsEncryption_DHprime(dhPrime); end; function TProtocolHelper.setHostPublicKeyAndPollForDevicePublicKey(const Protocol: IProtocol; hostPublicKey: PSafeArray; retries: SYSUINT; sleepBetweenRetries: SYSUINT): PSafeArray; begin Result := DefaultInterface.setHostPublicKeyAndPollForDevicePublicKey(Protocol, hostPublicKey, retries, sleepBetweenRetries); end; procedure TProtocolHelper.writeImage(const Protocol: IProtocol; encodingMode: Byte; imageData: PSafeArray; retries: SYSUINT; sleepBetweenRetries: SYSUINT); begin DefaultInterface.writeImage(Protocol, encodingMode, imageData, retries, sleepBetweenRetries); end; function TProtocolHelper.flattenMonochrome(image: OleVariant; screenWidth: Word; screenHeight: Word): PSafeArray; begin Result := DefaultInterface.flattenMonochrome(image, screenWidth, screenHeight); end; function TProtocolHelper.flattenColor16_565(image: OleVariant; screenWidth: Word; screenHeight: Word): PSafeArray; begin Result := DefaultInterface.flattenColor16_565(image, screenWidth, screenHeight); end; function TProtocolHelper.flatten(image: OleVariant; screenWidth: Word; screenHeight: Word; isColor: WordBool): PSafeArray; begin Result := DefaultInterface.flatten(image, screenWidth, screenHeight, isColor); end; function TProtocolHelper.resizeAndFlatten(image: OleVariant; offsetX: SYSUINT; offsetY: SYSUINT; bitmapWidth: SYSUINT; bitmapHeight: SYSUINT; screenWidth: Word; screenHeight: Word; isColor: WordBool; Scale: Scale; backgroundColor: OleVariant; Clip: Byte): PSafeArray; begin Result := DefaultInterface.resizeAndFlatten(image, offsetX, offsetY, bitmapWidth, bitmapHeight, screenWidth, screenHeight, isColor, Scale, backgroundColor, Clip); end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} constructor TProtocolHelperProperties.Create(AServer: TProtocolHelper); begin inherited Create; FServer := AServer; end; function TProtocolHelperProperties.GetDefaultInterface: IProtocolHelper; begin Result := FServer.DefaultInterface; end; {$ENDIF} class function CoReportHandler.Create: IReportHandler; begin Result := CreateComObject(CLASS_ReportHandler) as IReportHandler; end; class function CoReportHandler.CreateRemote(const MachineName: string): IReportHandler; begin Result := CreateRemoteComObject(MachineName, CLASS_ReportHandler) as IReportHandler; end; procedure TReportHandler.InitServerData; const CServerData: TServerData = ( ClassID: '{20008BA5-8133-45BA-91A5-AB54A1F70E13}'; IntfIID: '{2000446E-736E-4513-9751-A9B69648863E}'; EventIID: '{20004D65-E291-4B63-8062-7E99EBD21BDF}'; LicenseKey: nil; Version: 500); begin ServerData := @CServerData; end; procedure TReportHandler.Connect; var punk: IUnknown; begin if FIntf = nil then begin punk := GetServer; ConnectEvents(punk); Fintf:= punk as IReportHandler; end; end; procedure TReportHandler.ConnectTo(svrIntf: IReportHandler); begin Disconnect; FIntf := svrIntf; ConnectEvents(FIntf); end; procedure TReportHandler.DisConnect; begin if Fintf <> nil then begin DisconnectEvents(FIntf); FIntf := nil; end; end; function TReportHandler.GetDefaultInterface: IReportHandler; begin if FIntf = nil then Connect; Assert(FIntf <> nil, 'DefaultInterface is NULL. Component is not connected to Server. You must call ''Connect'' or ''ConnectTo'' before this operation'); Result := FIntf; end; constructor TReportHandler.Create(AOwner: TComponent); begin inherited Create(AOwner); {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps := TReportHandlerProperties.Create(Self); {$ENDIF} end; destructor TReportHandler.Destroy; begin {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps.Free; {$ENDIF} inherited Destroy; end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} function TReportHandler.GetServerProperties: TReportHandlerProperties; begin Result := FProps; end; {$ENDIF} procedure TReportHandler.InvokeEvent(DispID: TDispID; var Params: TVariantArray); begin case DispID of -1: Exit; // DISPID_UNKNOWN 5377: if Assigned(FOnonPenData) then FOnonPenData(Self, IUnknown(TVarData(Params[0]).VPointer) as IPenData {const IPenData}); 5378: if Assigned(FOnonPenDataOption) then FOnonPenDataOption(Self, IUnknown(TVarData(Params[0]).VPointer) as IPenDataOption {const IPenDataOption}); 5379: if Assigned(FOnonPenDataEncrypted) then FOnonPenDataEncrypted(Self, IUnknown(TVarData(Params[0]).VPointer) as IPenDataEncrypted {const IPenDataEncrypted}); 5380: if Assigned(FOnonPenDataEncryptedOption) then FOnonPenDataEncryptedOption(Self, IUnknown(TVarData(Params[0]).VPointer) as IPenDataEncryptedOption {const IPenDataEncryptedOption}); 5381: if Assigned(FOnonDevicePublicKey) then FOnonDevicePublicKey(Self, Params[0] { ??PSafeArray OleVariant}); 5382: if Assigned(FOnonDecrypt) then FOnonDecrypt(Self, IUnknown(TVarData(Params[0]).VPointer) as IDecrypt {const IDecrypt}); end; {case DispID} end; function TReportHandler.handleReport(data: PSafeArray): WordBool; begin Result := DefaultInterface.handleReport(data); end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} constructor TReportHandlerProperties.Create(AServer: TReportHandler); begin inherited Create; FServer := AServer; end; function TReportHandlerProperties.GetDefaultInterface: IReportHandler; begin Result := FServer.DefaultInterface; end; {$ENDIF} class function CoTablet.Create: ITablet; begin Result := CreateComObject(CLASS_Tablet) as ITablet; end; class function CoTablet.CreateRemote(const MachineName: string): ITablet; begin Result := CreateRemoteComObject(MachineName, CLASS_Tablet) as ITablet; end; procedure TTablet.InitServerData; const CServerData: TServerData = ( ClassID: '{20002178-1165-4D38-A7F5-B169DE2045C1}'; IntfIID: '{20005C27-7729-492F-8106-540F2E04DC66}'; EventIID: '{2000C72A-E338-477E-B359-D6D00006D29E}'; LicenseKey: nil; Version: 500); begin ServerData := @CServerData; end; procedure TTablet.Connect; var punk: IUnknown; begin if FIntf = nil then begin punk := GetServer; ConnectEvents(punk); Fintf:= punk as ITablet; end; end; procedure TTablet.ConnectTo(svrIntf: ITablet); begin Disconnect; FIntf := svrIntf; ConnectEvents(FIntf); end; procedure TTablet.DisConnect; begin if Fintf <> nil then begin DisconnectEvents(FIntf); FIntf := nil; end; end; function TTablet.GetDefaultInterface: ITablet; begin if FIntf = nil then Connect; Assert(FIntf <> nil, 'DefaultInterface is NULL. Component is not connected to Server. You must call ''Connect'' or ''ConnectTo'' before this operation'); Result := FIntf; end; constructor TTablet.Create(AOwner: TComponent); begin inherited Create(AOwner); {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps := TTabletProperties.Create(Self); {$ENDIF} end; destructor TTablet.Destroy; begin {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps.Free; {$ENDIF} inherited Destroy; end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} function TTablet.GetServerProperties: TTabletProperties; begin Result := FProps; end; {$ENDIF} procedure TTablet.InvokeEvent(DispID: TDispID; var Params: TVariantArray); begin case DispID of -1: Exit; // DISPID_UNKNOWN 6913: if Assigned(FOnonGetReportException) then FOnonGetReportException(Self, IUnknown(TVarData(Params[0]).VPointer) as ITabletEventsException {const ITabletEventsException}); 6914: if Assigned(FOnonUnhandledReportData) then FOnonUnhandledReportData(Self, Params[0] { ??PSafeArray OleVariant}); 6915: if Assigned(FOnonPenData) then FOnonPenData(Self, IUnknown(TVarData(Params[0]).VPointer) as IPenData {const IPenData}); 6916: if Assigned(FOnonPenDataOption) then FOnonPenDataOption(Self, IUnknown(TVarData(Params[0]).VPointer) as IPenDataOption {const IPenDataOption}); 6917: if Assigned(FOnonPenDataEncrypted) then FOnonPenDataEncrypted(Self, IUnknown(TVarData(Params[0]).VPointer) as IPenDataEncrypted {const IPenDataEncrypted}); 6918: if Assigned(FOnonPenDataEncryptedOption) then FOnonPenDataEncryptedOption(Self, IUnknown(TVarData(Params[0]).VPointer) as IPenDataEncryptedOption {const IPenDataEncryptedOption}); 6919: if Assigned(FOnonDevicePublicKey) then FOnonDevicePublicKey(Self, Params[0] { ??PSafeArray OleVariant}); end; {case DispID} end; function TTablet.Get_encryptionHandler: ITabletEncryptionHandler; begin Result := DefaultInterface.encryptionHandler; end; procedure TTablet.Set_encryptionHandler(const pRetVal: ITabletEncryptionHandler); begin DefaultInterface.Set_encryptionHandler(pRetVal); end; function TTablet.Get_Protocol: IProtocol; begin Result := DefaultInterface.Protocol; end; function TTablet.usbConnect(const usbDevice: IUsbDevice; exclusiveLock: WordBool): IErrorCode; begin Result := DefaultInterface.usbConnect(usbDevice, exclusiveLock); end; function TTablet.usbConnect2(const fileName: WideString; const bulkFileName: WideString; exclusiveLock: WordBool): IErrorCode; begin Result := DefaultInterface.usbConnect2(fileName, bulkFileName, exclusiveLock); end; function TTablet.serialConnect(const fileName: WideString; useCrc: WordBool): IErrorCode; begin Result := DefaultInterface.serialConnect(fileName, useCrc); end; function TTablet.isEmpty: WordBool; begin Result := DefaultInterface.isEmpty; end; function TTablet.isConnected: WordBool; begin Result := DefaultInterface.isConnected; end; procedure TTablet.disconnect1; begin DefaultInterface.disconnect; end; function TTablet.interfaceQueue: IInterfaceQueue; begin Result := DefaultInterface.interfaceQueue; end; procedure TTablet.queueNotifyAll; begin DefaultInterface.queueNotifyAll; end; function TTablet.supportsWrite: WordBool; begin Result := DefaultInterface.supportsWrite; end; procedure TTablet.getReportCountLengths(var pRetVal: PSafeArray); begin DefaultInterface.getReportCountLengths(pRetVal); end; procedure TTablet.isSupported(ReportId: Byte; var pRetVal: WordBool); begin DefaultInterface.isSupported(ReportId, pRetVal); end; function TTablet.getStatus: IStatus; begin Result := DefaultInterface.getStatus; end; procedure TTablet.reset; begin DefaultInterface.reset; end; function TTablet.getInformation: IInformation; begin Result := DefaultInterface.getInformation; end; function TTablet.getCapability: ICapability; begin Result := DefaultInterface.getCapability; end; function TTablet.getUid: SYSUINT; begin Result := DefaultInterface.getUid; end; procedure TTablet.setUid(uid: SYSUINT); begin DefaultInterface.setUid(uid); end; function TTablet.getHostPublicKey: PSafeArray; begin Result := DefaultInterface.getHostPublicKey; end; function TTablet.getDevicePublicKey: PSafeArray; begin Result := DefaultInterface.getDevicePublicKey; end; procedure TTablet.startCapture(sessionId: SYSUINT); begin DefaultInterface.startCapture(sessionId); end; procedure TTablet.endCapture; begin DefaultInterface.endCapture; end; function TTablet.getDHprime: PSafeArray; begin Result := DefaultInterface.getDHprime; end; procedure TTablet.setDHprime(dhPrime: PSafeArray); begin DefaultInterface.setDHprime(dhPrime); end; function TTablet.getDHbase: PSafeArray; begin Result := DefaultInterface.getDHbase; end; procedure TTablet.setDHbase(dhBase: PSafeArray); begin DefaultInterface.setDHbase(dhBase); end; procedure TTablet.setClearScreen; begin DefaultInterface.setClearScreen; end; function TTablet.getInkingMode: Byte; begin Result := DefaultInterface.getInkingMode; end; procedure TTablet.setInkingMode(inkingMode: Byte); begin DefaultInterface.setInkingMode(inkingMode); end; function TTablet.getInkThreshold: IInkThreshold; begin Result := DefaultInterface.getInkThreshold; end; procedure TTablet.setInkThreshold(const inkThreshold: IInkThreshold); begin DefaultInterface.setInkThreshold(inkThreshold); end; procedure TTablet.writeImage(encodingMode: Byte; imageData: PSafeArray); begin DefaultInterface.writeImage(encodingMode, imageData); end; procedure TTablet.endImageData; begin DefaultInterface.endImageData; end; function TTablet.getHandwritingThicknessColor: IHandwritingThicknessColor; begin Result := DefaultInterface.getHandwritingThicknessColor; end; procedure TTablet.setHandwritingThicknessColor(const HandwritingThicknessColor: IHandwritingThicknessColor); begin DefaultInterface.setHandwritingThicknessColor(HandwritingThicknessColor); end; function TTablet.getBackgroundColor: Word; begin Result := DefaultInterface.getBackgroundColor; end; procedure TTablet.setBackgroundColor(backgroundColor: Word); begin DefaultInterface.setBackgroundColor(backgroundColor); end; function TTablet.getHandwritingDisplayArea: IHandwritingDisplayArea; begin Result := DefaultInterface.getHandwritingDisplayArea; end; procedure TTablet.setHandwritingDisplayArea(const handwritingDisplayArea: IHandwritingDisplayArea); begin DefaultInterface.setHandwritingDisplayArea(handwritingDisplayArea); end; function TTablet.getBacklightBrightness: Word; begin Result := DefaultInterface.getBacklightBrightness; end; procedure TTablet.setBacklightBrightness(backlightBrightness: Word); begin DefaultInterface.setBacklightBrightness(backlightBrightness); end; function TTablet.getPenDataOptionMode: Byte; begin Result := DefaultInterface.getPenDataOptionMode; end; procedure TTablet.setPenDataOptionMode(penDataOptionMode: Byte); begin DefaultInterface.setPenDataOptionMode(penDataOptionMode); end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} constructor TTabletProperties.Create(AServer: TTablet); begin inherited Create; FServer := AServer; end; function TTabletProperties.GetDefaultInterface: ITablet; begin Result := FServer.DefaultInterface; end; function TTabletProperties.Get_encryptionHandler: ITabletEncryptionHandler; begin Result := DefaultInterface.encryptionHandler; end; procedure TTabletProperties.Set_encryptionHandler(const pRetVal: ITabletEncryptionHandler); begin DefaultInterface.Set_encryptionHandler(pRetVal); end; function TTabletProperties.Get_Protocol: IProtocol; begin Result := DefaultInterface.Protocol; end; {$ENDIF} class function CoComponent.Create: IComponent; begin Result := CreateComObject(CLASS_Component) as IComponent; end; class function CoComponent.CreateRemote(const MachineName: string): IComponent; begin Result := CreateRemoteComObject(MachineName, CLASS_Component) as IComponent; end; procedure TComponent2.InitServerData; const CServerData: TServerData = ( ClassID: '{20000000-5D96-46B0-895F-B0CC7295E44D}'; IntfIID: '{20001D33-3D2C-4E4D-AFE8-5E5D446637FD}'; EventIID: ''; LicenseKey: nil; Version: 500); begin ServerData := @CServerData; end; procedure TComponent2.Connect; var punk: IUnknown; begin if FIntf = nil then begin punk := GetServer; Fintf:= punk as IComponent; end; end; procedure TComponent2.ConnectTo(svrIntf: IComponent); begin Disconnect; FIntf := svrIntf; end; procedure TComponent2.DisConnect; begin if Fintf <> nil then begin FIntf := nil; end; end; function TComponent2.GetDefaultInterface: IComponent; begin if FIntf = nil then Connect; Assert(FIntf <> nil, 'DefaultInterface is NULL. Component is not connected to Server. You must call ''Connect'' or ''ConnectTo'' before this operation'); Result := FIntf; end; constructor TComponent2.Create(AOwner: TComponent); begin inherited Create(AOwner); {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps := TComponentProperties.Create(Self); {$ENDIF} end; destructor TComponent2.Destroy; begin {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} FProps.Free; {$ENDIF} inherited Destroy; end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} function TComponent.GetServerProperties: TComponentProperties; begin Result := FProps; end; {$ENDIF} function TComponent2.getProperty(const name: WideString): OleVariant; begin Result := DefaultInterface.getProperty(name); end; procedure TComponent2.setProperty(const name: WideString; value: OleVariant); begin DefaultInterface.setProperty(name, value); end; function TComponent2.componentFiles: IComponentFiles; begin Result := DefaultInterface.componentFiles; end; function TComponent2.diagnosticInformation(flag: SYSUINT): WideString; begin Result := DefaultInterface.diagnosticInformation(flag); end; {$IFDEF LIVE_SERVER_AT_DESIGN_TIME} constructor TComponentProperties.Create(AServer: TComponent); begin inherited Create; FServer := AServer; end; function TComponentProperties.GetDefaultInterface: IComponent; begin Result := FServer.DefaultInterface; end; {$ENDIF} procedure Register; begin RegisterComponents(dtlServerPage, [TUsbInterface, TSerialInterface, TUsbDevices, TJScript, TProtocolHelper, TReportHandler, TTablet, TComponent]); end; end. ======================================== FICHERO: Wincrypt.pas ======================================== unit Wincrypt; interface uses Windows; const CERT_STORE_PROV_SYSTEM = PAnsiChar(10); CERT_SYSTEM_STORE_CURRENT_USER = (1 shl 16); CERT_SYSTEM_STORE_LOCAL_MACHINE = (2 shl 16); X509_ASN_ENCODING = $00000001; PKCS_7_ASN_ENCODING = $00010000; CERT_FIND_ANY = 0; CERT_KEY_PROV_INFO_PROP_ID = 2; CERT_NAME_FRIENDLY_DISPLAY_TYPE = 5; CERT_NAME_SIMPLE_DISPLAY_TYPE = 4; // --- SECCIÓN AÑADIDA QUE FALTABA --- type HCRYPTPROV = THandle; // Definición del tipo que faltaba HCERTSTORE = Pointer; PCCERT_CONTEXT = Pointer; // --- FIN DE LA SECCIÓN AÑADIDA --- function CertOpenSystemStore(hProv: HCRYPTPROV; szSubsystemProtocol: PAnsiChar): HCERTSTORE; stdcall; external 'crypt32.dll' name 'CertOpenSystemStoreA'; function CertCloseStore(hCertStore: HCERTSTORE; dwFlags: DWORD): BOOL; stdcall; external 'crypt32.dll'; function CertFindCertificateInStore(hCertStore: HCERTSTORE; dwCertEncodingType: DWORD; dwFindFlags: DWORD; dwFindType: DWORD; pvFindPara: Pointer; pPrevCertContext: PCCERT_CONTEXT): PCCERT_CONTEXT; stdcall; external 'crypt32.dll'; function CertGetCertificateContextProperty(pCertContext: PCCERT_CONTEXT; dwPropId: DWORD; pvData: Pointer; out pcbData: DWORD): BOOL; stdcall; external 'crypt32.dll'; function CertGetNameString(pCertContext: PCCERT_CONTEXT; dwType: DWORD; dwFlags: DWORD; pvTypePara: Pointer; pszNameString: LPWSTR; cchNameString: DWORD): DWORD; stdcall; external 'crypt32.dll' name 'CertGetNameStringW'; function CertDuplicateCertificateContext(pCertContext: PCCERT_CONTEXT): PCCERT_CONTEXT; stdcall; external 'crypt32.dll'; function CertFreeCertificateContext(pCertContext: PCCERT_CONTEXT): BOOL; stdcall; external 'crypt32.dll'; implementation end.