unit principal;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Touch.Keyboard, Vcl.ExtCtrls,
  Vcl.StdCtrls, Vcl.Mask, Vcl.DBCtrls, Vcl.Grids, Vcl.DBGrids,
  ZAbstractConnection, ZConnection, ZAbstractDataset, ZDataset, Data.DB,
  ZAbstractRODataset, CPort,strutils, Vcl.ComCtrls, ZAbstractTable, frxClass,
  frxExportPDF, frxBarcode, frxDBSet, Vcl.ImgList, frxExportBaseDialog;//, frxExportBaseDialog;

type
  Tgeneral = class(TForm)
    Panel3: TPanel;
    dsqpalets1: TDataSource;
    qpalets1: TZReadOnlyQuery;
    qpalets1id: TIntegerField;
    qpalets1ide: TIntegerField;
    qpalets1codigo: TWideStringField;
    qpalets1descripcion: TWideStringField;
    qpalets1largo: TFloatField;
    qpalets1alto: TFloatField;
    qpalets1ancho: TFloatField;
    qpalets1tara: TFloatField;
    qpalets1tipo: TWideStringField;
    qpalets1activo: TIntegerField;
    vehiculos: TZReadOnlyQuery;
    dsvehiculos: TDataSource;
    vehiculosIDEMPRESA: TIntegerField;
    vehiculosID: TWideStringField;
    vehiculosTIPO: TWideStringField;
    vehiculosDESCRIPCION: TWideStringField;
    vehiculosFECHA_COMPRA: TDateField;
    vehiculosACTIVO: TIntegerField;
    qdestinos: TZReadOnlyQuery;
    dsalmacenes: TDataSource;
    qcajas: TZReadOnlyQuery;
    dscajas: TDataSource;
    Parriba: TPanel;
    dsqpalets2: TDataSource;
    qpalets2: TZReadOnlyQuery;
    RadioGroup1: TRadioGroup;
    rentradas: TRadioButton;
    renvasados: TRadioButton;
    lpeso2: TLabel;
    dspartidas: TDataSource;
    dsentradas: TDataSource;
    dspesadas: TDataSource;
    qpartidas: TZQuery;
    tfecha: TDateTimePicker;
    qparcelas: TZReadOnlyQuery;
    qmprimas: TZReadOnlyQuery;
    dsqparcelas: TDataSource;
    dsqmprimas: TDataSource;
    qmprimasid: TWideStringField;
    qmprimasdescripcion: TWideStringField;
    qmprimasobservaciones: TWideStringField;
    qmprimasimagen: TBlobField;
    qmprimasEAN: TWideStringField;
    qmprimasactivo: TIntegerField;
    qparcelascodpar: TWideStringField;
    qparcelasempresa: TIntegerField;
    qparcelasnombre: TWideStringField;
    qparcelasvariedad: TWideStringField;
    qparcelasnum_plantas: TIntegerField;
    qparcelasfecha_plantacion: TDateField;
    qparcelasmarco_plantacion: TWideStringField;
    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;
    tpartidas: TZTable;
    dstpartidas: TDataSource;
    tpartidasid: TIntegerField;
    tpartidaside: TIntegerField;
    tpartidasfecha: TDateField;
    tpartidasid_parcela: TWideStringField;
    tpartidasid_mprimas: TWideStringField;
    qcajasid: TIntegerField;
    qcajaside: TIntegerField;
    qcajascodigo: TWideStringField;
    qcajasdescripcion: TWideStringField;
    qcajaslargo: TFloatField;
    qcajasalto: TFloatField;
    qcajasancho: TFloatField;
    qcajastara: TFloatField;
    qcajastipo: TWideStringField;
    qcajasactivo: TIntegerField;
    Puerto2: TComPort;
    qdestinosid: TIntegerField;
    qdestinosnombre: TWideStringField;
    qdestinoscapacidad: TIntegerField;
    qdestinosstock_kg: TFloatField;
    qdestinosstock_cajas: TIntegerField;
    qdestinosstock_palets: TIntegerField;
    Timer1: TTimer;
    informes: TfrxReport;
    INFORMEDB: TfrxDBDataset;
    frxBarCodeObject1: TfrxBarCodeObject;
    pdfexport: TfrxPDFExport;
    qinfpartidas: TZReadOnlyQuery;
    qinfpartidasid: TIntegerField;
    qinfpartidasfecha: TDateField;
    qinfpartidasnombre: TWideStringField;
    qinfpartidasdescripcion: TWideStringField;
    qinfpartidasmatricula: TWideStringField;
    qinfpartidasnum_palets: TIntegerField;
    qinfpartidasid_envase: TWideStringField;
    qinfpartidasnum_envases: TIntegerField;
    qinfpartidaspeso_bruto: TFloatField;
    qinfpartidastara: TFloatField;
    qinfpartidaspeso_neto: TFloatField;
    qinfpartidaspeso_medio: TFloatField;
    qinfpartidastemperatura: TFloatField;
    dsqinfpartidas: TDataSource;
    qinfpartidascea: TWideStringField;
    Timer2: TTimer;
    qinfpartidasid_1: TIntegerField;
    qinfpartidasdestino: TWideStringField;
    Pbajo: TPanel;
    PEntradasDetalle: TPanel;
    PEtiquetas: TPanel;
    Label9: TLabel;
    Label10: TLabel;
    Button2: TButton;
    Button1: TButton;
    Panel1: TPanel;
    Panel2: TPanel;
    Label8: TLabel;
    DBGrid1: TDBGrid;
    DBGrid3: TDBGrid;
    Panel9: TPanel;
    Label12: TLabel;
    Psalidasdetalle: TPanel;
    PEtiquetas2: TPanel;
    Label13: TLabel;
    Label14: TLabel;
    Button6: TButton;
    Button7: TButton;
    Panel12: TPanel;
    gridpesadasalidas: TDBGrid;
    Panel13: TPanel;
    Label15: TLabel;
    DBGrid5: TDBGrid;
    DBGrid6: TDBGrid;
    Panel14: TPanel;
    Label16: TLabel;
    Pmedio: TPanel;
    Pmovimientos: TPanel;
    Panel17: TPanel;
    Label17: TLabel;
    Panel19: TPanel;
    combodestino: TDBLookupComboBox;
    Label18: TLabel;
    Label19: TLabel;
    comboorigen: TDBLookupComboBox;
    tid: TEdit;
    qorigenes: TZReadOnlyQuery;
    dsqorigenes: TDataSource;
    qorigenesid: TIntegerField;
    qorigenesidempresa: TIntegerField;
    qorigenesnombre: TWideStringField;
    qorigenescapacidad: TIntegerField;
    qorigenesstock_kg: TFloatField;
    qorigenesstock_cajas: TIntegerField;
    qorigenesstock_palets: TIntegerField;
    qorigenesfinal: TIntegerField;
    qorigenesactivo: TIntegerField;
    qdestinosidempresa: TIntegerField;
    qdestinosfinal: TIntegerField;
    qdestinoscoste_kg_dia: TFloatField;
    qdestinospreguntar_generador: TIntegerField;
    qdestinosactivo: TIntegerField;
    qpalets2id: TIntegerField;
    qpalets2ide: TIntegerField;
    qpalets2codigo: TWideStringField;
    qpalets2cod_logi: TIntegerField;
    qpalets2descripcion: TWideStringField;
    qpalets2largo: TFloatField;
    qpalets2alto: TFloatField;
    qpalets2ancho: TFloatField;
    qpalets2tara: TFloatField;
    qpalets2peso_venta: TFloatField;
    qpalets2tipo: TWideStringField;
    qpalets2palet: TIntegerField;
    qpalets2envase_trabajo: TIntegerField;
    qpalets2envase_venta: TIntegerField;
    qpalets2costo: TFloatField;
    qpalets2activo: TIntegerField;
    qpalets2observaciones: TWideStringField;
    LHORA: TLabel;
    qparcelassuperficie: TFloatField;
    qparcelasest_meteo: TWideStringField;
    qparcelascoste_kg_ref: TFloatField;
    qdestinosmermas: TIntegerField;
    qdestinosproduccion: TIntegerField;
    qorigenescoste_kg_dia: TFloatField;
    qorigenespreguntar_generador: TIntegerField;
    qorigenesmermas: TIntegerField;
    qorigenesproduccion: TIntegerField;
    qpalets2facturar_pesofijo: TIntegerField;
    qinfpartidaslote: TIntegerField;
    qdestinostipo_trabajo: TWideStringField;
    qorigenestipo_trabajo: TWideStringField;
    qcajascod_logi: TIntegerField;
    qcajaspeso_venta: TFloatField;
    qcajaspalet: TIntegerField;
    qcajasenvase_trabajo: TIntegerField;
    qcajasenvase_venta: TIntegerField;
    qcajascosto: TFloatField;
    qcajasobservaciones: TWideStringField;
    qcajasfacturar_pesofijo: TIntegerField;
    qdestinoscamara: TIntegerField;
    qdestinosalmacen_asociado: TIntegerField;
    qorigenescamara: TIntegerField;
    qorigenesalmacen_asociado: TIntegerField;
    comboentrada: TDBLookupComboBox;
    qpalets2preguntar_gen: TIntegerField;
    qcajaspreguntar_gen: TIntegerField;
    qmprimasidempresa: TIntegerField;
    qmprimasvariedad: TWideStringField;
    qmprimasbasculas: TIntegerField;
    qmprimasusar_precio_parcela: TIntegerField;
    qmprimasdesechos: TIntegerField;
    qmprimascompuesto: TIntegerField;
    informedb2: TfrxDBDataset;
    qinfpartidastara0: TFloatField;
    qinfpartidaspartida: TIntegerField;
    ImageList2: TImageList;
    rmovimientos: TRadioButton;
    listaiconos: TImageList;
    PEntradasSalidas: TPanel;
    plotes: TPanel;
    plotes2: TPanel;
    gridlotestmp: TDBGrid;
    Panel16: TPanel;
    Label52: TLabel;
    Label53: TLabel;
    Label54: TLabel;
    Label55: TLabel;
    lbultos: TEdit;
    edpeso_es: TEdit;
    ltara: TEdit;
    lneto: TEdit;
    RadioButton4: TRadioButton;
    teclado: TTouchKeyboard;
    qformatoscajas: TZReadOnlyQuery;
    dsqformatoscajas: TDataSource;
    dsqformatos: TDataSource;
    qcalibres: TZReadOnlyQuery;
    qcalibresid: TIntegerField;
    qcalibresdescripcion: TWideStringField;
    qcalibresvalor: TWideStringField;
    DBGrid2: TDBGrid;
    dsqcalibres: TDataSource;
    qaux: TZReadOnlyQuery;
    Panel21: TPanel;
    Label45: TLabel;
    combolotes_es: TDBLookupComboBox;
    Label61: TLabel;
    comboentradas_es: TDBLookupComboBox;
    btnuevaentrada: TButton;
    Label47: TLabel;
    comboenvases_es: TDBLookupComboBox;
    porigenmatprima: TPanel;
    Label62: TLabel;
    comboorigen_es: TDBLookupComboBox;
    Label65: TLabel;
    combovariedad_es: TDBLookupComboBox;
    comboformatos_es: TDBLookupComboBox;
    lenvases_es: TEdit;
    Label48: TLabel;
    btnuevolote: TButton;
    btborrarlote: TButton;
    Label46: TLabel;
    DBText9: TDBText;
    Panel20: TPanel;
    Label57: TLabel;
    Label63: TLabel;
    Label64: TLabel;
    ltemperatura: TEdit;
    combopalets_es: TDBLookupComboBox;
    edpalets_es: TEdit;
    ltaraanterior: TEdit;
    btguardar: TButton;
    Label49: TLabel;
    Label58: TLabel;
    combodestino_es: TDBLookupComboBox;
    Label50: TLabel;
    combocalibre_es: TDBLookupComboBox;
    qformatoscajaside: TIntegerField;
    qformatoscajasidcfg: TIntegerField;
    qformatoscajasidenv: TIntegerField;
    qformatoscajascodigo: TWideStringField;
    qformatoscajasdescripcion: TWideStringField;
    qformatoscajasimagen: TBlobField;
    qformatoscajasnomimagen: TWideStringField;
    qformatoscajasextension: TWideStringField;
    qformatoscajasid: TIntegerField;
    qformatoscajaside_1: TIntegerField;
    qformatoscajasdescripcion_1: TWideStringField;
    qformatoscajasactivo: TIntegerField;
    Label56: TLabel;
    lventa_es: TEdit;
    PExpediciones: TPanel;
    PExpedicionesdetalle: TPanel;
    qmprimasmesas: TIntegerField;
    qmprimasidgenerico: TIntegerField;
    qcajasformatos: TZReadOnlyQuery;
    qcajasformatoside: TIntegerField;
    qcajasformatosidea: TIntegerField;
    qcajasformatosidea2: TIntegerField;
    qcajasformatosid_envase: TIntegerField;
    qcajasformatosid_formato: TIntegerField;
    qcajasformatoscajas: TLargeintField;
    qpedidos: TZReadOnlyQuery;
    dsqpedidos: TDataSource;
    qpedidosdetalle: TZReadOnlyQuery;
    dspedidosdetalle: TDataSource;
    qpedidosdetalleid: TIntegerField;
    qpedidosdetalleide: TIntegerField;
    qpedidosdetalleids: TWideStringField;
    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;
    qpedidoside: TIntegerField;
    qpedidosid: TIntegerField;
    qpedidosidcliente: TIntegerField;
    qpedidosnombre: TWideStringField;
    qpedidosiddestino: TWideStringField;
    qpedidosdescripcion: TWideStringField;
    qpedidosfecha_pedido: TDateField;
    qpedidosfecha_entrega: TDateField;
    qpedidoshora_carga: TTimeField;
    DBGrid7: TDBGrid;
    DBMemo1: TDBMemo;
    qinfpartidastrazabilidad: TWideStringField;
    comdata1: TComDataPacket;
    comdata2: TComDataPacket;
    Panel15: TPanel;
    Panel18: TPanel;
    DBGrid8: TDBGrid;
    Panel22: TPanel;
    dsqpesadas: TDataSource;
    dsqpesadaslotes: TDataSource;
    dsqpesadastmp: TDataSource;
    Panel23: TPanel;
    DBGrid9: TDBGrid;
    Panel24: TPanel;
    Panel25: TPanel;
    Panel26: TPanel;
    Panel27: TPanel;
    Button15: TButton;
    Button14: TButton;
    Label20: TLabel;
    DBText10: TDBText;
    Label21: TLabel;
    DBText11: TDBText;
    Label22: TLabel;
    DBText12: TDBText;
    Label23: TLabel;
    DBText13: TDBText;
    Label25: TLabel;
    DBText14: TDBText;
    DBText15: TDBText;
    Label27: TLabel;
    DBText16: TDBText;
    Label28: TLabel;
    Label29: TLabel;
    DBText17: TDBText;
    Label51: TLabel;
    DBText18: TDBText;
    Label59: TLabel;
    DBText19: TDBText;
    Label66: TLabel;
    DBText20: TDBText;
    Label67: TLabel;
    DBText22: TDBText;
    Label68: TLabel;
    DBText23: TDBText;
    Label69: TLabel;
    btactuallote: TButton;
    tbultos: TEdit;
    bttodoslotes: TButton;
    tpalets: TDBEdit;
    Button22: TButton;
    Panel28: TPanel;
    Button4: TButton;
    Button21: TButton;
    dsqpesadaslotesmov: TDataSource;
    qpesadaslotesmov: TZQuery;
    qpesadaslotessalidas: TZQuery;
    dsqpesadaslotessalidas: TDataSource;
    dsqpesadaslotesentradas: TDataSource;
    qpesadaslotesentradas: TZQuery;
    qpesadaslotesentradasid: TIntegerField;
    qpesadaslotesentradaside: TIntegerField;
    qpesadaslotesentradasidea: TIntegerField;
    qpesadaslotesentradasidea2: TIntegerField;
    qpesadaslotesentradaslote: TIntegerField;
    qpesadaslotesentradascajas: TIntegerField;
    qpesadaslotesentradasid_envase: TWideStringField;
    qpesadaslotesentradasid_formato: TIntegerField;
    qpesadaslotesentradasdesc_envase: TWideStringField;
    qpesadaslotesentradasdesc_formato: TWideStringField;
    qpesadaslotesentradaspesoneto_teorico: TFloatField;
    qpesadaslotesentradaspesoneto_real: TFloatField;
    qpesadaslotesentradases_entrada: TIntegerField;
    qpesadaslotesentradasparcela: TWideStringField;
    qpesadaslotesentradasmprima: TWideStringField;
    qpesadaslotesentradascalibrecalidad: TIntegerField;
    qpesadaslotesentradasdesc_calibre: TWideStringField;
    qpesadaslotesentradasresto_cajas: TIntegerField;
    qpesadaslotesmovid: TIntegerField;
    qpesadaslotesmovide: TIntegerField;
    qpesadaslotesmovidea: TIntegerField;
    qpesadaslotesmovidea2: TIntegerField;
    qpesadaslotesmovlote: TIntegerField;
    qpesadaslotesmovcajas: TIntegerField;
    qpesadaslotesmovid_envase: TWideStringField;
    qpesadaslotesmovid_formato: TIntegerField;
    qpesadaslotesmovdesc_envase: TWideStringField;
    qpesadaslotesmovdesc_formato: TWideStringField;
    qpesadaslotesmovpesoneto_teorico: TFloatField;
    qpesadaslotesmovpesoneto_real: TFloatField;
    qpesadaslotesmoves_entrada: TIntegerField;
    qpesadaslotesmovparcela: TWideStringField;
    qpesadaslotesmovmprima: TWideStringField;
    qpesadaslotesmovcalibrecalidad: TIntegerField;
    qpesadaslotesmovdesc_calibre: TWideStringField;
    qpesadaslotesmovresto_cajas: TIntegerField;
    qpesadaslotessalidasid: TIntegerField;
    qpesadaslotessalidaside: TIntegerField;
    qpesadaslotessalidasidea: TIntegerField;
    qpesadaslotessalidasidea2: TIntegerField;
    qpesadaslotessalidaslote: TIntegerField;
    qpesadaslotessalidascajas: TIntegerField;
    qpesadaslotessalidasid_envase: TWideStringField;
    qpesadaslotessalidasid_formato: TIntegerField;
    qpesadaslotessalidasdesc_envase: TWideStringField;
    qpesadaslotessalidasdesc_formato: TWideStringField;
    qpesadaslotessalidaspesoneto_teorico: TFloatField;
    qpesadaslotessalidaspesoneto_real: TFloatField;
    qpesadaslotessalidases_entrada: TIntegerField;
    qpesadaslotessalidasparcela: TWideStringField;
    qpesadaslotessalidasmprima: TWideStringField;
    qpesadaslotessalidascalibrecalidad: TIntegerField;
    qpesadaslotessalidasdesc_calibre: TWideStringField;
    qpesadaslotessalidasresto_cajas: TIntegerField;
    Label26: TLabel;
    qpedidospendientes: TZReadOnlyQuery;
    qpedidospendientesnombre: TWideStringField;
    qpedidospendientesiddestino: TWideStringField;
    qpedidospendientesfecha_carga: TDateField;
    qpedidospendientesdesc_producto: TWideStringField;
    qpedidospendientesdesc_envase: TWideStringField;
    qpedidospendientespalets: TIntegerField;
    qpedidospendientescantidad: TFloatField;
    qpedidospendientescantidadservida: TFloatField;
    qpedidospendientesobservaciones: TWideStringField;
    dsqpedidospendientes: TDataSource;
    timepedidos: TTimer;
    qpedidospendientesid: TIntegerField;
    qpedidospendienteside: TIntegerField;
    qpedidospendientesidenvase: TWideStringField;
    qpedidospendientesdescripcion: TWideStringField;
    Label70: TLabel;
    Panel29: TPanel;
    Detallesarticulos: TPageControl;
    Tasignar: TTabSheet;
    Panel30: TPanel;
    Label60: TLabel;
    Panel31: TPanel;
    Label71: TLabel;
    tbuscarenvasado: TEdit;
    DBGrid4: TDBGrid;
    DBGrid10: TDBGrid;
    Panel32: TPanel;
    btALnuevo: TButton;
    btALborrar: TButton;
    ImageList1: TImageList;
    dsqenvasados: TDataSource;
    qenvasados: TZQuery;
    dsqenvasados2: TDataSource;
    qenvasados2: TZQuery;
    qenvasados2id: TIntegerField;
    qenvasados2id_envase: TWideStringField;
    qenvasados2num_envases: TIntegerField;
    qenvasados2destino: TWideStringField;
    qenvasados2peso_neto_teorico: TFloatField;
    qenvasados2mprima: TWideStringField;
    qenvasados2parcela: TWideStringField;
    qenvasados2idempresa: TIntegerField;
    qenvasados2idpedido: TIntegerField;
    qenvasados2lote: TIntegerField;
    qenvasados2idalbaran: TWideStringField;
    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;
    dtlinpedidosdesc_envpropio: TWideStringField;
    qenvasadosid: TIntegerField;
    qenvasadosidempresa: TIntegerField;
    qenvasadosidEA: TIntegerField;
    qenvasadosid_palet: TWideStringField;
    qenvasadosnum_palets: TIntegerField;
    qenvasadosid_palet2: TWideStringField;
    qenvasadosnum_palets2: TIntegerField;
    qenvasadosid_envase: TWideStringField;
    qenvasadosnum_envases: TIntegerField;
    qenvasadosiddestino: TIntegerField;
    qenvasadosdestino: TWideStringField;
    qenvasadospeso_bruto: TFloatField;
    qenvasadostara: TFloatField;
    qenvasadospeso_neto: TFloatField;
    qenvasadospeso_neto_teorico: TFloatField;
    qenvasadospeso_medio: TFloatField;
    qenvasadostemperatura: TFloatField;
    qenvasadosfecha: TDateField;
    qenvasadosfechatrabajo: TDateField;
    qenvasadoshora: TTimeField;
    qenvasadosCEA: TWideStringField;
    qenvasadosresto_cajas: TFloatField;
    qenvasadosresto_pesoneto: TFloatField;
    qenvasadoslote: TIntegerField;
    qenvasadosORIGEN: TWideStringField;
    qenvasadosidorigen: TIntegerField;
    qenvasadosmprima: TWideStringField;
    qenvasadosgen_caja: TIntegerField;
    qenvasadoscosto: TFloatField;
    qenvasadoscoste_manipulacion: TFloatField;
    qenvasadosdias_camara: TIntegerField;
    qenvasadoscosto_camara: TFloatField;
    qenvasadoscodigoR: TWideStringField;
    qenvasadosparcela: TWideStringField;
    qenvasadosfecha_cierre: TDateField;
    qenvasadoscosto_materiales: TFloatField;
    qenvasadoscosto_cosechar: TFloatField;
    qenvasadosborrado: TIntegerField;
    qenvasadosseleccionado: TIntegerField;
    qenvasadosOBSERVACIONES: TWideStringField;
    qenvasadostipo_trabajo: TWideStringField;
    qenvasadostipo_generador: TWideStringField;
    qenvasadosremanipulado: TIntegerField;
    qenvasadosfecha_envasado: TDateField;
    qenvasadoscodean: TWideStringField;
    qenvasadoscodssc: TWideStringField;
    qenvasadospedidocliente: TIntegerField;
    qenvasadoscosto_sinmt: TFloatField;
    qenvasadostara0: TFloatField;
    qenvasadoslotes_detalle: TWideStringField;
    qenvasadosidpedido: TIntegerField;
    qenvasadosidalbaran: TWideStringField;
    qenvasadosrecuperar_envases: TIntegerField;
    qenvasadoscalibre: TFloatField;
    qenvasadosprov_albaran: TWideStringField;
    qenvasadosprov_fecha: TDateField;
    qenvasadosprov_ggn: TWideStringField;
    qenvasadosprov_lote: TWideStringField;
    qenvasadosprov_grower: TWideStringField;
    qenvasadosprov_puk: TWideStringField;
    qenvasadosprov_otros: TWideStringField;
    qinfpartidashora: TTimeField;
    qinfpartidasproductor: TWideStringField;
    qentradas: TZQuery;
    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;
    Memo1: TMemo;
    rdesechos: TRadioButton;
    qpesadaslotesentradaspuesto: TIntegerField;
    qpesadaslotessalidaspuesto: TIntegerField;
    qpesadaslotesmovpuesto: TIntegerField;
    qorigenescentrocoste_asociado: TWideStringField;
    qpartidasid: TIntegerField;
    qpartidaside: TIntegerField;
    qpartidasfecha: TDateField;
    qpartidasid_parcela: TWideStringField;
    qpartidasid_mprimas: TWideStringField;
    qpartidaslote: TIntegerField;
    rmultiples: TRadioButton;
    lporpalet: TEdit;
    eporpalet: TLabel;
    qinsertarmateriales: TZReadOnlyQuery;
    lgrupos: TLabel;
    combogrupos: TDBLookupComboBox;
    qgrupos: TZReadOnlyQuery;
    dsqgrupos: TDataSource;
    qgruposide: TIntegerField;
    qgruposid: TIntegerField;
    qgruposdescripcion: TWideStringField;
    qinsertarmaterialestmp: TZReadOnlyQuery;
    qinfpartidassgg: TWideStringField;
    qinfpartidassdop: TWideStringField;
    qinfpartidassigp: TWideStringField;
    qinfpartidassifs: TWideStringField;
    qinfpartidassbrc: TWideStringField;
    procedure FormShow(Sender: TObject);
    procedure rentradasClick(Sender: TObject);
    procedure renvasadosClick(Sender: TObject);
    procedure BTPESARClick(Sender: TObject);
    procedure tfechaChange(Sender: TObject);
    procedure Button5Click(Sender: TObject);
    procedure dstpartidasStateChange(Sender: TObject);
    procedure btguardarpartidaClick(Sender: TObject);
    procedure BTCANCELARClick(Sender: TObject);
    procedure btguardarentradaClick(Sender: TObject);
    procedure dsentradasStateChange(Sender: TObject);
    procedure btcancelarpesadaClick(Sender: TObject);
    procedure combopalets1CloseUp(Sender: TObject);
    procedure combocajasCloseUp(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
    procedure Puerto2RxChar(Sender: TObject; Count: Integer);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
    procedure Timer2Timer(Sender: TObject);
    procedure tidExit(Sender: TObject);
    procedure FormKeyPress(Sender: TObject; var Key: Char);
    procedure Button15Click(Sender: TObject);
    procedure Button6Click(Sender: TObject);
    procedure Edit1Enter(Sender: TObject);
    procedure gridpesadasalidasDrawColumnCell(Sender: TObject;
      const Rect: TRect; DataCol: Integer; Column: TColumn;
      State: TGridDrawState);
    procedure combovariedadsEnter(Sender: TObject);
    procedure comboenvasesEnter(Sender: TObject);
    procedure combopaletsEnter(Sender: TObject);
    procedure comboloteEnter(Sender: TObject);
    procedure comboorigenEnter(Sender: TObject);
    procedure combodestinoEnter(Sender: TObject);
    procedure comboentradaCloseUp(Sender: TObject);
    procedure combovariedadsCloseUp(Sender: TObject);
    procedure comboloteCloseUp(Sender: TObject);
    procedure comboorigenCloseUp(Sender: TObject);
    procedure combopalets1Enter(Sender: TObject);
    procedure combocajasEnter(Sender: TObject);
    procedure combodestinosEnter(Sender: TObject);
    procedure combopartidasDropDown(Sender: TObject);
    procedure combolotesentradaDropDown(Sender: TObject);
    procedure lenvases_esEnter(Sender: TObject);
    procedure lenvases_esExit(Sender: TObject);
    procedure edpalets_esEnter(Sender: TObject);
    procedure edpalets_esExit(Sender: TObject);
    procedure btnuevoloteClick(Sender: TObject);
    procedure comboorigen_esCloseUp(Sender: TObject);
    procedure combovariedad_esCloseUp(Sender: TObject);
    procedure comboentradas_esEnter(Sender: TObject);
    procedure btnuevaentradaClick(Sender: TObject);
    procedure ltemperaturaEnter(Sender: TObject);
    procedure ltemperaturaExit(Sender: TObject);
    procedure ltaraanteriorEnter(Sender: TObject);
    procedure ltaraanteriorExit(Sender: TObject);
    procedure combovariedad_esDropDown(Sender: TObject);
    procedure combodestino_esCloseUp(Sender: TObject);
    procedure comboformatos_esCloseUp(Sender: TObject);
    procedure combocalibre_esCloseUp(Sender: TObject);
    procedure comboformatos_esEnter(Sender: TObject);
    procedure combocalibre_esEnter(Sender: TObject);
    procedure combopalets_esExit(Sender: TObject);
    procedure btborrarloteClick(Sender: TObject);
    procedure edpeso_esChange(Sender: TObject);
    procedure edpeso_esEnter(Sender: TObject);
    procedure edpeso_esExit(Sender: TObject);
    procedure btguardarClick(Sender: TObject);
    procedure combovariedad_esExit(Sender: TObject);
    procedure rmovimientosClick(Sender: TObject);
    procedure RadioButton4Click(Sender: TObject);
    procedure Puerto2RxBuf(Sender: TObject; const Buffer; Count: Integer);
    procedure comdata1Packet(Sender: TObject; const Str: string);
    procedure comdata2Packet(Sender: TObject; const Str: string);
    procedure btactualloteClick(Sender: TObject);
    procedure bttodoslotesClick(Sender: TObject);
    procedure tidEnter(Sender: TObject);
    procedure dsqpesadaslotesDataChange(Sender: TObject; Field: TField);
    procedure tbultosExit(Sender: TObject);
    procedure tbultosEnter(Sender: TObject);
    procedure tpaletsExit(Sender: TObject);
    procedure tpaletsEnter(Sender: TObject);
    procedure Button22Click(Sender: TObject);
    procedure combodestinoExit(Sender: TObject);
    procedure edpeso_esKeyPress(Sender: TObject; var Key: Char);
    procedure combopalets_esDragDrop(Sender, Source: TObject; X, Y: Integer);
    procedure dsqpesadaslotesmovDataChange(Sender: TObject; Field: TField);
    procedure dsqpesadaslotessalidasDataChange(Sender: TObject; Field: TField);
    procedure dsqpesadaslotesentradasDataChange(Sender: TObject;
      Field: TField);
    procedure timepedidosTimer(Sender: TObject);
    procedure tbuscarenvasadoEnter(Sender: TObject);
    procedure tbuscarenvasadoExit(Sender: TObject);
    procedure tbuscarenvasadoChange(Sender: TObject);
    procedure btALnuevoClick(Sender: TObject);
    procedure dsqpedidospendientesDataChange(Sender: TObject; Field: TField);
    procedure btALborrarClick(Sender: TObject);
    procedure dspartidasDataChange(Sender: TObject; Field: TField);
    procedure rmultiplesClick(Sender: TObject);
    procedure lporpaletEnter(Sender: TObject);
    procedure lporpaletExit(Sender: TObject);
    procedure DBGrid7DrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumn; State: TGridDrawState);
  private
    { Private declarations }
  public
    { Public declarations }
    procedure InsertarMaterialestmp(AQuery: TZReadOnlyQuery;
      const AId, AIdEA, APuesto, ANumPalets, AIDEmpresa: Integer;
      const AidPalet: string;
      const AMultiplicador: real);
  end;

var
  general: Tgeneral;
  desdegrid,desdetrabajador,a_cero,estable,bloqueado,leer:boolean;
  visor,cadena,gid,tmesa:string;
  ttipobascula,tidbascula:string;
  ajusteentrada,ajustesalida,porcentagebloqueo,bloqueominimo,bloqueomaximo:real;
  gfecha:tdatetime;
  vgeneradores,recuperar,esentrada,esmultiple:integer;
  numpalets,numcajas,restocajas:integer;
  newnumpalets,newrestocajas,newnumcajas:integer;
  pesobruto:real;
  newpesobruto:real;
  pide,pseparartraza_es:integer;
const
  rojo=$00AAAAFF;
  amarillo=$00B9FFFF;
  verde=$00C7FBAA;
  azul=$00FFFFBB;



implementation
uses selectgeneradores,datos, selectlotes,recuperar, entradas;
{$R *.dfm}
function SoloNumeros(Cad: string): string;
var
  i: Integer;
begin
  Result:='';
  for i:= 1 to Length(Cad) do
    if (Cad[i] in ['0'..'9']) or (cad[i]=',') then
      Result:= Result + Cad[i];
end;



procedure Tgeneral.btALborrarClick(Sender: TObject);
var pedido:string;
begin

    dtlinpedidos.Edit;
    dtlinpedidoscantidadservida.value:=dtlinpedidoscantidadservida.AsInteger-qenvasados2num_envases.AsInteger;
    dtlinpedidos.Post;
    qaux.sql.Clear;
    qaux.sql.add('update ea_pesadas set idpedido=null,pedidocliente=null,idalbaran=null where id='+qenvasados2id.AsString);
    qaux.ExecSQL;
    pedido:=qpedidospendientesid.asstring;
    qpedidospendientes.Refresh;
    qpedidospendientes.Locate('id',pedido,[locaseinsensitive]);
    qenvasados2.Refresh;
    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 and fecha>='+''''+'2020-08-01'+''''+' ORDER BY id,idea');
    qenvasados.open;
    pedido:=dtlinpedidosid.Asstring;
    dtlinpedidos.Refresh;
    dtlinpedidos.Locate('Id',pedido,[locaseinsensitive,lopartialkey]);
end;

procedure Tgeneral.btALnuevoClick(Sender: TObject);
var pedido:string;
begin
    qaux.Close;
    qaux.SQL.Clear;
    qaux.SQL.Add('select id from almacenes where final=1');
    qaux.Open;
    qenvasados.Edit;
    qenvasadosidpedido.value:=dtlinpedidosid.AsInteger;
    qenvasadospedidocliente.value:=dtlinpedidosidpedido.AsInteger;
    qenvasadosiddestino.value:=qaux.Fields[0].AsInteger;
    //    qenvasadosidalbaran.value:=dtpedidospedidocliente.asinteger;
    qenvasados.Post;
    dtlinpedidos.Edit;
    dtlinpedidoscantidadservida.value:=dtlinpedidoscantidadservida.AsInteger+qenvasadosnum_envases.AsInteger;
    dtlinpedidos.Post;
    if dtlinpedidoscantidadservida.AsInteger>=dtlinpedidoscantidad.AsInteger then         showmessage('ˇˇˇˇ PEDIDO COMPLETADO ˇˇˇˇ');

    pedido:=qpedidospendientesid.asstring;
    qpedidospendientes.Refresh;
    qpedidospendientes.Locate('id',pedido,[locaseinsensitive]);
    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.Asstring;
    dtlinpedidos.Refresh;
    dtlinpedidos.Locate('Id',pedido,[locaseinsensitive,lopartialkey]);
    tbuscarenvasado.SetFocus;
end;

procedure Tgeneral.btborrarloteClick(Sender: TObject);
var   tara,bruto,neto,multiplicador,venta:real;
      tbultos,tneto,tmultiplicador,tventa,tide:string;
      escompuesta_es,num_envases,palets:integer;
begin
    if esentrada=1 then
    begin
        qpesadaslotesentradas.Delete;
        qpesadaslotesentradas.refresh;
    //////////////////////// INSERTO LOS MATERIALES DE LAS CAJAS SEGUN EL FORMATO
          if qpesadaslotesentradas.RecordCount>0 then
          begin
             qaux.Close;
             qaux.sql.clear;
             qaux.sql.Add('delete from ea_materiales_tmp where ide='+dm.qlotesidempresa.asstring+' and idea=-1000 and idea2=-1000 and puesto='+tidbascula);
             qaux.execsql;
             tide:=dm.qlotesidempresa.AsString;
// inserto los materiales de los palets
             insertarmaterialestmp(qinsertarmaterialestmp,-1000,-1000,strtoint(tidbascula),strtoint(edpalets_es.Text),strtoint(tide),qpalets1codigo.asstring,strtofloat(tmultiplicador));
{             qinsertarmaterialestmp.Prepare;
             qinsertarmaterialestmp.ParamByName('IDEA').AsInteger:=-1000;
             qinsertarmaterialestmp.ParamByName('IDEA2').AsInteger:=-1000;
             qinsertarmaterialestmp.ParamByName('PUESTO').AsInteger:=STRTOINT(TIDBASCULA);
             qinsertarmaterialestmp.ParamByName('NUMPALETS').AsInteger:=strtoint(edpalets_es.text);
             qinsertarmaterialestmp.ParamByName('IDPALET').AsInteger:=qpalets1id.asinteger;
             qinsertarmaterialestmp.ParamByName('MULTIPLICADOR').Asstring:=tmultiplicador;
             qinsertarmaterialestmp.ParamByName('EMPRESA').Asinteger:=strtoint(tide);
             qinsertarmaterialestmp.ExecSQL;
 }
             {
             if combopalets_es.keyvalue<>null then
             begin
                  qaux.Close;
                  qaux.SQL.Clear;
                  qaux.SQL.Add('insert into ea_materiales_tmp ');
                  qaux.SQL.Add('select idempresa,-1000-'+tidbascula+' as idea,-1000-'+tidbascula+' as idea2,idarticulof,sum(cantidadtotal) as cantidadtotal,sum(pesototal) as pesototal,null,sum(preciototal) as preciototal,0 as recuperado,null as identrada,'+tidbascula+' as puesto 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_tmp lp,articulos_almacen aa where aa.ide=lp.ide and aa.codigo=lp.id_envase ');
                  qaux.SQL.Add(' and lp.ide='+qpesadaslotesentradaside.AsString+' and lp.idea=-1000-'+tidbascula+' and lp.idea2=-1000-'+tidbascula+' 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) 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_tmp lp, ');
                  qaux.SQL.Add(' configuraciones aa where aa.ide=lp.ide and aa.id=lp.id_formato and lp.ide='+qpesadaslotesentradaside.AsString+' and lp.idea=-1000-'+tidbascula+' and lp.idea2=-1000-'+tidbascula+' group by lp.id_formato) 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*'+edpalets_es.Text+') as cantidadtotal,(ac.peso*'+edpalets_es.Text+') as pesototal,(ac.coste*'+edpalets_es.Text+') as preciototal');
                  qaux.SQL.Add(' FROM articulos_componentes ac where ac.idempresa='+qpesadaslotesentradaside.AsString+' and ac.idarticuloalmacen='+qpalets1id.asstring);
                  qaux.SQL.Add(' ) as ea_materiales_tmp group by idarticulof ');
                  qaux.execsql;
             end;}
          end else
                begin
                   qaux.Close;
                   qaux.sql.clear;
                   qaux.sql.Add('delete from ea_materiales_tmp where idea=-1000 and idea2=-1000 and puesto='+tidbascula);
                   qaux.execsql;

                end;
       qaux.close;
       qaux.sql.clear;
       qaux.sql.Add('select sum(pesoneto_teorico),sum(cajas) from lotes_pesadas_tmp where idea=-1000 and idea2=-1000 and puesto='+tidbascula);
       qaux.open;
       if qpesadaslotesentradas.RecordCount>0 then
       begin
         lbultos.text:=qaux.Fields[1].asstring;
         lventa_es.Text:=floattostr(qaux.Fields[0].AsFloat);
       end else
             begin
                lbultos.Text:='0';
                lventa_es.Text:='0';
             end;
       qaux.close;
       qaux.sql.clear;
       qaux.sql.Add('select sum(peso) from ea_materiales_tmp where ide='+dm.qlotesidempresa.asstring+' and idea=-1000 and idea2=-1000 and puesto='+tidbascula);
       qaux.open;
       ltara.Text:=floattostr(qaux.Fields[0].AsFloat);
       lneto.text:=floattostr(strtofloat(edpeso_es.Text)-strtofloat(ltara.Text)-strtofloat(ltaraanterior.Text));
        tbultos:=StringReplace(lbultos.text, '.', ',',[rfReplaceAll, rfIgnoreCase]);
        lbultos.Text;
        bruto:=strtofloat(edpeso_es.text);
        tara:=strtofloat(ltara.text);
        neto:=strtofloat(lneto.text);
        tneto:= StringReplace(lneto.text, ',', '.',[rfReplaceAll, rfIgnoreCase]);
        if tbultos<>'0' then
        begin
            qaux.SQL.Clear;
            qaux.SQL.Add('update lotes_pesadas_tmp set pesoneto_real=cajas/'+tbultos+'*'+tneto+' where idea=-1000 and idea2=-1000 and puesto='+tidbascula);
            qaux.ExecSQL;
        end;
        if tbultos<>'0' then
        begin
           if qcajasfacturar_pesofijo.AsInteger=0 then
           begin
             qaux.SQL.Clear;
             qaux.SQL.Add('update lotes_pesadas_tmp set pesoneto_teorico=cajas/'+tbultos+'*'+tneto+' where idea=-1000 and idea2=-1000 and puesto='+tidbascula);
             qaux.ExecSQL;
           end;
        end;

       qaux.sql.clear;
       qaux.sql.Add('select sum(pesoneto_teorico),sum(cajas) from lotes_pesadas_tmp where idea=-1000 and idea2=-1000 and puesto='+tidbascula);
       qaux.open;

       lbultos.text:=qaux.Fields[1].asstring;
       lventa_es.Text:=floattostr(qaux.Fields[0].AsFloat);
       qpesadaslotesentradas.refresh;

    end;
    tmultiplicador:=StringReplace(floattostr(multiplicador), '.', ',',[rfReplaceAll, rfIgnoreCase]);
    if esentrada=0 then
    begin
        if qpesadaslotessalidas.recordcount>0 then qpesadaslotessalidas.Delete;
        qpesadaslotessalidas.refresh;
    //////////////////////// INSERTO LOS MATERIALES DE LAS CAJAS SEGUN EL FORMATO
               //////////// materiales de los envases
          if qpesadaslotessalidas.RecordCount>0 then
          begin
             qaux.Close;
             qaux.sql.clear;
             qaux.sql.Add('delete from ea_materiales_tmp where ide='+dm.qlotessalidasidempresa.asstring+' and idea=-2000 and idea2=0 and puesto='+tidbascula);
             qaux.execsql;
             if combopalets_es.keyvalue<>null then
             begin
                   // inserto los materiales de los palets
                   if esmultiple=1 then palets:=1 else palets:=strtoint(edpalets_es.Text);
             tide:=dm.qlotessalidasidempresa.AsString;
// inserto los materiales de los palets
             insertarmaterialestmp(qinsertarmaterialestmp,-2000,0,strtoint(tidbascula),strtoint(edpalets_es.Text),strtoint(tide),qpalets1codigo.asstring,strtofloat(tmultiplicador));
{             qinsertarmaterialestmp.Prepare;
             qinsertarmaterialestmp.ParamByName('IDEA').AsInteger:=-2000;
             qinsertarmaterialestmp.ParamByName('IDEA2').AsInteger:=0;
             qinsertarmaterialestmp.ParamByName('PUESTO').AsInteger:=STRTOINT(TIDBASCULA);
             qinsertarmaterialestmp.ParamByName('NUMPALETS').AsInteger:=strtoint(edpalets_es.text);
             qinsertarmaterialestmp.ParamByName('IDPALET').AsInteger:=qpalets1id.asinteger;
             qinsertarmaterialestmp.ParamByName('MULTIPLICADOR').Asstring:=tmultiplicador;
             qinsertarmaterialestmp.ParamByName('EMPRESA').Asinteger:=strtoint(tide);
             qinsertarmaterialestmp.ExecSQL;
}
                   {
                  qaux.Close;
                  qaux.SQL.Clear;
                  qaux.SQL.Add('insert into ea_materiales_tmp ');
                  qaux.SQL.Add('select idempresa,-2000 as idea,0 as idea2,idarticulof,sum(cantidadtotal) as cantidadtotal,sum(pesototal) as pesototal,null,sum(preciototal) as preciototal,0 as recuperado,null as identrada,'+tidbascula+' as puesto  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_tmp lp,articulos_almacen aa where aa.ide=lp.ide and aa.codigo=lp.id_envase ');
                  qaux.SQL.Add(' and lp.ide='+qpesadaslotessalidaside.AsString+' and lp.idea=-2000 and lp.idea2=0 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_tmp lp, ');
                  qaux.SQL.Add(' configuraciones aa where aa.ide=lp.ide and aa.id=lp.id_formato and lp.ide='+qpesadaslotessalidaside.AsString+' and lp.idea=-2000 and lp.idea2=0 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*'+edpalets_es.Text+') as cantidadtotal,(ac.peso*'+edpalets_es.Text+') as pesototal,(ac.coste*'+edpalets_es.Text+') as preciototal');
                  qaux.SQL.Add(' FROM articulos_componentes ac where ac.idempresa='+qpesadaslotessalidaside.AsString+' and ac.idarticuloalmacen='+qpalets1id.asstring);
                  qaux.SQL.Add(' ) as ea_materiales_tmp group by idarticulof ');
                  qaux.execsql;}
             end;
          end else
                begin
                   qaux.Close;
                   qaux.sql.clear;
                   qaux.sql.Add('delete from ea_materiales_tmp where idea=-2000 and idea2=0 and puesto='+tidbascula);
                   qaux.execsql;

                end;
/////////////////////

                 qpesadaslotessalidas.refresh;
                 if qpesadaslotessalidas.RecordCount>0 then
                 begin
                 qaux.sql.clear;
                 qaux.sql.Add('select sum(pesoneto_teorico),sum(cajas) from lotes_pesadas_tmp where idea=-2000 and idea2=0 and puesto='+tidbascula);
                 qaux.open;
                 lbultos.text:=qaux.Fields[1].asstring;
              //   lneto.Text:='0';
                 lventa_es.Text:=floattostr(qaux.Fields[0].AsFloat);
                 tventa:=lventa_es.Text;
                 qaux.sql.clear;
                 qaux.sql.Add('select sum(peso) from ea_materiales_tmp where idea=-2000 and idea2=0');
                 qaux.open;
                 ltara.Text:=floattostr(qaux.Fields[0].AsFloat);
                 lneto.text:=floattostr(strtofloat(edpeso_es.Text)-strtofloat(ltara.Text)-strtofloat(ltaraanterior.Text));
                  tbultos:=StringReplace(lbultos.text, '.', ',',[rfReplaceAll, rfIgnoreCase]);lbultos.Text;
                  bruto:=strtofloat(edpeso_es.text);
                  tara:=strtofloat(ltara.text);
                  venta:=strtofloat(lventa_es.Text);
                  tventa:=floattostr(venta);
                  neto:=strtofloat(lneto.text);
                  tneto:= StringReplace(lneto.text, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  tventa:=StringReplace(tventa, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  if tbultos<>'0' then
                  begin
                    if qpalets2facturar_pesofijo.AsInteger=1 then
                    begin
                      qaux.SQL.Clear;
                      qaux.SQL.Add('update lotes_pesadas_tmp set pesoneto_teorico=cajas/'+tbultos+'*'+tventa+',pesoneto_real=cajas/'+tbultos+'*'+tneto+' where puesto='+tidbascula+' and idea='+qpesadaslotessalidasidea.AsString+' and idea2='+qpesadaslotessalidasidea2.AsString);
                      qaux.ExecSQL;
                    end;
                  end;
                  if tbultos<>'0' then
                  begin
                    if qpalets2facturar_pesofijo.AsInteger=0 then
                    begin
                        qaux.SQL.Clear;
                        qaux.SQL.Add('update lotes_pesadas_tmp set pesoneto_teorico=cajas/'+tbultos+'*'+tneto+',pesoneto_real=cajas/'+tbultos+'*'+tneto+' where puesto='+tidbascula+' and idea='+qpesadaslotessalidasidea.AsString+' and idea2='+qpesadaslotessalidasidea2.AsString);
                        qaux.ExecSQL;
                    end;
                  end;
                 qaux.close;
                 qaux.sql.clear;
                 qaux.sql.Add('select sum(pesoneto_teorico),sum(cajas) from lotes_pesadas_tmp where idea=-2000 and idea2=0 and puesto='+tidbascula);
                 qaux.open;
                 lventa_es.Text:=floattostr(qaux.Fields[0].AsFloat);
                  qpesadaslotessalidas.refresh;
                  if edpeso_es.Text='0' then edpeso_es.SetFocus;

                 end;
  ///////////////////

    end;


end;

procedure Tgeneral.BTCANCELARClick(Sender: TObject);
begin
    tpartidas.cancel;
end;

procedure Tgeneral.btguardarpartidaClick(Sender: TObject);
begin
    tpartidasfecha.Value:=tfecha.Date;
    tpartidaside.Value:=1;
    tpartidas.Post;
    tpartidas.Close;
    qpartidas.refresh;
    qpartidas.First;

end;

procedure Tgeneral.BTPESARClick(Sender: TObject);
begin
//   PEntradas.Visible:=true;
   qdestinos.Open;
   qpalets1.open;
//   qpalets2.open;
   qcajas.Open;


end;

procedure Tgeneral.btcancelarpesadaClick(Sender: TObject);
begin
   dm.qpesadas.Close;
   dm.qpesadastmp.Close;
   dm.qpesadaslotes.Close;
   if esentrada=1 then qpesadaslotesentradas.Close;
   if esentrada=0 then qpesadaslotessalidas.Close;
   if esentrada=2 then qpesadaslotesmov.Close;
   qaux.SQL.Clear;
   qaux.SQL.Add('delete from ea_pesadas_tmp');
   qaux.ExecSQL;
   qaux.SQL.Clear;
   qaux.SQL.Add('delete from lotes_pesadas_tmp');
   qaux.ExecSQL;
   comboorigen.KeyValue:=null;
   combodestino.KeyValue:=null;
   timer1.Enabled:=true;
   timer2.Enabled:=true;
   tid.Text:='';
   tid.SetFocus;

end;
procedure TGeneral.InsertarMaterialestmp(AQuery: TZReadOnlyQuery;
  const AId, AIdEA, APuesto, ANumPalets, AIDEmpresa: Integer;
  const AidPalet : string ;
  const AMultiplicador: real);
begin
  // Aseguramos que la consulta esté preparada para recibir los parámetros
  qinsertarmaterialestmp.Prepare;

  // Asignamos cada parámetro con el valor recibido
  AQuery.ParamByName('IDEA').AsInteger          := AId;
  AQuery.ParamByName('IDEA2').AsInteger         := AIdEA;
  AQuery.ParamByName('PUESTO').AsInteger        := APuesto;
  AQuery.ParamByName('NUMPALETS').AsInteger     := ANumPalets;
  AQuery.ParamByName('IDPALET').Asstring       := AIdPalet;
  AQuery.ParamByName('MULTIPLICADOR').Asfloat   := AMultiplicador;
  AQuery.ParamByName('EMPRESA').AsInteger       := AIDEmpresa;

  // Ejecutamos la consulta de inserción
  AQuery.ExecSQL;
end;

procedure Tgeneral.Button15Click(Sender: TObject);
var dia,mes,anyo:word;
    vdia,vmes,vanyo,vfecha:string;
    iddestino,idalmacenintermedio,nomalmacenintermedio,nomalmacen:string;
    observaciones:string;
    v_id,v_idea,v_ide:integer;
    dias,error,idea,cajas,newcajas,vescompuesta:integer;
    costocamara,pesoneto,tara,vmultiplicador,costomateriales:real;
    newpalets:integer;
    pneto,newpneto,preal,newpreal:real;
    vneto,vbruto,vventa,vpesomedio,vtara,vbultos,vcosto:string;
    v_bultos:integer;
    v_tara,v_taraanterior,v_pesoneto,v_pesobruto,v_pesoventa,v_pesomedio,v_costo:real;
begin
   decodedate(tfecha.Date,anyo,mes,dia);
   vanyo:=floattostr(anyo);
   vmes:=floattostr(mes);
   vdia:=floattostr(dia);
   vfecha:=''''+vanyo+'-'+vmes+'-'+vdia+'''';
   dias:=trunc(tfecha.date-dm.qpesadasfecha.AsDateTime);
   v_ide:=dm.qpesadasidempresa.Asinteger;
   v_id:=dm.qpesadasid.Asinteger;
   v_idea:=dm.qpesadasidea.Asinteger;
   cajas:=dm.qpesadasnum_envases.AsInteger;
   newcajas:=dm.qpesadastmpnum_envases.AsInteger;
//////////////////////////
   iddestino:=dm.qpesadasiddestino.AsString;
   if qorigenesalmacen_asociado.AsString<>'' then
   begin
       idalmacenintermedio:=qorigenesalmacen_asociado.asstring;
       dm.qaux.SQL.Clear;
       dm.qaux.SQL.Add('select nombre from almacenes where id='+idalmacenintermedio);
       dm.qaux.open;
       nomalmacenintermedio:= dm.qaux.Fields[0].AsString;
   end;
/// de cliente a camara
       if (qorigenesfinal.AsInteger=1) and (qdestinoscamara.asinteger=1)   then
       begin
       if cajas=newcajas then
           begin
               observaciones:=dm.qpesadasobservaciones.asstring;
               observaciones:=observaciones+datetostr(tfecha.Date)+'('+qorigenesnombre.asstring+'-->'+qdestinosnombre.asstring+')';
               dm.qpesadas.edit;
               dm.qpesadasid_palet2.Value:='TRIGGER_ON';
               dm.qpesadasiddestino.Value:=qdestinosid.asinteger;// strtoint(idalmacenintermedio);
               dm.qpesadasdestino.value:=qdestinosnombre.AsString;// almacenintermedio;
               dm.qpesadasfechatrabajo.Value:=tfecha.date;
               dm.qpesadasremanipulado.Value:=1;
               dm.qpesadasobservaciones.value:=observaciones;
               dm.qpesadasgen_caja.Value:=vgeneradores;
               dm.qpesadas.Post;
           end else
           begin
               observaciones:=dm.qpesadasobservaciones.asstring;
               observaciones:=observaciones+datetostr(tfecha.Date)+'('+qorigenesnombre.asstring+'-->'+qdestinosnombre.asstring+')';
               if v_idea<0 then v_idea:=v_idea-2 else v_idea:=-2;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_pesadas_tmp set idea='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update lotes_pesadas_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_materiales_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_pesadas (select * from v_eapesadastmp where idea='+inttostr(v_idea)+' and id='+inttostr(v_id)+' and idempresa='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into lotes_pesadas (select * from v_lotespesadastmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_materiales (select * from v_eamaterialestmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_pesadas_tmp set num_palets=0,remanipulado=1 where idea='+inttostr(v_idea)+' and id='+inttostr(v_id)+' and idempresa='+inttostr(v_ide)+' and puesto='+tidbascula);
               qaux.ExecSQL;
               dm.qpesadastmp.refresh;
               dm.qpesadaslotes.First;
               while not dm.qpesadaslotes.eof do
               begin
                 qaux.Close;
                 qaux.SQL.Clear;
                 qaux.SQL.Add('select * from lotes_pesadas_tmp where id='+dm.qpesadaslotesid.asstring);
                 qaux.open;
                 if qaux.RecordCount>0 then
                 begin
                   if dm.qpesadaslotescajas.AsInteger>qpesadaslotesmovcajas.AsInteger then
                   begin
                     v_bultos:=cajas-newcajas;
                     v_pesoneto:=(dm.qpesadaslotespesoneto_real.asfloat/cajas)*v_bultos;
                     v_pesoventa:=(dm.qpesadaslotespesoneto_teorico.asfloat/cajas)*v_bultos;
                     vneto:=floattostr(v_pesoneto);
                     vneto:= StringReplace(vneto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                     vventa:=floattostr(v_pesoventa);
                     vventa:= StringReplace(vventa, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                     qaux.Close;
                     qaux.SQL.Clear;
                     qaux.SQL.Add('update lotes_pesadas_tmp set cajas='+inttostr(v_bultos)+',resto_cajas='+inttostr(v_bultos)+',pesoneto_teorico='+vventa+',pesoneto_real='+vneto+' where id='+dm.qpesadaslotesid.asstring+' and puesto='+tidbascula);
                     qaux.ExecSQL;
                 end else
                   begin
                     qaux.Close;
                     qaux.SQL.Clear;
                     qaux.SQL.Add('delete from lotes_pesadas_tmp where puesto='+tidbascula);
                     qaux.ExecSQL;
                   end;
                 end else
                 begin
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('insert into lotes_pesadas_tmp (select *,'+tidbascula+' as puesto from lotes_pesadas where id='+dm.qpesadaslotesid.asstring+' and idea='+dm.qpesadaslotesidea.asstring+' and idea2='+dm.qpesadaslotesidea2.asstring+' and ide='+dm.qpesadasloteside.asstring+')');
                   qaux.ExecSQL;
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update lotes_pesadas_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
                   qaux.ExecSQL;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_pesadas_tmp set idea='+inttostr(v_idea)+' where puesto='+tidbascula);
                   qaux.ExecSQL;
                 end;
                  qaux.Close;
                  qaux.sql.clear;
                  qaux.sql.Add('delete from ea_materiales_tmp where puesto='+tidbascula);
                  qaux.execsql;
//             tide:=dm.qpesadasloteside.AsString;
// inserto los materiales de los palets
             insertarmaterialestmp(qinsertarmaterialestmp,v_id,v_idea,strtoint(tidbascula),strtoint(edpalets_es.Text),v_ide,qpalets1codigo.asstring,vmultiplicador);
{             qinsertarmaterialestmp.Prepare;
             qinsertarmaterialestmp.ParamByName('IDEA').AsInteger:=v_id;
             qinsertarmaterialestmp.ParamByName('IDEA2').AsInteger:=v_idea;
             qinsertarmaterialestmp.ParamByName('PUESTO').AsInteger:=STRTOINT(TIDBASCULA);
             qinsertarmaterialestmp.ParamByName('NUMPALETS').AsInteger:=strtoint(edpalets_es.text);
             qinsertarmaterialestmp.ParamByName('IDPALET').AsInteger:=qpalets1id.asinteger;
             qinsertarmaterialestmp.ParamByName('MULTIPLICADOR').Asfloat:=vmultiplicador;
             qinsertarmaterialestmp.ParamByName('EMPRESA').Asinteger:=v_ide;
             qinsertarmaterialestmp.ExecSQL;
}

                  {qaux.Close;
                  qaux.SQL.Clear;
                  qaux.SQL.Add('insert into ea_materiales_tmp ');
                  qaux.SQL.Add('select idempresa,'+inttostr(v_id)+' as idea,'+inttostr(v_idea)+' as idea2,idarticulof,sum(cantidadtotal) as cantidadtotal,sum(pesototal) as pesototal,null,sum(preciototal) as preciototal,0 as recuperado,null as identrada,'+tidbascula+' as puesto 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_tmp lp,articulos_almacen aa where aa.ide=lp.ide and aa.codigo=lp.id_envase ');
                  qaux.SQL.Add(' and lp.ide='+inttostr(v_ide)+' and lp.idea='+inttostr(v_id)+' and lp.idea2='+inttostr(v_idea)+' 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) 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_tmp lp, ');
                  qaux.SQL.Add(' configuraciones aa where aa.ide=lp.ide and aa.id=lp.id_formato and lp.ide='+inttostr(v_ide)+' and lp.idea='+inttostr(v_id)+' and lp.idea2='+inttostr(v_idea)+' 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*'+dm.qpesadastmpnum_palets.AsString+') as cantidadtotal,(ac.peso*'+dm.qpesadastmpnum_palets.AsString+') as pesototal,(ac.coste*'+dm.qpesadastmpnum_palets.AsString+') as preciototal');
                  qaux.SQL.Add(' FROM articulos_componentes ac where ac.idempresa='+inttostr(v_ide)+' and ac.idarticuloalmacen=(select id from articulos_almacen where codigo='+''''+dm.qpesadastmpid_palet.AsString+''''+')');
                  qaux.SQL.Add(' ) as ea_materiales_tmp group by idarticulof ');
                  qaux.execsql;     }

                  qaux.sql.clear;
                  qaux.sql.Add('select sum(pesoneto_teorico),sum(cajas),sum(pesoneto_real) from lotes_pesadas_tmp where idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea)+' and puesto='+tidbascula);
                  qaux.open;

                  v_bultos:=qaux.Fields[1].asinteger;
                  v_pesoventa:=qaux.Fields[0].AsFloat;
                  v_pesoneto:=qaux.Fields[2].AsFloat;
                  if v_bultos=0 then v_pesomedio:=0 else v_pesomedio:=v_pesoneto/v_bultos;
                  ////////////////////////
                  qaux.sql.clear;
                  qaux.sql.Add('select sum(peso) from ea_materiales_tmp where ide='+inttostr(v_ide)+' and idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea)+' and puesto='+tidbascula);
                  qaux.open;
                  v_tara:=qaux.Fields[0].AsFloat;
                  v_pesobruto:=v_tara+v_pesoneto;
                  vtara:=floattostr(v_tara);
                  vtara:= StringReplace(vtara, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vneto:=floattostr(v_pesoneto);
                  vneto:= StringReplace(vneto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vbruto:=floattostr(v_pesobruto);
                  vbruto:= StringReplace(vbruto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vventa:=floattostr(v_pesoventa);
                  vventa:= StringReplace(vventa, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vpesomedio:=floattostr(v_pesomedio);
                  vpesomedio:= StringReplace(vpesomedio, ',', '.',[rfReplaceAll, rfIgnoreCase]);

                  qaux.close;
                  qaux.SQL.Clear;
                  qaux.SQL.Add('update ea_pesadas_tmp set resto_cajas='+inttostr(v_bultos)+',num_envases='+inttostr(v_bultos)+',peso_medio='+vpesomedio+',peso_bruto='+vbruto+',tara='+vtara+',peso_neto='+vneto+',peso_neto_teorico='+vventa+',iddestino='+qorigenesid.AsString+',destino='+''''+qorigenesnombre.AsString+''''+' where idempresa='+inttostr(v_ide)+' and id='+inttostr(v_id)+' and idea='+inttostr(v_idea)+' and puesto='+tidbascula);                  qaux.ExecSQL;
                  dm.qpesadastmp.close;
                  dm.qpesadastmp.Open;
                  dm.qpesadaslotes.Next;
               end;
               v_idea:=v_idea+1;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_pesadas_tmp set num_palets=0,idea='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update lotes_pesadas_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_materiales_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_pesadas (select * from v_eapesadastmp where idea='+inttostr(v_idea)+' and id='+inttostr(v_id)+' and idempresa='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into lotes_pesadas (select * from v_lotespesadastmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_materiales (select * from v_eamaterialestmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               dm.qpesadas.edit;
               dm.qpesadasid_palet2.Value:='TRIGGER_ON';
               dm.qpesadasiddestino.Value:=0;// strtoint(idalmacenintermedio);
               dm.qpesadasdestino.value:='PALETS FRACCCIONADOS';// almacenintermedio;
               dm.qpesadasfechatrabajo.Value:=tfecha.date;
               dm.qpesadasremanipulado.Value:=1;
               dm.qpesadasobservaciones.value:=observaciones;
               dm.qpesadasgen_caja.Value:=vgeneradores;
               dm.qpesadasresto_cajas.Value:=0;
               dm.qpesadas.Post;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update lotes_pesadas set resto_cajas=0 where idea='+inttostr(v_id)+' and idea2='+dm.qpesadasidea.asstring+' and ide='+inttostr(v_ide));
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('delete from ea_materiales where idea='+inttostr(v_id)+' and idea2='+dm.qpesadasidea.asstring+' and ide='+inttostr(v_ide));
               qaux.ExecSQL;
           end;
       end;
/// de cliente a produccion

       if (qdestinosproduccion.asinteger=1) and (qorigenesfinal.AsInteger=1) then
       begin
       if cajas=newcajas then
           begin
               observaciones:=dm.qpesadasobservaciones.asstring;
               observaciones:=observaciones+datetostr(tfecha.Date)+'('+qorigenesnombre.asstring+'-->'+qdestinosnombre.asstring+')';
               dm.qpesadas.edit;
               dm.qpesadasid_palet2.Value:='TRIGGER_ON';
               dm.qpesadasiddestino.Value:=qdestinosid.asinteger;// strtoint(idalmacenintermedio);
               dm.qpesadasdestino.value:=qdestinosnombre.AsString;// almacenintermedio;
               dm.qpesadasfechatrabajo.Value:=tfecha.date;
               dm.qpesadasremanipulado.Value:=1;
               dm.qpesadasobservaciones.value:=observaciones;
               dm.qpesadasgen_caja.Value:=vgeneradores;
               dm.qpesadas.Post;
           end else
           begin
               observaciones:=dm.qpesadasobservaciones.asstring;
               observaciones:=observaciones+datetostr(tfecha.Date)+'('+qorigenesnombre.asstring+'-->'+qdestinosnombre.asstring+')';
               if v_idea<0 then v_idea:=v_idea-2 else v_idea:=-2;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_pesadas_tmp set idea='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update lotes_pesadas_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_materiales_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_pesadas (select * from v_1eapesadastmp where idea='+inttostr(v_idea)+' and id='+inttostr(v_id)+' and idempresa='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into lotes_pesadas (select * from v_lotespesadastmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_materiales (select * from v_eamaterialestmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_pesadas_tmp set num_palets=0,remanipulado=1 where puesto='+tidbascula);
               qaux.ExecSQL;
               dm.qpesadastmp.refresh;
               dm.qpesadaslotes.First;
               while not dm.qpesadaslotes.eof do
               begin
                 qaux.Close;
                 qaux.SQL.Clear;
                 qaux.SQL.Add('select * from lotes_pesadas_tmp where id='+dm.qpesadaslotesid.asstring+' and puesto='+tidbascula);
                 qaux.open;
                 if qaux.RecordCount>0 then
                 begin
                   if dm.qpesadaslotescajas.AsInteger>qpesadaslotesmovcajas.AsInteger then
                   begin
                     v_bultos:=cajas-newcajas;
                     v_pesoneto:=(dm.qpesadaslotespesoneto_real.asfloat/cajas)*v_bultos;
                     v_pesoventa:=(dm.qpesadaslotespesoneto_teorico.asfloat/cajas)*v_bultos;
                     vneto:=floattostr(v_pesoneto);
                     vneto:= StringReplace(vneto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                     vventa:=floattostr(v_pesoventa);
                     vventa:= StringReplace(vventa, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                     qaux.Close;
                     qaux.SQL.Clear;
                     qaux.SQL.Add('update lotes_pesadas_tmp set cajas='+inttostr(v_bultos)+',resto_cajas='+inttostr(v_bultos)+',pesoneto_teorico='+vventa+',pesoneto_real='+vneto+' where id='+dm.qpesadaslotesid.asstring+' and puesto='+tidbascula);
                     qaux.ExecSQL;
                 end else
                   begin
                     qaux.Close;
                     qaux.SQL.Clear;
                     qaux.SQL.Add('delete from lotes_pesadas_tmp where  puesto='+tidbascula);
                     qaux.ExecSQL;
                   end;
                 end else
                 begin
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('insert into lotes_pesadas_tmp (select *,'+tidbascula+' as puesto from lotes_pesadas where id='+dm.qpesadaslotesid.asstring+' and idea='+dm.qpesadaslotesidea.asstring+' and idea2='+dm.qpesadaslotesidea2.asstring+' and ide='+dm.qpesadasloteside.asstring+')');
                   qaux.ExecSQL;
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update lotes_pesadas_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
                   qaux.ExecSQL;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_pesadas_tmp set idea='+inttostr(v_idea)+' where puesto='+tidbascula);
                   qaux.ExecSQL;
                 end;
                  qaux.Close;
                  qaux.sql.clear;
                  qaux.sql.Add('delete from ea_materiales_tmp where puesto='+tidbascula);
                  qaux.execsql;

                  insertarmaterialestmp(qinsertarmaterialestmp,v_id,v_idea,strtoint(tidbascula),dm.qpesadastmpnum_palets.asinteger,v_ide,dm.qpesadastmpid_palet.asstring,1.0);
{                  qaux.Close;
                  qaux.SQL.Clear;
                  qaux.SQL.Add('insert into ea_materiales_tmp ');
                  qaux.SQL.Add('select idempresa,'+inttostr(v_id)+' as idea,'+inttostr(v_idea)+' as idea2,idarticulof,sum(cantidadtotal) as cantidadtotal,sum(pesototal) as pesototal,null,sum(preciototal) as preciototal,0 as recuperado,null as identrada,'+tidbascula+' as puesto 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_tmp lp,articulos_almacen aa where aa.ide=lp.ide and aa.codigo=lp.id_envase ');
                  qaux.SQL.Add(' and lp.ide='+inttostr(v_ide)+' and lp.idea='+inttostr(v_id)+' and lp.idea2='+inttostr(v_idea)+' 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) 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_tmp lp, ');
                  qaux.SQL.Add(' configuraciones aa where aa.ide=lp.ide and aa.id=lp.id_formato and lp.ide='+inttostr(v_ide)+' and lp.idea='+inttostr(v_id)+' and lp.idea2='+inttostr(v_idea)+' 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*'+dm.qpesadastmpnum_palets.AsString+') as cantidadtotal,(ac.peso*'+dm.qpesadastmpnum_palets.AsString+') as pesototal,(ac.coste*'+dm.qpesadastmpnum_palets.AsString+') as preciototal');
                  qaux.SQL.Add(' FROM articulos_componentes ac where ac.idempresa='+inttostr(v_ide)+' and ac.idarticuloalmacen=(select id from articulos_almacen where codigo='+''''+dm.qpesadastmpid_palet.AsString+''''+')');
                  qaux.SQL.Add(' ) as ea_materiales_tmp group by idarticulof ');
                  qaux.execsql;
}
                  qaux.sql.clear;
                  qaux.sql.Add('select sum(pesoneto_teorico),sum(cajas),sum(pesoneto_real) from lotes_pesadas_tmp where idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea)+' and puesto='+tidbascula);
                  qaux.open;

                  v_bultos:=qaux.Fields[1].asinteger;
                  v_pesoventa:=qaux.Fields[0].AsFloat;
                  v_pesoneto:=qaux.Fields[2].AsFloat;
                  if v_bultos=0 then v_pesomedio:=0 else v_pesomedio:=v_pesoneto/v_bultos;
                  ////////////////////////
                  qaux.sql.clear;
                  qaux.sql.Add('select sum(peso) from ea_materiales_tmp where ide='+inttostr(v_ide)+' and idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea)+' and puesto='+tidbascula);
                  qaux.open;
                  v_tara:=qaux.Fields[0].AsFloat;
                  v_pesobruto:=v_tara+v_pesoneto;
                  vtara:=floattostr(v_tara);
                  vtara:= StringReplace(vtara, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vneto:=floattostr(v_pesoneto);
                  vneto:= StringReplace(vneto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vbruto:=floattostr(v_pesobruto);
                  vbruto:= StringReplace(vbruto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vventa:=floattostr(v_pesoventa);
                  vventa:= StringReplace(vventa, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vpesomedio:=floattostr(v_pesomedio);
                  vpesomedio:= StringReplace(vpesomedio, ',', '.',[rfReplaceAll, rfIgnoreCase]);

                  qaux.close;
                  qaux.SQL.Clear;
                  qaux.SQL.Add('update ea_pesadas_tmp set resto_cajas='+inttostr(v_bultos)+',num_envases='+inttostr(v_bultos)+',peso_medio='+vpesomedio+',peso_bruto='+vbruto+',tara='+vtara+',peso_neto='+vneto+',peso_neto_teorico='+vventa+',iddestino='+qorigenesid.AsString+',destino='+''''+qorigenesnombre.AsString+''''+' where idempresa='+inttostr(v_ide)+' and id='+inttostr(v_id)+' and idea='+inttostr(v_idea)+' and puesto='+tidbascula);
                  qaux.ExecSQL;
                  dm.qpesadastmp.close;
                  dm.qpesadastmp.Open;
                  dm.qpesadaslotes.Next;
               end;
               v_idea:=v_idea+1;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_pesadas_tmp set num_palets=0,idea='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update lotes_pesadas_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_materiales_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_pesadas (select * from v_eapesadastmp where idea='+inttostr(v_idea)+' and id='+inttostr(v_id)+' and idempresa='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into lotes_pesadas (select * from v_lotespesadastmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_materiales (select * from v_eamaterialestmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               dm.qpesadas.edit;
               dm.qpesadasid_palet2.Value:='TRIGGER_ON';
               dm.qpesadasiddestino.Value:=0;// strtoint(idalmacenintermedio);
               dm.qpesadasdestino.value:='PALETS FRACCCIONADOS';// almacenintermedio;
               dm.qpesadasfechatrabajo.Value:=tfecha.date;
               dm.qpesadasremanipulado.Value:=1;
               dm.qpesadasobservaciones.value:=observaciones;
               dm.qpesadasgen_caja.Value:=vgeneradores;
               dm.qpesadasresto_cajas.Value:=0;
               dm.qpesadas.Post;
                   v_ide:=dm.qpesadasidempresa.AsInteger;
                   v_id:=dm.qpesadasid.AsInteger;
                   v_idea:=dm.qpesadasidea.AsInteger;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_materiales set recuperado=-1 where idea='+inttostr(v_id)+' and  idea2='+inttostr(v_idea)+' and ide='+inttostr(v_ide));
                   qaux.ExecSQL;
                   qaux.sql.clear;
                   qaux.sql.Add('select sum(peso),sum(precio) from ea_materiales where ide='+inttostr(v_ide)+' and idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea));
                   qaux.open;
                   v_tara:=qaux.Fields[0].AsFloat;
                   v_costo:=qaux.fields[1].asfloat;
                   vtara:=floattostr(v_tara);
                   vtara:= StringReplace(vtara, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                   vcosto:=floattostr(v_costo);
                   vcosto:= StringReplace(vcosto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                   qaux.close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_pesadas set costo_materiales='+vcosto+',tara='+vtara+' where idempresa='+inttostr(v_ide)+' and id='+inttostr(v_id)+' and idea='+inttostr(v_idea));
                   qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update lotes_pesadas set resto_cajas=0 where idea='+inttostr(v_id)+' and idea2='+dm.qpesadasidea.asstring+' and ide='+inttostr(v_ide));
               qaux.ExecSQL;
           end;
       end;


/// de camara a cliente

    if (qorigenescamara.asinteger=1) and (qdestinosfinal.AsInteger=1) then
    begin
       qaux.Close;
       qaux.SQL.Clear;
       qaux.SQL.Add('select id,nombre from almacenes where id='+qorigenesalmacen_asociado.AsString+' and idempresa='+qorigenesidempresa.AsString);
       qaux.open;

       nomalmacenintermedio:=qaux.Fields[1].AsString;
       idalmacenintermedio:=qaux.Fields[0].AsString;
       if cajas=newcajas then
           begin
               observaciones:=dm.qpesadasobservaciones.asstring;
               observaciones:=observaciones+' '+datetostr(tfecha.Date)+'('+qorigenesnombre.asstring+'-->'+qdestinosnombre.asstring+')';
               if dm.qpesadasidEA.AsInteger>0 then
               begin
                 dm.qpesadas.edit;
                 dm.qpesadasid_palet2.Value:='TRIGGER_ON';
                 dm.qpesadasiddestino.Value:=strtoint(idalmacenintermedio);
                 dm.qpesadasdestino.value:=nomalmacenintermedio;
                 dm.qpesadasfechatrabajo.Value:=tfecha.date;
                 dm.qpesadasremanipulado.Value:=1;
                 dm.qpesadasobservaciones.value:=observaciones;
                 dm.qpesadasgen_caja.Value:=vgeneradores;
                 dm.qpesadasresto_cajas.Value:=0;
                 dm.qpesadasresto_pesoneto.value:=0;
                 dm.qpesadasdias_camara.Value:=dias;
                 dm.qpesadas.Post;
                 if qorigenesalmacen_asociado.value<>null then
                 begin
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_pesadas_tmp set resto_cajas=0,fecha='+vfecha+',fechatrabajo='+vfecha+',idea=0,iddestino='+qdestinosid.asstring+',destino='+''''+qdestinosnombre.asstring+''''+',idorigen='+qorigenesalmacen_asociado.asstring+',origen=(select nombre from almacenes where id='+qorigenesalmacen_asociado.asstring+' and idempresa='+qorigenesidempresa.asstring+'),observaciones='+''''+observaciones+''''+' where puesto='+tidbascula);
                   qaux.ExecSQL;
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update lotes_pesadas_tmp set resto_cajas=0,idea2=0 where puesto='+tidbascula);
                   qaux.ExecSQL;
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_materiales_tmp set idea2=0 where puesto='+tidbascula);
                   qaux.ExecSQL;
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('insert into ea_pesadas (select * from v_eapesadastmp where idea=0 and id='+inttostr(v_id)+' and idempresa='+inttostr(v_ide)+')');
                   qaux.ExecSQL;
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('insert into lotes_pesadas (select * from v_lotespesadastmp where idea2=0 and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
                   qaux.execsql;
                   qaux.close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('insert into ea_materiales (select * from v_eamaterialestmp where idea2=0 and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
                   qaux.ExecSQL;
                 end;
               end;
               if dm.qpesadasidEA.AsInteger<=0 then
               begin
                 v_idea:=dm.qpesadasidea.AsInteger-1;
                 dm.qpesadas.edit;
                 dm.qpesadasid_palet2.Value:='TRIGGER_ON';
                 dm.qpesadasiddestino.Value:=qdestinosid.asinteger;
                 dm.qpesadasdestino.value:=qdestinosnombre.AsString;
                 dm.qpesadasfechatrabajo.Value:=tfecha.date;
                 dm.qpesadasremanipulado.Value:=1;
                 dm.qpesadasobservaciones.value:=observaciones;
                 dm.qpesadasgen_caja.Value:=vgeneradores;
                 dm.qpesadas.Post;
                 if qorigenesalmacen_asociado.value<>null then
                 begin
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_pesadas_tmp set resto_cajas=0,resto_pesoneto=0,fecha='+vfecha+',fechatrabajo='+vfecha+',idea='+inttostr(v_idea)+',iddestino='+idalmacenintermedio+',destino='+''''+nomalmacenintermedio+''''+',idorigen='+qorigenesalmacen_asociado.asstring+',origen=(select nombre from almacenes where id='+qorigenesalmacen_asociado.asstring+' and idempresa='+qorigenesidempresa.asstring+'),observaciones='+''''+observaciones+''''+' where puesto='+tidbascula);
                   qaux.ExecSQL;
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update lotes_pesadas_tmp set resto_cajas=0,idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
                   qaux.ExecSQL;
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_materiales_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
                   qaux.ExecSQL;
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('insert into ea_pesadas (select * from v_eapesadastmp where idea='+inttostr(v_idea)+' and id='+inttostr(v_id)+' and idempresa='+inttostr(v_ide)+')');
                   qaux.ExecSQL;
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('insert into lotes_pesadas (select * from v_lotespesadastmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
                   qaux.execsql;
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('insert into ea_materiales (select * from v_eamaterialestmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
                   qaux.ExecSQL;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_pesadas set resto_cajas=0,resto_pesoneto=0 where id='+inttostr(v_id)+' and  idea='+inttostr(v_idea)+' and idempresa='+inttostr(v_ide));
                   qaux.ExecSQL;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_materiales set recuperado=-1 where idea='+inttostr(v_id)+' and  idea2='+inttostr(v_idea)+' and ide='+inttostr(v_ide));
                   qaux.ExecSQL;
                   qaux.sql.clear;
                   qaux.sql.Add('select sum(peso),sum(precio) from ea_materiales where ide='+inttostr(v_ide)+' and idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea));
                   qaux.open;
                   v_tara:=qaux.Fields[0].AsFloat;
                   v_costo:=qaux.fields[1].asfloat;
                   vtara:=floattostr(v_tara);
                   vtara:= StringReplace(vtara, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                   vcosto:=floattostr(v_costo);
                   vcosto:= StringReplace(vcosto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                   qaux.close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_pesadas set costo_materiales='+vcosto+',tara='+vtara+' where idempresa='+inttostr(v_ide)+' and id='+inttostr(v_id)+' and idea='+inttostr(v_idea));
                   qaux.ExecSQL;
                 end;
               end;

           end else
           begin   //1
               observaciones:=dm.qpesadasobservaciones.asstring;
               observaciones:=observaciones+' '+datetostr(tfecha.Date)+'('+qorigenesnombre.asstring+'-->'+qdestinosnombre.asstring+')';
               qaux.SQL.Clear;
               qaux.SQL.Add('select min(idea) from ea_pesadas where idempresa='+inttostr(v_ide)+' and id='+inttostr(v_id));
               qaux.open;
               v_idea:=qaux.fields[0].asinteger;
               if v_idea>=0 then v_idea:=-1 else v_idea:=v_idea-1;
               if qorigenesalmacen_asociado.value<>null then
               begin  //2
               //////////////////////   inserto el apunte intermedio en almacen
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_pesadas_tmp set resto_cajas=0,num_palets=0,fecha='+vfecha+',fechatrabajo='+vfecha+',idea='+inttostr(v_idea)+',iddestino='+idalmacenintermedio+',destino='+''''+nomalmacenintermedio+''''+',observaciones='+''''+observaciones+''''+' where puesto='+tidbascula);
                   qaux.ExecSQL;
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update lotes_pesadas_tmp set resto_cajas=0,idea2='+inttostr(v_idea)+' where puesto='+tidbascula);                    qaux.ExecSQL;
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_materiales_tmp set idea2='+inttostr(v_idea)+' where  puesto='+tidbascula);
                   qaux.ExecSQL;
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('insert into ea_pesadas (select * from v_eapesadastmp where idea='+inttostr(v_idea)+' and id='+inttostr(v_id)+' and idempresa='+inttostr(v_ide)+')');
                   qaux.ExecSQL;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('insert into lotes_pesadas (select * from v_lotespesadastmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
                   qaux.ExecSQL;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('insert into ea_materiales (select * from v_eamaterialestmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
                   qaux.ExecSQL;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_materiales set recuperado=-1 where idea='+inttostr(v_id)+' and  idea2='+inttostr(v_idea)+' and ide='+inttostr(v_ide));
                   qaux.ExecSQL;
                   qaux.sql.clear;
                   qaux.sql.Add('select sum(peso),sum(precio) from ea_materiales where ide='+inttostr(v_ide)+' and idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea));
                   qaux.open;
                   v_tara:=qaux.Fields[0].AsFloat;
                   v_costo:=qaux.fields[1].asfloat;
                   vtara:=floattostr(v_tara);
                   vtara:= StringReplace(vtara, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                   vcosto:=floattostr(v_costo);
                   vcosto:= StringReplace(vcosto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                   qaux.close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_pesadas set resto_cajas=0,costo_materiales='+vcosto+',tara='+vtara+' where idempresa='+inttostr(v_ide)+' and id='+inttostr(v_id)+' and idea='+inttostr(v_idea));
                   qaux.ExecSQL;
                   v_idea:=v_idea-1;
                   ///////////////   inserto el apunte parcial en clientes
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_pesadas_tmp set fecha='+vfecha+',fechatrabajo='+vfecha+',idea='+inttostr(v_idea)+',iddestino='+qdestinosid.asstring+',destino='+''''+qdestinosnombre.asstring+''''+',idorigen='+qorigenesalmacen_asociado.asstring+',origen=(select nombre from almacenes where id='+qorigenesalmacen_asociado.asstring+' and idempresa='+qorigenesidempresa.asstring+'),observaciones='+''''+observaciones+''''+' where  puesto='+tidbascula);
                   qaux.ExecSQL;
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update lotes_pesadas_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
                   qaux.ExecSQL;
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_materiales_tmp set idea2='+inttostr(v_idea)+' where  puesto='+tidbascula);
                   qaux.ExecSQL;
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('insert into ea_pesadas (select * from v_eapesadastmp where idea='+inttostr(v_idea)+' and id='+inttostr(v_id)+' and idempresa='+inttostr(v_ide)+')');
                   qaux.ExecSQL;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('insert into lotes_pesadas (select * from v_lotespesadastmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
                   qaux.execsql;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('insert into ea_materiales (select * from v_eamaterialestmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
                   qaux.execsql;
                   qaux.sql.clear;
                   qaux.sql.Add('select sum(peso),sum(precio) from ea_materiales where ide='+inttostr(v_ide)+' and idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea));
                   qaux.open;
                   v_tara:=qaux.Fields[0].AsFloat;
                   v_costo:=qaux.fields[1].asfloat;
                   vtara:=floattostr(v_tara);
                   vtara:= StringReplace(vtara, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                   vcosto:=floattostr(v_costo);
                   vcosto:= StringReplace(vcosto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                   qaux.close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_pesadas set costo_materiales='+vcosto+',tara='+vtara+' where idempresa='+inttostr(v_ide)+' and id='+inttostr(v_id)+' and idea='+inttostr(v_idea));
                   qaux.ExecSQL;
                   ///////////////   inserto el resto del palet en camara
                   v_idea:=v_idea-1;

                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_pesadas_tmp set num_palets=1,remanipulado=1,num_envases='+inttostr(cajas-newcajas)+',resto_cajas='+inttostr(cajas-newcajas)+',fechatrabajo='+vfecha+',idea='+inttostr(v_idea)+',iddestino='+qorigenesid.asstring+',destino='+''''+qorigenesnombre.asstring+''''+',idorigen='+qorigenesid.asstring+',origen='+''''+qorigenesnombre.asstring+''''+',observaciones='+''''+observaciones+''''+' where  puesto='+tidbascula);
                   qaux.ExecSQL;
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update lotes_pesadas_tmp set cajas='+inttostr(cajas-newcajas)+',resto_cajas='+inttostr(cajas-newcajas)+',idea2='+inttostr(v_idea)+' where  puesto='+tidbascula);
                   qaux.ExecSQL;
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_materiales_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
                   qaux.ExecSQL;
                   qaux.Close;
                   qaux.sql.clear;
                   qaux.sql.Add('delete from ea_materiales_tmp where idea2<='+inttostr(v_idea));
                   qaux.execsql;
                   qaux.Close;
                  insertarmaterialestmp(qinsertarmaterialestmp,v_id,v_idea,strtoint(tidbascula),dm.qpesadastmpnum_palets.asinteger,v_ide,dm.qpesadastmpid_palet.asstring,1.0);
{                   qaux.SQL.Clear;
                   qaux.SQL.Add('insert into ea_materiales_tmp ');
                   qaux.SQL.Add('select idempresa,'+inttostr(v_id)+' as idea,'+inttostr(v_idea)+' as idea2,idarticulof,sum(cantidadtotal) as cantidadtotal,sum(pesototal) as pesototal,null,sum(preciototal) as preciototal,0 as recuperado,null as identrada,'+tidbascula+' as puesto 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_tmp lp,articulos_almacen aa where aa.ide=lp.ide and aa.codigo=lp.id_envase ');
                   qaux.SQL.Add(' and lp.ide='+inttostr(v_ide)+' and lp.idea='+inttostr(v_id)+' and lp.idea2='+inttostr(v_idea)+' 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) 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_tmp lp, ');
                   qaux.SQL.Add(' configuraciones aa where aa.ide=lp.ide and aa.id=lp.id_formato and lp.ide='+inttostr(v_ide)+' and lp.idea='+inttostr(v_id)+' and lp.idea2='+inttostr(v_idea)+' 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*'+dm.qpesadastmpnum_palets.AsString+') as cantidadtotal,(ac.peso*'+dm.qpesadastmpnum_palets.AsString+') as pesototal,(ac.coste*'+dm.qpesadastmpnum_palets.AsString+') as preciototal');
                   qaux.SQL.Add(' FROM articulos_componentes ac where ac.idempresa='+inttostr(v_ide)+' and ac.idarticuloalmacen=(select id from articulos_almacen where codigo='+''''+dm.qpesadastmpid_palet.AsString+''''+')');
                   qaux.SQL.Add(' ) as ea_materiales_tmp group by idarticulof ');
                   qaux.execsql;
}
                   qaux.SQL.Clear;
                   qaux.SQL.Add('insert into ea_pesadas (select * from v_eapesadastmp where idea='+inttostr(v_idea)+' and id='+inttostr(v_id)+' and idempresa='+inttostr(v_ide)+')');
                   qaux.ExecSQL;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('insert into lotes_pesadas (select * from v_lotespesadastmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
                   qaux.execsql;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('insert into ea_materiales (select * from v_eamaterialestmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
                   qaux.execsql;
                   qaux.sql.clear;
                   qaux.sql.Add('select sum(peso),sum(precio) from ea_materiales where ide='+inttostr(v_ide)+' and idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea));
                   qaux.open;
                   v_tara:=qaux.Fields[0].AsFloat;
                   v_costo:=qaux.fields[1].asfloat;
                   v_pesomedio:= dm.qpesadaspeso_medio.asfloat;
                   v_pesoneto:=v_pesomedio*(cajas-newcajas);
                   v_pesobruto:=v_pesoneto+v_tara;
                   vtara:=floattostr(v_tara);
                   vtara:= StringReplace(vtara, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                   vcosto:=floattostr(v_costo);
                   vcosto:= StringReplace(vcosto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                   vneto:=floattostr(v_pesoneto);
                   vneto:= StringReplace(vneto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                   vbruto:=floattostr(v_pesobruto);
                   vbruto:= StringReplace(vbruto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                   qaux.close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_pesadas set peso_neto='+vneto+',peso_bruto='+vbruto+',costo_materiales='+vcosto+',tara='+vtara+' where idempresa='+inttostr(v_ide)+' and id='+inttostr(v_id)+' and idea='+inttostr(v_idea));
                   qaux.ExecSQL;
               end; //2
               dm.qpesadas.edit;
               dm.qpesadasid_palet2.Value:='TRIGGER_ON';
               dm.qpesadasiddestino.Value:=0;// strtoint(idalmacenintermedio);
               qaux.sql.clear;
               qaux.sql.add('select nombre from almacenes where id=0');
               qaux.Open;
               dm.qpesadasdestino.value:=qaux.fields[0].asstring;//'PALETS FRACCCIONADOS';// almacenintermedio;
               dm.qpesadasfechatrabajo.Value:=tfecha.date;
               dm.qpesadasremanipulado.Value:=1;
               dm.qpesadasobservaciones.value:=observaciones;
               dm.qpesadasgen_caja.Value:=vgeneradores;
               dm.qpesadasresto_cajas.Value:=0;
               dm.qpesadas.Post;
               v_id:=dm.qpesadasid.asinteger;
               v_idea:=dm.qpesadasidea.asinteger;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update lotes_pesadas set resto_cajas=0 where idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea)+' and ide='+inttostr(v_ide));
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_materiales set recuperado=-1 where idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea)+' and ide='+inttostr(v_ide));
               qaux.ExecSQL;
               qaux.sql.clear;
               qaux.sql.Add('select sum(peso),sum(precio) from ea_materiales where ide='+inttostr(v_ide)+' and idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea));
               qaux.open;
               v_tara:=qaux.Fields[0].AsFloat;
               v_costo:=qaux.fields[1].asfloat;
               vtara:=floattostr(v_tara);
               vtara:= StringReplace(vtara, ',', '.',[rfReplaceAll, rfIgnoreCase]);
               vcosto:=floattostr(v_costo);
               vcosto:= StringReplace(vcosto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
               qaux.close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_pesadas set costo_materiales='+vcosto+',tara='+vtara+' where idempresa='+inttostr(v_ide)+' and id='+inttostr(v_id)+' and idea='+inttostr(v_idea));
               qaux.ExecSQL;

           end;
    end;
//// de otros a produccion

        if (qorigenescamara.asinteger=0) and (qdestinosproduccion.AsInteger=1) and (qorigenesfinal.asinteger=0) then
        begin
       if cajas=newcajas then
           begin
               observaciones:=dm.qpesadasobservaciones.asstring;
               observaciones:=observaciones+datetostr(tfecha.Date)+'('+qorigenesnombre.asstring+'-->'+qdestinosnombre.asstring+')';
               dm.qpesadas.edit;
               dm.qpesadasid_palet2.Value:='TRIGGER_ON';
               dm.qpesadasiddestino.Value:=qdestinosid.asinteger;// strtoint(idalmacenintermedio);
               dm.qpesadasdestino.value:=qdestinosnombre.AsString;// almacenintermedio;
               dm.qpesadasfechatrabajo.Value:=tfecha.date;
               dm.qpesadasremanipulado.Value:=1;
               dm.qpesadasobservaciones.value:=observaciones;
               dm.qpesadasgen_caja.Value:=vgeneradores;
               dm.qpesadas.Post;
           end else
           begin
               observaciones:=dm.qpesadasobservaciones.asstring;
               observaciones:=observaciones+datetostr(tfecha.Date)+'('+qorigenesnombre.asstring+'-->'+qdestinosnombre.asstring+')';
               if v_idea<0 then v_idea:=v_idea-2 else v_idea:=-2;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_pesadas_tmp set idea='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update lotes_pesadas_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_materiales_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_pesadas (select * from v_eapesadastmp where idea='+inttostr(v_idea)+' and id='+inttostr(v_id)+' and idempresa='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into lotes_pesadas (select * from v_lotespesadastmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_materiales (select * from v_eamaterialestmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_pesadas_tmp set num_palets=0,remanipulado=1 where puesto='+tidbascula);
               qaux.ExecSQL;
               dm.qpesadastmp.refresh;
               dm.qpesadaslotes.First;
               while not dm.qpesadaslotes.eof do
               begin
                 qaux.Close;
                 qaux.SQL.Clear;
                 qaux.SQL.Add('select * from lotes_pesadas_tmp where id='+dm.qpesadaslotesid.asstring+' and puesto='+tidbascula);
                 qaux.open;
                 if qaux.RecordCount>0 then
                 begin
                   if dm.qpesadaslotescajas.AsInteger>qpesadaslotesmovcajas.AsInteger then
                   begin
                     v_bultos:=cajas-newcajas;
                     v_pesoneto:=(dm.qpesadaslotespesoneto_real.asfloat/cajas)*v_bultos;
                     v_pesoventa:=(dm.qpesadaslotespesoneto_teorico.asfloat/cajas)*v_bultos;
                     vneto:=floattostr(v_pesoneto);
                     vneto:= StringReplace(vneto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                     vventa:=floattostr(v_pesoventa);
                     vventa:= StringReplace(vventa, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                     qaux.Close;
                     qaux.SQL.Clear;
                     qaux.SQL.Add('update lotes_pesadas_tmp set cajas='+inttostr(v_bultos)+',resto_cajas='+inttostr(v_bultos)+',pesoneto_teorico='+vventa+',pesoneto_real='+vneto+' where id='+dm.qpesadaslotesid.asstring+' and puesto='+tidbascula);
                     qaux.ExecSQL;
                   end else
                   begin
                     qaux.Close;
                     qaux.SQL.Clear;
                     qaux.SQL.Add('delete from lotes_pesadas_tmp where puesto='+tidbascula);
                     qaux.ExecSQL;
                   end;
                 end else
                 begin
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('insert into lotes_pesadas_tmp (select *,'+tidbascula+' as puesto from lotes_pesadas where id='+dm.qpesadaslotesid.asstring+' and idea='+dm.qpesadaslotesidea.asstring+' and idea2='+dm.qpesadaslotesidea2.asstring+' and ide='+dm.qpesadasloteside.asstring+')');
                   qaux.ExecSQL;
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update lotes_pesadas_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
                   qaux.ExecSQL;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_pesadas_tmp set idea='+inttostr(v_idea)+' where puesto='+tidbascula);
                   qaux.ExecSQL;
                 end;
                  qaux.Close;
                  qaux.sql.clear;
                  qaux.sql.Add('delete from ea_materiales_tmp where puesto='+tidbascula);
                  qaux.execsql;

                  qaux.Close;
                  insertarmaterialestmp(qinsertarmaterialestmp,v_id,v_idea,strtoint(tidbascula),dm.qpesadastmpnum_palets.asinteger,v_ide,dm.qpesadastmpid_palet.asstring,1.0);
{
                  qaux.SQL.Clear;

                  qaux.SQL.Add('insert into ea_materiales_tmp ');
                  qaux.SQL.Add('select idempresa,'+inttostr(v_id)+' as idea,'+inttostr(v_idea)+' as idea2,idarticulof,sum(cantidadtotal) as cantidadtotal,sum(pesototal) as pesototal,null,sum(preciototal) as preciototal,0 as recuperado,null as identrada,'+tidbascula+' as puesto 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_tmp lp,articulos_almacen aa where aa.ide=lp.ide and aa.codigo=lp.id_envase ');
                  qaux.SQL.Add(' and lp.ide='+inttostr(v_ide)+' and lp.idea='+inttostr(v_id)+' and lp.idea2='+inttostr(v_idea)+' 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) 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_tmp lp, ');
                  qaux.SQL.Add(' configuraciones aa where aa.ide=lp.ide and aa.id=lp.id_formato and lp.ide='+inttostr(v_ide)+' and lp.idea='+inttostr(v_id)+' and lp.idea2='+inttostr(v_idea)+' 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*'+dm.qpesadastmpnum_palets.AsString+') as cantidadtotal,(ac.peso*'+dm.qpesadastmpnum_palets.AsString+') as pesototal,(ac.coste*'+dm.qpesadastmpnum_palets.AsString+') as preciototal');
                  qaux.SQL.Add(' FROM articulos_componentes ac where ac.idempresa='+inttostr(v_ide)+' and ac.idarticuloalmacen=(select id from articulos_almacen where codigo='+''''+dm.qpesadastmpid_palet.AsString+''''+')');
                  qaux.SQL.Add(' ) as ea_materiales_tmp group by idarticulof ');
                  qaux.execsql;
}
                  qaux.sql.clear;
                  qaux.sql.Add('select sum(pesoneto_teorico),sum(cajas),sum(pesoneto_real) from lotes_pesadas_tmp where idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea));
                  qaux.open;

                  v_bultos:=qaux.Fields[1].asinteger;
                  v_pesoventa:=qaux.Fields[0].AsFloat;
                  v_pesoneto:=qaux.Fields[2].AsFloat;
                  if v_bultos=0 then v_pesomedio:=0 else v_pesomedio:=v_pesoneto/v_bultos;
                  ////////////////////////
                  qaux.sql.clear;
                  qaux.sql.Add('select sum(peso) from ea_materiales_tmp where ide='+inttostr(v_ide)+' and idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea)+' and puesto='+tidbascula);
                  qaux.open;
                  v_tara:=qaux.Fields[0].AsFloat;
                  v_pesobruto:=v_tara+v_pesoneto;
                  vtara:=floattostr(v_tara);
                  vtara:= StringReplace(vtara, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vneto:=floattostr(v_pesoneto);
                  vneto:= StringReplace(vneto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vbruto:=floattostr(v_pesobruto);
                  vbruto:= StringReplace(vbruto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vventa:=floattostr(v_pesoventa);
                  vventa:= StringReplace(vventa, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vpesomedio:=floattostr(v_pesomedio);
                  vpesomedio:= StringReplace(vpesomedio, ',', '.',[rfReplaceAll, rfIgnoreCase]);

                  qaux.close;
                  qaux.SQL.Clear;
                  qaux.SQL.Add('update ea_pesadas_tmp set resto_cajas='+inttostr(v_bultos)+',num_envases='+inttostr(v_bultos)+',peso_medio='+vpesomedio+',peso_bruto='+vbruto+',tara='+vtara+',peso_neto='+vneto+',peso_neto_teorico='+vventa+',iddestino='+qorigenesid.AsString+',destino='+''''+qorigenesnombre.AsString+''''+' where idempresa='+inttostr(v_ide)+' and id='+inttostr(v_id)+' and idea='+inttostr(v_idea)+' and puesto='+tidbascula);
                  qaux.ExecSQL;
                  dm.qpesadastmp.close;
                  dm.qpesadastmp.Open;
                  dm.qpesadaslotes.Next;
               end;
               v_idea:=v_idea+1;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_pesadas_tmp set num_palets=0,idea='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update lotes_pesadas_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_materiales_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_pesadas (select * from v_eapesadastmp where idea='+inttostr(v_idea)+' and id='+inttostr(v_id)+' and idempresa='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into lotes_pesadas (select * from v_lotespesadastmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_materiales (select * from v_eamaterialestmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               dm.qpesadas.edit;
               dm.qpesadasid_palet2.Value:='TRIGGER_ON';
               dm.qpesadasiddestino.Value:=0;// strtoint(idalmacenintermedio);
               dm.qpesadasdestino.value:='PALETS FRACCCIONADOS';// almacenintermedio;
               dm.qpesadasfechatrabajo.Value:=tfecha.date;
               dm.qpesadasremanipulado.Value:=1;
               dm.qpesadasobservaciones.value:=observaciones;
               dm.qpesadasgen_caja.Value:=vgeneradores;
               dm.qpesadasresto_cajas.Value:=0;
               dm.qpesadas.Post;
                   v_ide:=dm.qpesadasidempresa.AsInteger;
                   v_id:=dm.qpesadasid.AsInteger;
                   v_idea:=dm.qpesadasidea.AsInteger;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_materiales set recuperado=-1 where idea='+inttostr(v_id)+' and  idea2='+inttostr(v_idea)+' and ide='+inttostr(v_ide));
                   qaux.ExecSQL;
                   qaux.sql.clear;
                   qaux.sql.Add('select sum(peso),sum(precio) from ea_materiales where ide='+inttostr(v_ide)+' and idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea));
                   qaux.open;
                   v_tara:=qaux.Fields[0].AsFloat;
                   v_costo:=qaux.fields[1].asfloat;
                   vtara:=floattostr(v_tara);
                   vtara:= StringReplace(vtara, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                   vcosto:=floattostr(v_costo);
                   vcosto:= StringReplace(vcosto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                   qaux.close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_pesadas set costo_materiales='+vcosto+',tara='+vtara+' where idempresa='+inttostr(v_ide)+' and id='+inttostr(v_id)+' and idea='+inttostr(v_idea));
                   qaux.ExecSQL;

               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update lotes_pesadas set resto_cajas=0 where idea='+inttostr(v_id)+' and idea2='+dm.qpesadasidea.asstring+' and ide='+inttostr(v_ide));
               qaux.ExecSQL;
           end;

        end;
//// de camara a produccion

        if (qorigenescamara.asinteger=1) and (qdestinosproduccion.AsInteger=1) then
        begin
       if cajas=newcajas then
           begin
               observaciones:=dm.qpesadasobservaciones.asstring;
               observaciones:=observaciones+datetostr(tfecha.Date)+'('+qorigenesnombre.asstring+'-->'+qdestinosnombre.asstring+')';
               dm.qpesadas.edit;
               dm.qpesadasid_palet2.Value:='TRIGGER_ON';
               dm.qpesadasiddestino.Value:=qdestinosid.asinteger;// strtoint(idalmacenintermedio);
               dm.qpesadasdestino.value:=qdestinosnombre.AsString;// almacenintermedio;
               dm.qpesadasfechatrabajo.Value:=tfecha.date;
               dm.qpesadasdias_camara.Value:=dias;
               dm.qpesadasremanipulado.Value:=1;
               dm.qpesadasobservaciones.value:=observaciones;
               dm.qpesadasgen_caja.Value:=vgeneradores;
               dm.qpesadas.Post;
           end else
           begin
               observaciones:=dm.qpesadasobservaciones.asstring;
               observaciones:=observaciones+datetostr(tfecha.Date)+'('+qorigenesnombre.asstring+'-->'+qdestinosnombre.asstring+')';
               if v_idea<0 then v_idea:=v_idea-2 else v_idea:=-2;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_pesadas_tmp set idorigen='+qorigenesid.AsString+',origen='+''''+qorigenesnombre.asstring+''''+',num_palets=0,remanipulado=1,dias_camara='+inttostr(dias)+',idea='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update lotes_pesadas_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_materiales_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_pesadas (select * from v_eapesadastmp where idea='+inttostr(v_idea)+' and id='+inttostr(v_id)+' and idempresa='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into lotes_pesadas (select * from v_lotespesadastmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_materiales (select * from v_eamaterialestmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.Close;
               dm.qpesadastmp.refresh;
               dm.qpesadaslotes.First;
               while not dm.qpesadaslotes.eof do
               begin
                 qaux.Close;
                 qaux.SQL.Clear;
                 qaux.SQL.Add('select * from lotes_pesadas_tmp where id='+dm.qpesadaslotesid.asstring+' and puesto='+tidbascula);
                 qaux.open;
                 if qaux.RecordCount>0 then
                 begin
                   if dm.qpesadaslotescajas.AsInteger>qpesadaslotesmovcajas.AsInteger then
                   begin
                     v_bultos:=cajas-newcajas;
                     v_pesoneto:=(dm.qpesadaslotespesoneto_real.asfloat/cajas)*v_bultos;
                     v_pesoventa:=(dm.qpesadaslotespesoneto_teorico.asfloat/cajas)*v_bultos;
                     vneto:=floattostr(v_pesoneto);
                     vneto:= StringReplace(vneto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                     vventa:=floattostr(v_pesoventa);
                     vventa:= StringReplace(vventa, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                     qaux.Close;
                     qaux.SQL.Clear;
                     qaux.SQL.Add('update lotes_pesadas_tmp set cajas='+inttostr(v_bultos)+',resto_cajas='+inttostr(v_bultos)+',pesoneto_teorico='+vventa+',pesoneto_real='+vneto+' where id='+dm.qpesadaslotesid.asstring+' and puesto='+tidbascula);
                     qaux.ExecSQL;
                   end else
                   begin
                     qaux.Close;
                     qaux.SQL.Clear;
                     qaux.SQL.Add('delete from lotes_pesadas_tmp where id='+dm.qpesadaslotesid.asstring);
                     qaux.ExecSQL;
                   end;
                 end else
                 begin
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('insert into lotes_pesadas_tmp (select *,'+tidbascula+' as puesto from lotes_pesadas where id='+dm.qpesadaslotesid.asstring+' and idea='+dm.qpesadaslotesidea.asstring+' and idea2='+dm.qpesadaslotesidea2.asstring+' and ide='+dm.qpesadasloteside.asstring+')');
                   qaux.ExecSQL;
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update lotes_pesadas_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
                   qaux.ExecSQL;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_pesadas_tmp set idea='+inttostr(v_idea)+' where puesto='+tidbascula);
                   qaux.ExecSQL;
                 end;
                  qaux.Close;
                  qaux.sql.clear;
                  qaux.sql.Add('delete from ea_materiales_tmp where puesto='+tidbascula);
                  qaux.execsql;

                  qaux.Close;
                  insertarmaterialestmp(qinsertarmaterialestmp,v_id,v_idea,strtoint(tidbascula),dm.qpesadastmpnum_palets.asinteger,v_ide,dm.qpesadastmpid_palet.asstring,1.0);
{
                  qaux.SQL.Clear;
                  qaux.SQL.Add('insert into ea_materiales_tmp ');
                  qaux.SQL.Add('select idempresa,'+inttostr(v_id)+' as idea,'+inttostr(v_idea)+' as idea2,idarticulof,sum(cantidadtotal) as cantidadtotal,sum(pesototal) as pesototal,null,sum(preciototal) as preciototal,0 as recuperado,null as identrada,'+tidbascula+' 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_tmp lp,articulos_almacen aa where aa.ide=lp.ide and aa.codigo=lp.id_envase ');
                  qaux.SQL.Add(' and lp.ide='+inttostr(v_ide)+' and lp.idea='+inttostr(v_id)+' and lp.idea2='+inttostr(v_idea)+' 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) 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_tmp lp, ');
                  qaux.SQL.Add(' configuraciones aa where aa.ide=lp.ide and aa.id=lp.id_formato and lp.ide='+inttostr(v_ide)+' and lp.idea='+inttostr(v_id)+' and lp.idea2='+inttostr(v_idea)+' 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*'+dm.qpesadastmpnum_palets.AsString+') as cantidadtotal,(ac.peso*'+dm.qpesadastmpnum_palets.AsString+') as pesototal,(ac.coste*'+dm.qpesadastmpnum_palets.AsString+') as preciototal');
                  qaux.SQL.Add(' FROM articulos_componentes ac where ac.idempresa='+inttostr(v_ide)+' and ac.idarticuloalmacen=(select id from articulos_almacen where codigo='+''''+dm.qpesadastmpid_palet.AsString+''''+')');
                  qaux.SQL.Add(' ) as ea_materiales_tmp group by idarticulof ');
                  qaux.execsql;
 }
                  qaux.sql.clear;
                  qaux.sql.Add('select sum(pesoneto_teorico),sum(cajas),sum(pesoneto_real) from lotes_pesadas_tmp where idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea)+' and puesto='+tidbascula);
                  qaux.open;

                  v_bultos:=qaux.Fields[1].asinteger;
                  v_pesoventa:=qaux.Fields[0].AsFloat;
                  v_pesoneto:=qaux.Fields[2].AsFloat;
                  if v_bultos=0 then v_pesomedio:=0 else v_pesomedio:=v_pesoneto/v_bultos;
                  ////////////////////////
                  qaux.sql.clear;
                  qaux.sql.Add('select sum(peso) from ea_materiales_tmp where ide='+inttostr(v_ide)+' and idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea));
                  qaux.open;
                  v_tara:=qaux.Fields[0].AsFloat;
                  v_pesobruto:=v_tara+v_pesoneto;
                  vtara:=floattostr(v_tara);
                  vtara:= StringReplace(vtara, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vneto:=floattostr(v_pesoneto);
                  vneto:= StringReplace(vneto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vbruto:=floattostr(v_pesobruto);
                  vbruto:= StringReplace(vbruto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vventa:=floattostr(v_pesoventa);
                  vventa:= StringReplace(vventa, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vpesomedio:=floattostr(v_pesomedio);
                  vpesomedio:= StringReplace(vpesomedio, ',', '.',[rfReplaceAll, rfIgnoreCase]);

                  qaux.close;
                  qaux.SQL.Clear;
                  qaux.SQL.Add('update ea_pesadas_tmp set resto_cajas='+inttostr(v_bultos)+',num_envases='+inttostr(v_bultos)+',peso_medio='+vpesomedio+',peso_bruto='+vbruto+',tara='+vtara+',peso_neto='+vneto+',peso_neto_teorico='+vventa+',iddestino='+qorigenesid.AsString+',destino='+''''+qorigenesnombre.AsString+''''+' where idempresa='+inttostr(v_ide)+' and id='+inttostr(v_id)+' and idea='+inttostr(v_idea)+' and puesto='+tidbascula);
                  qaux.ExecSQL;
                  dm.qpesadastmp.close;
                  dm.qpesadastmp.Open;
                  dm.qpesadaslotes.Next;
               end;
               v_idea:=v_idea+1;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_pesadas_tmp set num_palets=0,idea='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update lotes_pesadas_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_materiales_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_pesadas (select * from v_eapesadastmp where idea='+inttostr(v_idea)+' and id='+inttostr(v_id)+' and idempresa='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into lotes_pesadas (select * from v_lotespesadastmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_materiales (select * from v_eamaterialestmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               dm.qpesadas.edit;
               dm.qpesadasid_palet2.Value:='TRIGGER_ON';
               dm.qpesadasiddestino.Value:=0;// strtoint(idalmacenintermedio);
               dm.qpesadasdestino.value:='PALETS FRACCCIONADOS';// almacenintermedio;
               dm.qpesadasfechatrabajo.Value:=tfecha.date;
               dm.qpesadasremanipulado.Value:=1;
               dm.qpesadasobservaciones.value:=observaciones;
               dm.qpesadasgen_caja.Value:=vgeneradores;
               dm.qpesadasresto_cajas.Value:=0;
               dm.qpesadas.Post;
                   v_ide:=dm.qpesadasidempresa.AsInteger;
                   v_id:=dm.qpesadasid.AsInteger;
                   v_idea:=dm.qpesadasidea.AsInteger;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_materiales set recuperado=-1 where idea='+inttostr(v_id)+' and  idea2='+inttostr(v_idea)+' and ide='+inttostr(v_ide));
                   qaux.ExecSQL;
                   qaux.sql.clear;
                   qaux.sql.Add('select sum(peso),sum(precio) from ea_materiales where ide='+inttostr(v_ide)+' and idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea));
                   qaux.open;
                   v_tara:=qaux.Fields[0].AsFloat;
                   v_costo:=qaux.fields[1].asfloat;
                   vtara:=floattostr(v_tara);
                   vtara:= StringReplace(vtara, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                   vcosto:=floattostr(v_costo);
                   vcosto:= StringReplace(vcosto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                   qaux.close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_pesadas set costo_materiales='+vcosto+',tara='+vtara+' where idempresa='+inttostr(v_ide)+' and id='+inttostr(v_id)+' and idea='+inttostr(v_idea));
                   qaux.ExecSQL;

               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update lotes_pesadas set resto_cajas=0 where idea='+inttostr(v_id)+' and idea2='+dm.qpesadasidea.asstring+' and ide='+inttostr(v_ide));
               qaux.ExecSQL;
           end;
        end;
//// de camara a camara
        if (qorigenescamara.asinteger=1) and (qdestinoscamara.AsInteger=1) then
        begin
       if cajas=newcajas then
           begin
               observaciones:=dm.qpesadasobservaciones.asstring;
               observaciones:=observaciones+datetostr(tfecha.Date)+'('+qorigenesnombre.asstring+'-->'+qdestinosnombre.asstring+')';
               dm.qpesadas.edit;
               dm.qpesadasid_palet2.Value:='TRIGGER_ON';
               dm.qpesadasiddestino.Value:=qdestinosid.asinteger;// strtoint(idalmacenintermedio);
               dm.qpesadasdestino.value:=qdestinosnombre.AsString;// almacenintermedio;
//               dm.qpesadasfechatrabajo.Value:=tfecha.date;
               dm.qpesadasremanipulado.Value:=1;
               dm.qpesadasobservaciones.value:=observaciones;
               dm.qpesadasgen_caja.Value:=vgeneradores;
               dm.qpesadas.Post;
           end else
           begin
               observaciones:=dm.qpesadasobservaciones.asstring;
               observaciones:=observaciones+datetostr(tfecha.Date)+'('+qorigenesnombre.asstring+'-->'+qdestinosnombre.asstring+')';
               if v_idea<0 then v_idea:=v_idea-2 else v_idea:=-2;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_pesadas_tmp set idea='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update lotes_pesadas_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_materiales_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_pesadas (select *,'+tidbascula+' as puesto from ea_pesadas_tmp where idea='+inttostr(v_idea)+' and id='+inttostr(v_id)+' and idempresa='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into lotes_pesadas (select *,'+tidbascula+' as puesto from lotes_pesadas_tmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_materiales (select *,'+tidbascula+' as puesto from ea_materiales_tmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_pesadas_tmp set num_palets=0,remanipulado=1 where puesto='+tidbascula);
               qaux.ExecSQL;
               dm.qpesadastmp.refresh;
               dm.qpesadaslotes.First;
               while not dm.qpesadaslotes.eof do
               begin
                 qaux.Close;
                 qaux.SQL.Clear;
                 qaux.SQL.Add('select * from lotes_pesadas_tmp where id='+dm.qpesadaslotesid.asstring+' and puesto='+tidbascula);
                 qaux.open;
                 if qaux.RecordCount>0 then
                 begin
                   if dm.qpesadaslotescajas.AsInteger>qpesadaslotesmovcajas.AsInteger then
                   begin
                     v_bultos:=cajas-newcajas;
                     v_pesoneto:=(dm.qpesadaslotespesoneto_real.asfloat/cajas)*v_bultos;
                     v_pesoventa:=(dm.qpesadaslotespesoneto_teorico.asfloat/cajas)*v_bultos;
                     vneto:=floattostr(v_pesoneto);
                     vneto:= StringReplace(vneto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                     vventa:=floattostr(v_pesoventa);
                     vventa:= StringReplace(vventa, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                     qaux.Close;
                     qaux.SQL.Clear;
                     qaux.SQL.Add('update lotes_pesadas_tmp set cajas='+inttostr(v_bultos)+',resto_cajas='+inttostr(v_bultos)+',pesoneto_teorico='+vventa+',pesoneto_real='+vneto+' where id='+dm.qpesadaslotesid.asstring+' and puesto='+tidbascula);
                     qaux.ExecSQL;
                   end else
                   begin
                     qaux.Close;
                     qaux.SQL.Clear;
                     qaux.SQL.Add('delete from lotes_pesadas_tmp where id='+dm.qpesadaslotesid.asstring+' and puesto='+tidbascula);
                     qaux.ExecSQL;
                   end;
                 end else
                 begin
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('insert into lotes_pesadas_tmp (select *,'+tidbascula+' as puesto from lotes_pesadas where id='+dm.qpesadaslotesid.asstring+' and idea='+dm.qpesadaslotesidea.asstring+' and idea2='+dm.qpesadaslotesidea2.asstring+' and ide='+dm.qpesadasloteside.asstring+')');
                   qaux.ExecSQL;
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update lotes_pesadas_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
                   qaux.ExecSQL;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_pesadas_tmp set idea='+inttostr(v_idea)+' where puesto='+tidbascula);
                   qaux.ExecSQL;
                 end;
                  qaux.Close;
                  qaux.sql.clear;
                  qaux.sql.Add('delete from ea_materiales_tmp where idea2<0 and puesto='+tidbascula);
                  qaux.execsql;
                  insertarmaterialestmp(qinsertarmaterialestmp,v_id,v_idea,strtoint(tidbascula),dm.qpesadastmpnum_palets.asinteger,v_ide,dm.qpesadastmpid_palet.asstring,1.0);
{                  qaux.Close;
                  qaux.SQL.Clear;
                  qaux.SQL.Add('insert into ea_materiales_tmp ');
                  qaux.SQL.Add('select idempresa,'+inttostr(v_id)+' as idea,'+inttostr(v_idea)+' as idea2,idarticulof,sum(cantidadtotal) as cantidadtotal,sum(pesototal) as pesototal,null,sum(preciototal) as preciototal,0 as recuperado,null as identrada,'+tidbascula+' as puesto 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_tmp lp,articulos_almacen aa where aa.ide=lp.ide and aa.codigo=lp.id_envase ');
                  qaux.SQL.Add(' and lp.ide='+inttostr(v_ide)+' and lp.idea='+inttostr(v_id)+' and lp.idea2='+inttostr(v_idea)+' 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) 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_tmp lp, ');
                  qaux.SQL.Add(' configuraciones aa where aa.ide=lp.ide and aa.id=lp.id_formato and lp.ide='+inttostr(v_ide)+' and lp.idea='+inttostr(v_id)+' and lp.idea2='+inttostr(v_idea)+' 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*'+dm.qpesadastmpnum_palets.AsString+') as cantidadtotal,(ac.peso*'+dm.qpesadastmpnum_palets.AsString+') as pesototal,(ac.coste*'+dm.qpesadastmpnum_palets.AsString+') as preciototal');
                  qaux.SQL.Add(' FROM articulos_componentes ac where ac.idempresa='+inttostr(v_ide)+' and ac.idarticuloalmacen=(select id from articulos_almacen where codigo='+''''+dm.qpesadastmpid_palet.AsString+''''+')');
                  qaux.SQL.Add(' ) as ea_materiales_tmp group by idarticulof ');
                  qaux.execsql;
 }
                  qaux.sql.clear;
                  qaux.sql.Add('select sum(pesoneto_teorico),sum(cajas),sum(pesoneto_real) from lotes_pesadas_tmp where idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea)+' and puesto='+tidbascula);
                  qaux.open;

                  v_bultos:=qaux.Fields[1].asinteger;
                  v_pesoventa:=qaux.Fields[0].AsFloat;
                  v_pesoneto:=qaux.Fields[2].AsFloat;
                  if v_bultos=0 then v_pesomedio:=0 else v_pesomedio:=v_pesoneto/v_bultos;
                  ////////////////////////
                  qaux.sql.clear;
                  qaux.sql.Add('select sum(peso) from ea_materiales_tmp where ide='+inttostr(v_ide)+' and idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea)+' and puesto='+tidbascula);
                  qaux.open;
                  v_tara:=qaux.Fields[0].AsFloat;
                  v_pesobruto:=v_tara+v_pesoneto;
                  vtara:=floattostr(v_tara);
                  vtara:= StringReplace(vtara, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vneto:=floattostr(v_pesoneto);
                  vneto:= StringReplace(vneto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vbruto:=floattostr(v_pesobruto);
                  vbruto:= StringReplace(vbruto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vventa:=floattostr(v_pesoventa);
                  vventa:= StringReplace(vventa, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vpesomedio:=floattostr(v_pesomedio);
                  vpesomedio:= StringReplace(vpesomedio, ',', '.',[rfReplaceAll, rfIgnoreCase]);

                  qaux.close;
                  qaux.SQL.Clear;
                  qaux.SQL.Add('update ea_pesadas_tmp set resto_cajas='+inttostr(v_bultos)+',num_envases='+inttostr(v_bultos)+',peso_medio='+vpesomedio+',peso_bruto='+vbruto+',tara='+vtara+',peso_neto='+vneto+',peso_neto_teorico='+vventa+',iddestino='+qorigenesid.AsString+',destino='+''''+qorigenesnombre.AsString+''''+' where idempresa='+inttostr(v_ide)+' and id='+inttostr(v_id)+' and idea='+inttostr(v_idea)+' and puesto='+tidbascula);
                  qaux.ExecSQL;
                  dm.qpesadastmp.close;
                  dm.qpesadastmp.Open;
                  dm.qpesadaslotes.Next;
               end;
               v_idea:=v_idea+1;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_pesadas_tmp set num_palets=0,idea='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update lotes_pesadas_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_materiales_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_pesadas (select * from v_eapesadastmp where idea='+inttostr(v_idea)+' and id='+inttostr(v_id)+' and idempresa='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into lotes_pesadas (select * from v_lotespesadastmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_materiales (select * from v_eamaterialestmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               dm.qpesadas.edit;
               dm.qpesadasid_palet2.Value:='TRIGGER_ON';
               dm.qpesadasiddestino.Value:=0;// strtoint(idalmacenintermedio);
               dm.qpesadasdestino.value:='PALETS FRACCCIONADOS';// almacenintermedio;
               dm.qpesadasfechatrabajo.Value:=tfecha.date;
               dm.qpesadasremanipulado.Value:=1;
               dm.qpesadasobservaciones.value:=observaciones;
               dm.qpesadasgen_caja.Value:=vgeneradores;
               dm.qpesadasresto_cajas.Value:=0;
               dm.qpesadas.Post;
                   v_ide:=dm.qpesadasidempresa.AsInteger;
                   v_id:=dm.qpesadasid.AsInteger;
                   v_idea:=dm.qpesadasidea.AsInteger;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_materiales set recuperado=-1 where idea='+inttostr(v_id)+' and  idea2='+inttostr(v_idea)+' and ide='+inttostr(v_ide));
                   qaux.ExecSQL;
                   qaux.sql.clear;
                   qaux.sql.Add('select sum(peso),sum(precio) from ea_materiales where ide='+inttostr(v_ide)+' and idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea));
                   qaux.open;
                   v_tara:=qaux.Fields[0].AsFloat;
                   v_costo:=qaux.fields[1].asfloat;
                   vtara:=floattostr(v_tara);
                   vtara:= StringReplace(vtara, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                   vcosto:=floattostr(v_costo);
                   vcosto:= StringReplace(vcosto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                   qaux.close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_pesadas set costo_materiales='+vcosto+',tara='+vtara+' where idempresa='+inttostr(v_ide)+' and id='+inttostr(v_id)+' and idea='+inttostr(v_idea));
                   qaux.ExecSQL;

               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update lotes_pesadas set resto_cajas=0 where idea='+inttostr(v_id)+' and idea2='+dm.qpesadasidea.asstring+' and ide='+inttostr(v_ide));
               qaux.ExecSQL;
           end;
        end;
// produccion a camara
        if (qorigenesproduccion.asinteger=1) and (qdestinoscamara.asinteger=1) then
        begin
       if cajas=newcajas then
           begin
               observaciones:=dm.qpesadasobservaciones.asstring;
               observaciones:=observaciones+datetostr(tfecha.Date)+'('+qorigenesnombre.asstring+'-->'+qdestinosnombre.asstring+')';
               dm.qpesadas.edit;
               dm.qpesadasid_palet2.Value:='TRIGGER_ON';
               dm.qpesadasiddestino.Value:=qdestinosid.asinteger;// strtoint(idalmacenintermedio);
               dm.qpesadasdestino.value:=qdestinosnombre.AsString;// almacenintermedio;
               dm.qpesadasfechatrabajo.Value:=tfecha.date;
               dm.qpesadasremanipulado.Value:=1;
               dm.qpesadasobservaciones.value:=observaciones;
               dm.qpesadasgen_caja.Value:=vgeneradores;
               dm.qpesadas.Post;
           end else
           begin
             qaux.Close;
             qaux.SQL.Clear;
             qaux.SQL.Add('select min(idea) from ea_pesadas where id='+inttostr(v_id)+' and idempresa='+inttostr(v_ide));
             qaux.open;
             v_idea:=qaux.Fields[0].AsInteger;
               observaciones:=dm.qpesadasobservaciones.asstring;
               observaciones:=observaciones+datetostr(tfecha.Date)+'('+qorigenesnombre.asstring+'-->'+qdestinosnombre.asstring+')';
               if v_idea<0 then v_idea:=v_idea-2 else v_idea:=-2;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_pesadas_tmp set idea='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update lotes_pesadas_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_materiales_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_pesadas (select * from v_eapesadastmp where idea='+inttostr(v_idea)+' and id='+inttostr(v_id)+' and idempresa='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into lotes_pesadas (select * from v_lotespesadastmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_materiales (select * from v_eamaterialestmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_pesadas_tmp set num_palets=0,remanipulado=1 where puesto='+tidbascula);
               qaux.ExecSQL;
               dm.qpesadastmp.refresh;
               dm.qpesadaslotes.First;
               while not dm.qpesadaslotes.eof do
               begin
                 qaux.Close;
                 qaux.SQL.Clear;
                 qaux.SQL.Add('select * from lotes_pesadas_tmp where id='+dm.qpesadaslotesid.asstring+' and puesto='+tidbascula);
                 qaux.open;
                 if qaux.RecordCount>0 then
                 begin
                   if dm.qpesadaslotescajas.AsInteger>qpesadaslotesmovcajas.AsInteger then
                   begin
                     v_bultos:=cajas-newcajas;
                     v_pesoneto:=(dm.qpesadaslotespesoneto_real.asfloat/cajas)*v_bultos;
                     v_pesoventa:=(dm.qpesadaslotespesoneto_teorico.asfloat/cajas)*v_bultos;
                     vneto:=floattostr(v_pesoneto);
                     vneto:= StringReplace(vneto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                     vventa:=floattostr(v_pesoventa);
                     vventa:= StringReplace(vventa, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                     qaux.Close;
                     qaux.SQL.Clear;
                     qaux.SQL.Add('update lotes_pesadas_tmp set cajas='+inttostr(v_bultos)+',resto_cajas='+inttostr(v_bultos)+',pesoneto_teorico='+vventa+',pesoneto_real='+vneto+' where id='+dm.qpesadaslotesid.asstring+' and puesto='+tidbascula);
                     qaux.ExecSQL;
                   end else
                   begin
                     qaux.Close;
                     qaux.SQL.Clear;
                     qaux.SQL.Add('delete from lotes_pesadas_tmp where id='+dm.qpesadaslotesid.asstring+' and puesto='+tidbascula);
                     qaux.ExecSQL;
                   end;
                 end else
                 begin
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('insert into lotes_pesadas_tmp (select *,'+tidbascula+' as puesto from lotes_pesadas where id='+dm.qpesadaslotesid.asstring+' and idea='+dm.qpesadaslotesidea.asstring+' and idea2='+dm.qpesadaslotesidea2.asstring+' and ide='+dm.qpesadasloteside.asstring+')');
                   qaux.ExecSQL;
                   qaux.Close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update lotes_pesadas_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
                   qaux.ExecSQL;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_pesadas_tmp set idea='+inttostr(v_idea)+' where puesto='+tidbascula);
                   qaux.ExecSQL;
                 end;
                  qaux.Close;
                  qaux.sql.clear;
                  qaux.sql.Add('delete from ea_materiales_tmp where puesto='+tidbascula);
                  qaux.execsql;

                  insertarmaterialestmp(qinsertarmaterialestmp,v_id,v_idea,strtoint(tidbascula),dm.qpesadastmpnum_palets.asinteger,v_ide,dm.qpesadastmpid_palet.asstring,1.0);
{                  qaux.Close;
                  qaux.SQL.Clear;
                  qaux.SQL.Add('insert into ea_materiales_tmp ');
                  qaux.SQL.Add('select idempresa,'+inttostr(v_id)+' as idea,'+inttostr(v_idea)+' as idea2,idarticulof,sum(cantidadtotal) as cantidadtotal,sum(pesototal) as pesototal,null,sum(preciototal) as preciototal,0 as recuperado,null as identrada,'+tidbascula+' as puesto 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_tmp lp,articulos_almacen aa where aa.ide=lp.ide and aa.codigo=lp.id_envase ');
                  qaux.SQL.Add(' and lp.ide='+inttostr(v_ide)+' and lp.idea='+inttostr(v_id)+' and lp.idea2='+inttostr(v_idea)+' 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) 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_tmp lp, ');
                  qaux.SQL.Add(' configuraciones aa where aa.ide=lp.ide and aa.id=lp.id_formato and lp.ide='+inttostr(v_ide)+' and lp.idea='+inttostr(v_id)+' and lp.idea2='+inttostr(v_idea)+' 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*'+dm.qpesadastmpnum_palets.AsString+') as cantidadtotal,(ac.peso*'+dm.qpesadastmpnum_palets.AsString+') as pesototal,(ac.coste*'+dm.qpesadastmpnum_palets.AsString+') as preciototal');
                  qaux.SQL.Add(' FROM articulos_componentes ac where ac.idempresa='+inttostr(v_ide)+' and ac.idarticuloalmacen=(select id from articulos_almacen where codigo='+''''+dm.qpesadastmpid_palet.AsString+''''+')');
                  qaux.SQL.Add(' ) as ea_materiales_tmp group by idarticulof ');
                  qaux.execsql;
 }
                  qaux.sql.clear;
                  qaux.sql.Add('select sum(pesoneto_teorico),sum(cajas),sum(pesoneto_real) from lotes_pesadas_tmp where idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea)+' and puesto='+tidbascula);
                  qaux.open;

                  v_bultos:=qaux.Fields[1].asinteger;
                  v_pesoventa:=qaux.Fields[0].AsFloat;
                  v_pesoneto:=qaux.Fields[2].AsFloat;
                  if v_bultos=0 then v_pesomedio:=0 else v_pesomedio:=v_pesoneto/v_bultos;
                  ////////////////////////
                  qaux.sql.clear;
                  qaux.sql.Add('select sum(peso) from ea_materiales_tmp where ide='+inttostr(v_ide)+' and idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea)+' and puesto='+tidbascula);
                  qaux.open;
                  v_tara:=qaux.Fields[0].AsFloat;
                  v_pesobruto:=v_tara+v_pesoneto;
                  vtara:=floattostr(v_tara);
                  vtara:= StringReplace(vtara, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vneto:=floattostr(v_pesoneto);
                  vneto:= StringReplace(vneto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vbruto:=floattostr(v_pesobruto);
                  vbruto:= StringReplace(vbruto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vventa:=floattostr(v_pesoventa);
                  vventa:= StringReplace(vventa, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  vpesomedio:=floattostr(v_pesomedio);
                  vpesomedio:= StringReplace(vpesomedio, ',', '.',[rfReplaceAll, rfIgnoreCase]);

                  qaux.close;
                  qaux.SQL.Clear;
                  qaux.SQL.Add('update ea_pesadas_tmp set resto_cajas='+inttostr(v_bultos)+',num_envases='+inttostr(v_bultos)+',peso_medio='+vpesomedio+',peso_bruto='+vbruto+',tara='+vtara+',peso_neto='+vneto+',peso_neto_teorico='+vventa+',iddestino='+qorigenesid.AsString+',destino='+''''+qorigenesnombre.AsString+''''+' where idempresa='+inttostr(v_ide)+' and id='+inttostr(v_id)+' and idea='+inttostr(v_idea)+' and puesto='+tidbascula);
                  qaux.ExecSQL;
                  dm.qpesadastmp.close;
                  dm.qpesadastmp.Open;
                  dm.qpesadaslotes.Next;
               end;
               v_idea:=v_idea+1;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_pesadas_tmp set num_palets=0,idea='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update lotes_pesadas_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update ea_materiales_tmp set idea2='+inttostr(v_idea)+' where puesto='+tidbascula);
               qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_pesadas (select * from v_eapesadastmp where idea='+inttostr(v_idea)+' and id='+inttostr(v_id)+' and idempresa='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into lotes_pesadas (select * from v_lotespesadastmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               qaux.SQL.Clear;
               qaux.SQL.Add('insert into ea_materiales (select * from v_eamaterialestmp where idea2='+inttostr(v_idea)+' and idea='+inttostr(v_id)+' and ide='+inttostr(v_ide)+')');
               qaux.ExecSQL;
               dm.qpesadas.edit;
               dm.qpesadasid_palet2.Value:='TRIGGER_ON';
               dm.qpesadasiddestino.Value:=0;// strtoint(idalmacenintermedio);
               dm.qpesadasdestino.value:='PALETS FRACCCIONADOS';// almacenintermedio;
               dm.qpesadasfechatrabajo.Value:=tfecha.date;
               dm.qpesadasremanipulado.Value:=1;
               dm.qpesadasobservaciones.value:=observaciones;
               dm.qpesadasgen_caja.Value:=vgeneradores;
               dm.qpesadasresto_cajas.Value:=0;
               dm.qpesadas.Post;
                   v_ide:=dm.qpesadasidempresa.AsInteger;
                   v_id:=dm.qpesadasid.AsInteger;
                   v_idea:=dm.qpesadasidea.AsInteger;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_materiales set recuperado=-1 where idea='+inttostr(v_id)+' and  idea2='+inttostr(v_idea)+' and ide='+inttostr(v_ide));
                   qaux.ExecSQL;
                   qaux.sql.clear;
                   qaux.sql.Add('select sum(peso),sum(precio) from ea_materiales where ide='+inttostr(v_ide)+' and idea='+inttostr(v_id)+' and idea2='+inttostr(v_idea));
                   qaux.open;
                   v_tara:=qaux.Fields[0].AsFloat;
                   v_costo:=qaux.fields[1].asfloat;
                   vtara:=floattostr(v_tara);
                   vtara:= StringReplace(vtara, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                   vcosto:=floattostr(v_costo);
                   vcosto:= StringReplace(vcosto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                   qaux.close;
                   qaux.SQL.Clear;
                   qaux.SQL.Add('update ea_pesadas set costo_materiales='+vcosto+',tara='+vtara+' where idempresa='+inttostr(v_ide)+' and id='+inttostr(v_id)+' and idea='+inttostr(v_idea));
                   qaux.ExecSQL;
               qaux.Close;
               qaux.SQL.Clear;
               qaux.SQL.Add('update lotes_pesadas set resto_cajas=0 where idea='+inttostr(v_id)+' and idea2='+dm.qpesadasidea.asstring+' and ide='+inttostr(v_ide));
               qaux.ExecSQL;
           end;
        end;
//////////////////////////


   comboorigen.KeyValue:=null;
   combodestino.KeyValue:=null;
   dm.qpesadas.Close;
   dm.qpesadastmp.Close;
   dm.qpesadaslotes.Close;
   qpesadaslotesmov.Close;
   tid.Text:='';
   tid.SetFocus;
   qaux.Close;
   qaux.sql.clear;
   qaux.sql.Add('delete from ea_materiales_tmp where  puesto='+tidbascula);
   qaux.execsql;
   qaux.Close;
   qaux.sql.clear;
   qaux.sql.Add('delete from ea_pesadas_tmp where  puesto='+tidbascula);
   qaux.execsql;
   qaux.Close;
   qaux.sql.clear;
   qaux.sql.Add('delete from lotes_pesadas_tmp where puesto='+tidbascula);
   qaux.execsql;
end;

procedure Tgeneral.Button1Click(Sender: TObject);
begin

    qinfpartidas.Close;
    qinfpartidas.SQL.Clear;
    qinfpartidas.SQL.Add('select l.id as partida,p.id,p.fecha,pc.nombre,mp.descripcion,ea.matricula,eap.id,eap.num_palets,eap.id_envase,eap.num_envases,eap.peso_bruto,eap.tara,eap.peso_neto,eap.peso_medio,eap.temperatura,eap.cea,eap.destino,eap.lote,eap.tara0,l.trazabilidad');
    qinfpartidas.SQL.Add(',ea.hora,l.productor,l.sgg,l.sdop,l.sigp,l.sifs,l.sbrc from lotes l,partidas p, parcelas pc,materias_primas mp, entradas_almacen ea,ea_pesadas eap ');
    qinfpartidas.SQL.Add('where eap.lote=l.codigo and p.id_parcela=pc.codpar and p.id_mprimas=mp.id and p.id=ea.partida and ea.id=eap.idea and ');
    qinfpartidas.SQL.Add('p.id='+qpartidasid.asstring);
    qinfpartidas.SQL.Add(' order by eap.hora');
    qinfpartidas.open;
    informedb.Datasource:=dsqinfpartidas;
    informes.Report.Clear;
    informes.LoadFromFile('c:\agrigest\informes\entradas-partida.fr3');
    informes.Variables.Variables['TITULO']:=QUOTEDSTR('Lote: '+qpartidaslote.asstring+ ' FECHA: '+datetostr(tfecha.Date)+' PARCELA: '+qinfpartidasnombre.AsString+' VARIEDAD: '+qinfpartidasdescripcion.AsString+' TRAZABILIDAD: '+qinfpartidastrazabilidad.AsString);
    informes.ShowReport();
end;

procedure Tgeneral.btactualloteClick(Sender: TObject);
var cajas,newcajas,newpalets:integer;
    pneto,newpneto,preal,newpreal,tara:real;
    v_ide,v_id,v_idea,vneto,vbruto,vventa,vpesomedio,vtara,vbultos:string;
    v_bultos,v_palets:integer;
    v_tara,v_taraanterior,v_pesoneto,v_pesobruto,v_pesoventa,v_pesomedio:real;
begin
   v_ide:=dm.qpesadasidempresa.Asstring;
   v_id:=dm.qpesadasid.Asstring;
   v_idea:=dm.qpesadasidea.Asstring;
   v_bultos:=strtoint(tbultos.Text);
   cajas:=dm.qpesadaslotesresto_cajas.asinteger;
   if v_bultos<cajas then v_palets:=0 else v_palets:=1;

   pneto:=dm.qpesadaslotespesoneto_teorico.AsFloat/cajas;
   preal:=dm.qpesadaslotespesoneto_real.AsFloat/cajas;
   v_pesoventa:=pneto*v_bultos;
   v_pesoneto:=preal*v_bultos;
   vneto:=floattostr(v_pesoneto);
   vneto:= StringReplace(vneto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
   vventa:=floattostr(v_pesoventa);
   vventa:= StringReplace(vventa, ',', '.',[rfReplaceAll, rfIgnoreCase]);

   qpesadaslotesmov.open;
   qaux.Close;
   qaux.SQL.Clear;
   qaux.SQL.Add('select * from ea_pesadas_tmp where puesto='+tidbascula+' and id='+v_id+' and idempresa='+v_ide+' and idea='+v_idea);
   qaux.Open;
   if qaux.RecordCount=0 then
   begin
     qaux.Close;
     qaux.SQL.Clear;
     qaux.SQL.Add('insert into ea_pesadas_tmp select *,'+tidbascula+' as puesto from ea_pesadas where id='+v_id+' and idea='+v_idea+' and idempresa='+v_ide);
     qaux.ExecSQL;
   end;
   qaux.Close;
   qaux.SQL.Clear;
   qaux.SQL.Add('select * from lotes_pesadas_tmp where puesto='+tidbascula+' and idea='+v_idea+' and ide='+v_ide+' and idea2=+'+v_idea);
   qaux.Open;
   if qaux.RecordCount=0 then
   begin
     qaux.Close;
     qaux.SQL.Clear;
     qaux.SQL.Add('insert into lotes_pesadas_tmp select id,ide,idea,idea2,lote,cajas,id_envase,id_formato,desc_envase,desc_formato,pesoneto_teorico,pesoneto_real,es_entrada,parcela,mprima,calibrecalidad,desc_calibre,resto_cajas,'+tidbascula+' as puesto from lotes_pesadas where id='+dm.qpesadaslotesid.asstring+' and idea ='+v_id+' and idea2='+v_idea+' and ide='+v_ide);
     qaux.ExecSQL;

   end;
   qaux.Close;
   qaux.SQL.Clear;
   qaux.SQL.Add('select * from lotes_pesadas_tmp where puesto='+tidbascula+' and idea='+v_id+' and ide='+v_ide+' and idea2='+v_idea);
   qaux.Open;
   if qaux.RecordCount=1 then
   begin
     qaux.Close;
     qaux.SQL.Clear;
     qaux.SQL.Add('update lotes_pesadas_tmp set pesoneto_real='+vneto+',pesoneto_teorico='+vventa+',cajas='+inttostr(v_bultos)+',resto_cajas='+inttostr(v_bultos)+' where puesto='+tidbascula+' and idea='+v_id+' and ide='+v_ide);
     qaux.ExecSQL;
   end;
   qpesadaslotesmov.refresh;
   qaux.Close;
   qaux.SQL.Clear;
   qaux.SQL.Add('select * from lotes_pesadas_tmp where puesto='+tidbascula);
   qaux.Open;
   if qaux.RecordCount>0 then
   begin
     qaux.Close;
     qaux.SQL.Clear;
     qaux.SQL.Add('select sum(pesoneto_teorico),sum(pesoneto_real) from lotes_pesadas_tmp where puesto='+tidbascula);
     qaux.Open;
     v_pesoventa:=qaux.Fields[0].AsFloat;
     v_pesoneto:=qaux.Fields[1].AsFloat;
     qaux.SQL.Clear;
     qaux.SQL.Add('select compuesto from materias_primas where id='+''''+dm.qpesadastmpmprima.asstring+'''');
     qaux.Open;
     if qaux.Fields[0].Asinteger=1 then
     begin
       qaux.Close;
       qaux.SQL.Clear;
       qaux.SQL.Add('select sum(cajas*(porcentaje/100)) from lotes_pesadas_tmp l,mp_compuestas m where l.mprima=m.idmpc and l.ide=m.idempresa and puesto='+tidbascula+'');
       qaux.Open;
     end else
     begin
       qaux.Close;
       qaux.SQL.Clear;
       qaux.SQL.Add('select sum(cajas) from lotes_pesadas_tmp where puesto='+tidbascula);
       qaux.Open;
     end;
     v_bultos:=qaux.Fields[0].Asinteger;
     //////////////////////// INSERTO LOS MATERIALES DE LAS CAJAS SEGUN EL FORMATO Y EL PALET
    qaux.Close;
    qaux.sql.clear;
    qaux.sql.Add('delete from ea_materiales_tmp where puesto='+tidbascula+' and ide='+v_ide+' and idea='+v_id+' and idea2='+v_idea);
    qaux.execsql;
    insertarmaterialestmp(qinsertarmaterialestmp,strtoint(v_id),strtoint(v_idea),strtoint(tidbascula),dm.qpesadasnum_palets.asinteger,strtoint(v_ide),dm.qpesadastmpid_palet.asstring,1.0);
{
    qaux.Close;
    qaux.SQL.Clear;
    qaux.SQL.Add('insert into ea_materiales_tmp ');
    qaux.SQL.Add('select idempresa,'+v_id+' as idea,'+v_idea+' as idea2,idarticulof,sum(cantidadtotal) as cantidadtotal,sum(pesototal) as pesototal,null,sum(preciototal) as preciototal,0 as recuperado,null as identrada,'+tidbascula+' as puesto 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,'+tidbascula+' as puesto ');
    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_tmp lp,articulos_almacen aa where aa.ide=lp.ide and aa.codigo=lp.id_envase ');
    qaux.SQL.Add(' and lp.ide='+v_ide+' and lp.idea='+v_id+' and lp.idea2='+v_idea+' and puesto='+tidbascula+' 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) as cantidadtotal,(ac.peso*lp.cajas) as pesototal,(ac.coste*lp.cajas) as preciototal,'+tidbascula+' as puesto 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_tmp lp, ');
    qaux.SQL.Add(' configuraciones aa where aa.ide=lp.ide and aa.id=lp.id_formato and lp.ide='+v_ide+' and lp.idea='+v_id+' and lp.idea='+v_idea+' and puesto='+tidbascula+' 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*'+inttostr(dm.qpesadasnum_palets.Asinteger*v_palets)+') as cantidadtotal,(ac.peso*'+inttostr(dm.qpesadasnum_palets.Asinteger*v_palets)+') as pesototal,(ac.coste*'+dm.qpesadasnum_palets.AsString+') as preciototal,'+tidbascula+' as puesto');
    qaux.SQL.Add(' FROM articulos_componentes ac where ac.idempresa='+v_ide+' and ac.idarticuloalmacen=(select id from articulos_almacen where codigo='+''''+dm.qpesadasid_palet.AsString+''''+')');
    qaux.SQL.Add(' ) as ea_materiales_tmp group by idarticulof ');
    qaux.execsql;
}
    qaux.sql.clear;
    qaux.sql.Add('select sum(pesoneto_teorico),sum(cajas),sum(pesoneto_real) from lotes_pesadas_tmp where idea='+v_id+' and idea2='+v_idea+' and puesto='+tidbascula);
    qaux.open;

    v_bultos:=qaux.Fields[1].asinteger;
    v_pesoventa:=qaux.Fields[0].AsFloat;
    v_pesoneto:=qaux.Fields[2].AsFloat;
    if v_bultos=0 then v_pesomedio:=0 else v_pesomedio:=v_pesoneto/v_bultos;
    ////////////////////////
    qaux.sql.clear;
    qaux.sql.Add('select sum(peso) from ea_materiales_tmp where ide='+v_ide+' and idea='+v_id+' and idea2='+v_idea+' and puesto='+tidbascula);
    qaux.open;
    v_tara:=qaux.Fields[0].AsFloat;
    v_pesobruto:=v_tara+v_pesoneto;
    vtara:=floattostr(v_tara);
    vtara:= StringReplace(vtara, ',', '.',[rfReplaceAll, rfIgnoreCase]);
    vneto:=floattostr(v_pesoneto);
    vneto:= StringReplace(vneto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
    vbruto:=floattostr(v_pesobruto);
    vbruto:= StringReplace(vbruto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
    vventa:=floattostr(v_pesoventa);
    vventa:= StringReplace(vventa, ',', '.',[rfReplaceAll, rfIgnoreCase]);
    vpesomedio:=floattostr(v_pesomedio);
    vpesomedio:= StringReplace(vpesomedio, ',', '.',[rfReplaceAll, rfIgnoreCase]);

    qaux.close;
    qaux.SQL.Clear;
    qaux.SQL.Add('update ea_pesadas_tmp set resto_cajas='+inttostr(v_bultos)+',num_envases='+inttostr(v_bultos)+',peso_medio='+vpesomedio+',peso_bruto='+vbruto+',tara='+vtara+',peso_neto='+vneto+',peso_neto_teorico='+vventa+',iddestino='+qdestinosid.AsString+',destino='+''''+qdestinosnombre.AsString+''''+' where idempresa='+v_ide+' and id='+v_id+' and idea='+v_idea);
    qaux.ExecSQL;
    dm.qpesadastmp.close;
    dm.qpesadastmp.Open;

   end;
   tbultos.Text:=inttostr(dm.qpesadaslotesresto_cajas.Asinteger-strtoint(tbultos.Text));
   qpesadaslotesmov.Close;
   qpesadaslotesmov.ParamByName('PUESTO').Asstring:=tidbascula;
   qpesadaslotesmov.open;
end;

procedure Tgeneral.bttodoslotesClick(Sender: TObject);
var cajas,newcajas,newpalets:integer;
    pneto,newpneto,preal,newpreal,tara:real;
    v_ide,v_id,v_idea,vneto,vbruto,vventa,vpesomedio,vtara,vbultos:string;
    v_bultos:integer;
    v_tara,v_taraanterior,v_pesoneto,v_pesobruto,v_pesoventa,v_pesomedio:real;
begin
   v_ide:=dm.qpesadasidempresa.Asstring;
   v_id:=dm.qpesadasid.Asstring;
   v_idea:=dm.qpesadasidea.Asstring;

   qaux.Close;
   qaux.SQL.Clear;
   qaux.SQL.Add('delete from lotes_pesadas_tmp where puesto='+tidbascula);
   qaux.ExecSQL;
   qaux.Close;
   qaux.SQL.Clear;
   qaux.SQL.Add('delete from ea_materiales_tmp where puesto='+tidbascula);
   qaux.ExecSQL;
   qaux.Close;
   qaux.SQL.Clear;
   qaux.SQL.Add('insert into lotes_pesadas_tmp '+dm.qpesadaslotes.SQL.Text);
   qaux.ExecSQL;
   qaux.Close;
   qaux.SQL.Clear;
   qaux.SQL.Add('update lotes_pesadas_tmp set  puesto='+tidbascula+' where idea='+v_id+' and idea2='+v_idea+' and ide='+v_ide);
   qaux.ExecSQL;
   qpesadaslotesmov.close;
   qpesadaslotesmov.open;
   qaux.Close;
   qaux.SQL.Clear;
   qaux.SQL.Add('select * from lotes_pesadas_tmp where  puesto='+tidbascula);
   qaux.Open;
   if qaux.RecordCount>0 then
   begin
     qaux.Close;
     qaux.SQL.Clear;
     qaux.SQL.Add('select sum(pesoneto_teorico),sum(pesoneto_real) from lotes_pesadas_tmp where  puesto='+tidbascula);
     qaux.Open;
     v_pesoneto:=qaux.Fields[0].AsFloat;
     v_pesoventa:=qaux.Fields[1].AsFloat;
     qaux.SQL.Clear;
     qaux.SQL.Add('select compuesto from materias_primas where id='+''''+dm.qpesadastmpmprima.asstring+'''');
     qaux.Open;
     if qaux.Fields[0].Asinteger=1 then
     begin
       qaux.Close;
       qaux.SQL.Clear;
       qaux.SQL.Add('select sum(cajas*(porcentaje/100)) from lotes_pesadas_tmp l,mp_compuestas m where l.mprima=m.idmpc and l.ide=m.idempresa');
       qaux.Open;
     end else
     begin
       qaux.Close;
       qaux.SQL.Clear;
       qaux.SQL.Add('select sum(cajas) from lotes_pesadas_tmp');
       qaux.Open;
     end;

    v_bultos:=qaux.Fields[0].Asinteger;
    qaux.Close;
    qaux.sql.clear;
    qaux.sql.Add('delete from ea_materiales_tmp where ide='+v_ide+' and idea='+v_id+' and idea2='+v_idea+' and puesto='+tidbascula);
    qaux.execsql;
    insertarmaterialestmp(qinsertarmaterialestmp,strtoint(v_id),strtoint(v_idea),strtoint(tidbascula),dm.qpesadasnum_palets.asinteger,strtoint(v_ide),dm.qpesadasid_palet.asstring,1.0);
{    qaux.Close;
    qaux.SQL.Clear;

    qaux.SQL.Add('insert into ea_materiales_tmp ');
    qaux.SQL.Add('select idempresa,'+v_id+' as idea,'+v_idea+' as idea2,idarticulof,sum(cantidadtotal) as cantidadtotal,sum(pesototal) as pesototal,null,sum(preciototal) as preciototal,0 as recuperado,null as identrada,'+tidbascula+' as puesto 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_tmp lp,articulos_almacen aa where aa.ide=lp.ide and aa.codigo=lp.id_envase ');
    qaux.SQL.Add(' and lp.ide='+v_ide+' and lp.idea='+v_id+' and lp.idea2='+v_idea+' and  puesto='+tidbascula+' 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) as cantidadtotal,(ac.cantidad*ac.peso*lp.cajas) as pesototal,(ac.cantidad*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_tmp lp, ');
    qaux.SQL.Add(' configuraciones aa where aa.ide=lp.ide and aa.id=lp.id_formato and lp.ide='+v_ide+' and lp.idea='+v_id+' and lp.idea2=+'+v_idea+' and  puesto='+tidbascula+' 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*'+dm.qpesadasnum_palets.AsString+') as cantidadtotal,(ac.peso*'+dm.qpesadasnum_palets.AsString+') as pesototal,(ac.coste*'+dm.qpesadasnum_palets.AsString+') as preciototal');
    qaux.SQL.Add(' FROM articulos_componentes ac where ac.idempresa='+v_ide+' and ac.idarticuloalmacen=(select id from articulos_almacen where codigo='+''''+dm.qpesadasid_palet.AsString+''''+')');
    qaux.SQL.Add(' ) as ea_materiales_tmp group by idarticulof ');
    qaux.execsql;
}
    qaux.sql.clear;
    qaux.sql.Add('select sum(pesoneto_teorico),sum(cajas),sum(pesoneto_real) from lotes_pesadas_tmp where idea='+v_id+' and idea2='+v_idea+' and  puesto='+tidbascula);
    qaux.open;
    v_bultos:=qaux.Fields[1].asinteger;
    v_pesoventa:=qaux.Fields[0].AsFloat;
    v_pesoneto:=qaux.Fields[2].AsFloat;
    if v_bultos=0 then v_pesomedio:=0 else v_pesomedio:=v_pesoneto/v_bultos;
    ////////////////////////
    qaux.sql.clear;
    qaux.sql.Add('select sum(peso) from ea_materiales_tmp where ide='+v_ide+' and idea='+v_id+' and idea2='+v_idea);
    qaux.open;
    v_tara:=qaux.Fields[0].AsFloat;
    v_pesobruto:=v_tara+v_pesoneto;
    vtara:=floattostr(v_tara);
    vtara:= StringReplace(vtara, ',', '.',[rfReplaceAll, rfIgnoreCase]);
    vneto:=floattostr(v_pesoneto);
    vneto:= StringReplace(vneto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
    vbruto:=floattostr(v_pesobruto);
    vbruto:= StringReplace(vbruto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
    vventa:=floattostr(v_pesoventa);
    vventa:= StringReplace(vventa, ',', '.',[rfReplaceAll, rfIgnoreCase]);
    vpesomedio:=floattostr(v_pesomedio);
    vpesomedio:= StringReplace(vpesomedio, ',', '.',[rfReplaceAll, rfIgnoreCase]);

    qaux.close;
    qaux.SQL.Clear;
    qaux.SQL.Add('update ea_pesadas_tmp set resto_cajas='+inttostr(v_bultos)+',num_envases='+inttostr(v_bultos)+',peso_medio='+vpesomedio+',peso_bruto='+vbruto+',tara='+vtara+',peso_neto='+vneto+',peso_neto_teorico='+vventa+',idea='+v_idea+',iddestino='+qdestinosid.AsString+',destino='+''''+qdestinosnombre.AsString+''''+' where idempresa='+v_ide+' and id='+v_id+' and idea='+v_idea+' and  puesto='+tidbascula);
    qaux.ExecSQL;
    dm.qpesadastmp.Refresh;
   end;

end;

procedure Tgeneral.Button22Click(Sender: TObject);
var cajas,newcajas,newpalets:integer;
    pneto,newpneto,preal,newpreal,tara:real;
begin
   qaux.Close;
   qaux.SQL.Clear;
   qaux.SQL.Add('delete from lotes_pesadas_tmp where id='+qpesadaslotesmovid.AsString);
   qaux.ExecSQL;
   qaux.Close;
   qpesadaslotesmov.Refresh;
     qaux.Close;
     qaux.SQL.Clear;
     qaux.SQL.Add('select sum(pesoneto_teorico) from lotes_pesadas_tmp');
     qaux.Open;
     newpneto:=qaux.Fields[0].AsFloat;
     qaux.Close;
     qaux.SQL.Clear;
     qaux.SQL.Add('select sum(pesoneto_real) from lotes_pesadas_tmp');
     qaux.Open;
     newpreal:=qaux.Fields[0].AsFloat;
     qaux.SQL.Clear;
     qaux.SQL.Add('select compuesto from materias_primas where id='+''''+dm.qpesadastmpmprima.asstring+'''');
     qaux.Open;
     if qaux.Fields[0].Asinteger=1 then
     begin
       qaux.Close;
       qaux.SQL.Clear;
       qaux.SQL.Add('select sum(cajas*(porcentaje/100)) from lotes_pesadas_tmp l,mp_compuestas m where l.mprima=m.idmpc and l.ide=m.idempresa');
       qaux.Open;
     end else
     begin
       qaux.Close;
       qaux.SQL.Clear;
       qaux.SQL.Add('select sum(cajas) from lotes_pesadas_tmp');
       qaux.Open;
     end;

     newcajas:=qaux.Fields[0].Asinteger;
     qaux.Close;
     qaux.SQL.Clear;
     qaux.SQL.Add('select tara from articulos_almacen where codigo='+''''+dm.qpesadastmpid_envase.asstring+'''');
     qaux.Open;
     tara:=qaux.Fields[0].Asfloat*newcajas;
     qaux.Close;
     qaux.SQL.Clear;
     qaux.SQL.Add('select tara from articulos_almacen where codigo='+''''+dm.qpesadastmpid_palet.asstring+'''');
     qaux.Open;
     tara:=tara+(qaux.Fields[0].AsFloat*dm.qpesadastmpnum_palets.AsInteger);

     qaux.Close;
     qaux.SQL.Clear;
     qaux.SQL.Add('update ea_pesadas_tmp set num_envases='+inttostr(newcajas)+',resto_cajas='+inttostr(newcajas)+',peso_neto='+stringReplace(floattostr(newpreal), ',', '.',[rfReplaceAll, rfIgnoreCase])+',peso_neto_teorico='+stringReplace(floattostr(newpneto), ',', '.',[rfReplaceAll, rfIgnoreCase])+',tara='+stringReplace(floattostr(tara), ',', '.',[rfReplaceAll, rfIgnoreCase])+',peso_bruto='+stringReplace(floattostr(newpreal+tara), ',', '.',[rfReplaceAll, rfIgnoreCase]));
     qaux.ExecSQL;
{     dm.qpesadastmp.Close;
     dm.qpesadastmp.Open;
     dm.qpesadastmp.Edit;
     dm.qpesadastmpnum_envases.value:=newcajas;
     dm.qpesadastmpresto_cajas.value:=newcajas;
     dm.qpesadastmppeso_neto.value:=newpreal;
     dm.qpesadastmppeso_neto_teorico.value:=newpneto;
     dm.qpesadastmptara.value:=tara;
     dm.qpesadastmppeso_bruto.Value:=tara+newpreal;
     dm.qpesadastmp.Post;}
     dm.qpesadastmp.Refresh;

end;

procedure Tgeneral.Button2Click(Sender: TObject);
var vsgg,vsdop,vsigp,vsifs,vsbrc:string;
begin
    qinfpartidas.Close;
    qinfpartidas.SQL.Clear;
    qinfpartidas.SQL.Add('select l.id as partida,p.id,p.fecha,pc.nombre,mp.descripcion,ea.matricula,eap.id,eap.num_palets,eap.id_envase,eap.num_envases,eap.peso_bruto,eap.tara,eap.tara0,eap.peso_neto,eap.peso_medio,eap.temperatura,eap.cea,eap.destino,eap.lote');
    qinfpartidas.SQL.Add(',eap.idempresa,eap.idea,l.trazabilidad,ea.hora,l.productor,l.sgg,l.sdop,l.sigp,l.sifs,l.sbrc from partidas p, parcelas pc,materias_primas mp, entradas_almacen ea,ea_pesadas eap, lotes l ');
    qinfpartidas.SQL.Add('where eap.lote=l.codigo and p.id_parcela=pc.codpar and p.id_mprimas=mp.id and p.id=ea.partida and ea.id=eap.idea and ');
    qinfpartidas.SQL.Add('eap.id='+dm.qpesadasentradasid.asstring);
    qinfpartidas.SQL.Add(' order by eap.hora');
    qinfpartidas.open;
    informedb.Datasource:=dsqinfpartidas;
    informes.Report.Clear;
    informes.LoadFromFile('c:\agrigest\informes\etiquetaentrada.fr3');

    if qinfpartidassgg.AsString='' then vsgg:='' else vsgg:='GLOBALGAP' + qinfpartidassgg.Asstring;
    if qinfpartidassdop.AsString='' then vsdop:='' else vsdop:='DOP' + qinfpartidassdop.Asstring;
    if qinfpartidassigp.AsString='' then vsigp:='' else vsigp:='IGP' + qinfpartidassigp.Asstring;
    if qinfpartidassifs.AsString='' then vsifs:='' else vsifs:='IFS' + qinfpartidassifs.Asstring;
    if qinfpartidassbrc.AsString='' then vsbrc:='' else vsbrc:='BRC' + qinfpartidassbrc.Asstring;

    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('PARTIDA: '+qpartidasid.asstring+ ' FECHA: '+datetostr(tfecha.Date)+' PARCELA: '+qinfpartidasnombre.AsString+' VARIEDAD: '+qinfpartidasdescripcion.AsString);
//    informes.PrintOptions.Printer.Empty
//    informes.Report.ShowReport();
    informes.Report.PrepareReport(true);
//    informes.PrintOptions.ShowDialog:=false;
    informes.Report.Print;
end;

procedure Tgeneral.Button4Click(Sender: TObject);
begin

    tid.Clear;
    ExitProcess(0);
end;

procedure Tgeneral.btnuevoloteClick(Sender: TObject);
var multiplicador,pesoteoricocaja,pesoteorico,pesoreal,pesobruto:real;
    tempid,escompuesta_es,num_envases,palets,videa,videa2:integer;
    tara,bruto,neto,venta:real;
    tmultiplicador,tbultos,tneto,tventa,tide,tpesoteoricocaja,tidea,tidea2:string;
begin

       multiplicador:=0;
       pesoteoricocaja:=0;
       pesoteorico:=0;
       pesoreal:=0;
       tempid:=0;
       tide:=dm.qlotesidempresa.asstring;
       if esmultiple=1 then pesobruto:=1 else pesobruto:=strtofloat(edpeso_es.text);
       if (pesobruto>=1) then
       begin
             escompuesta_es:=qmprimascompuesto.AsInteger;
             num_envases:=0;
             if escompuesta_es=1 then
             begin
                 if combolotes_es.ListSource=dm.dsqlotes then
                 begin
                     dm.qaux.sql.clear;
                     dm.qaux.sql.Add('select porcentaje from mp_compuestas where idmp='+''''+qmprimasid.asstring+''''+' and idmpc='+''''+dm.qlotesmprima.asstring+'''');
                     dm.qaux.open;
                     multiplicador:=dm.qaux.Fields[0].AsFloat/100;
                 end;
                 if combolotes_es.ListSource=dm.dsqlotessalidas then
                 begin
                     dm.qaux.sql.clear;
                     dm.qaux.sql.Add('select porcentaje from mp_compuestas where idmp='+''''+qmprimasid.asstring+''''+' and idmpc='+''''+dm.qlotessalidasmprima.asstring+'''');
                     dm.qaux.open;
                     multiplicador:=dm.qaux.Fields[0].AsFloat/100;
                 end;
             end;
             if escompuesta=0 then
             begin
                 multiplicador:=1;
             end;

             tmultiplicador:=floattostr(multiplicador);
             tmultiplicador:=StringReplace(tmultiplicador, ',', '.',[rfReplaceAll, rfIgnoreCase]);


         if esentrada=1 then
         begin
             num_envases:=strtoint(lenvases_es.text);
             videa:=-1000;
             videa2:=-1000;
             tidea:=inttostr(videa);
             tidea2:=inttostr(videa2);
             qpesadaslotesentradas.sql.Clear;
             qpesadaslotesentradas.SQL.Add('select * from lotes_pesadas_tmp where idea='+tidea+' and idea2='+tidea2+' and puesto='+tidbascula);
             qpesadaslotesentradas.Open;
             qpesadaslotesentradas.Append;
             qpesadaslotesentradaside.Value:=strtoint(tide);//dm.qlotesidempresa.asinteger;
             qpesadaslotesentradasidea.Value:=videa;//dm.tpesadasid.AsInteger;
             qpesadaslotesentradasidea2.Value:=videa2;
             qpesadaslotesentradaslote.value:=dm.qlotescodigo.asinteger;
             qpesadaslotesentradasmprima.Value:=dm.qlotesMPRIMA.AsString;
             qpesadaslotesentradascajas.value:=num_envases;
             qpesadaslotesentradasresto_cajas.value:=num_envases;
             qpesadaslotesentradaspesoneto_teorico.Value:=0;//pesoteorico;
             qpesadaslotesentradaspesoneto_real.Value:=0;//pesoreal;
             qpesadaslotesentradases_entrada.value:=esentrada;
             qpesadaslotesentradasid_envase.value:=qcajasid.AsString;
             qpesadaslotesentradasid_formato.value:=qformatoscajasid.Asinteger;
             qpesadaslotesentradasdesc_envase.value:=qcajasdescripcion.AsString;
             qpesadaslotesentradasdesc_formato.value:=qformatoscajasdescripcion_1.AsString;
             qpesadaslotesentradascalibrecalidad.value:=qcalibresid.Asinteger;
             qpesadaslotesentradasdesc_calibre.value:=qcalibresdescripcion.AsString;
             qpesadaslotesentradaspuesto.value:=strtoint(tidbascula);
             qpesadaslotesentradas.Post;
             qpesadaslotesentradas.refresh;
{    if (select sum(cajas) from lotes_pesadas where ide=new.idempresa and idea=new.id and idea2=new.idea)=new.num_envases then
    begin
       update lotes_pesadas set pesoneto_teorico=cajas*(new.peso_neto_teorico/new.num_envases),pesoneto_real=cajas*(new.peso_neto/new.num_envases) where ide=new.idempresa and idea=new.id and idea2=new.idea;
    end;
    end if;
    if (select sum(cajas)/2 from lotes_pesadas where ide=new.idempresa and idea=new.id and idea2=new.idea)=new.num_envases then
    begin
       update lotes_pesadas set pesoneto_teorico=cajas*((new.peso_neto_teorico/new.num_envases)/2),pesoneto_real=cajas*((new.peso_neto/new.num_envases)/2) where ide=new.idempresa and idea=new.id and idea2=new.idea;
    end;
    end if;
 }




      //////////////////////// INSERTO LOS MATERIALES DE LAS CAJAS SEGUN EL FORMATO Y EL PALET
             qaux.Close;
             qaux.sql.clear;
             qaux.sql.Add('delete from ea_materiales_tmp where ide='+dm.qlotesidempresa.asstring+' and puesto='+tidbascula);
             qaux.execsql;

// para insertar materiales necesito el puesto y numero de envases y si es envase o presentacion
//insert into ea_materiales_tmp
//SELECT EMPRESA,-1000+1 as idea,-1000+1 as idea2,componente,cantidad*1 as cantidadtotal,peso*1 as pesototal,null,coste*1 as preciototal,0 as recuperado,null as identrada,1 as puesto from v_componentesenvases where configuracion=3 and tipo='ENVASE';

// inserto los materiales de los ids
    insertarmaterialestmp(qinsertarmaterialestmp,-1000,-1000,strtoint(tidbascula),strtoint(edpalets_es.text),strtoint(tide),qpalets1codigo.asstring,multiplicador);
{             qinsertarmaterialestmp.Prepare;
             qinsertarmaterialestmp.ParamByName('IDEA').AsInteger:=-1000;
             qinsertarmaterialestmp.ParamByName('IDEA2').AsInteger:=-1000;
             qinsertarmaterialestmp.ParamByName('PUESTO').AsInteger:=STRTOINT(TIDBASCULA);
             qinsertarmaterialestmp.ParamByName('NUMPALETS').AsInteger:=strtoint(edpalets_es.text);
             qinsertarmaterialestmp.ParamByName('IDPALET').AsInteger:=qpalets1id.asinteger;
             qinsertarmaterialestmp.ParamByName('MULTIPLICADOR').Asstring:=tmultiplicador;
             qinsertarmaterialestmp.ParamByName('EMPRESA').Asinteger:=strtoint(tide);

             qinsertarmaterialestmp.ExecSQL;
}
 {            if qpesadaslotesentradas.RecordCount>0 then
             begin
               if combopalets_es.keyvalue<>null then
               begin
                  qaux.Close;
                  qaux.SQL.Clear;
                  qaux.SQL.Add('insert into ea_materiales_tmp ');
                  qaux.SQL.Add('select idempresa,-1000-'+tidbascula+' as idea,-1000-'+tidbascula+' as idea2,idarticulof,sum(cantidadtotal) as cantidadtotal,sum(pesototal) as pesototal,null,sum(preciototal) as preciototal,0 as recuperado,null as identrada,'+tidbascula+' as puesto 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_tmp lp,articulos_almacen aa where aa.ide=lp.ide and aa.codigo=lp.id_envase ');
                  qaux.SQL.Add(' and lp.ide='+qpesadaslotesentradaside.AsString+' and lp.idea=-1000-'+tidbascula+' and lp.idea2=-1000-'+tidbascula+' 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) 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_tmp lp, ');
                  qaux.SQL.Add(' configuraciones aa where aa.ide=lp.ide and aa.id=lp.id_formato and lp.ide='+qpesadaslotesentradaside.AsString+' and lp.idea=-1000-'+tidbascula+' and lp.idea2=-1000-'+tidbascula+' group by lp.id_formato) 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*'+edpalets_es.Text+') as cantidadtotal,(ac.peso*'+edpalets_es.Text+') as pesototal,(ac.coste*'+edpalets_es.Text+') as preciototal');
                  qaux.SQL.Add(' FROM articulos_componentes ac where ac.idempresa='+qpesadaslotesentradaside.AsString+' and ac.idarticuloalmacen='+qpalets1id.asstring);
                  qaux.SQL.Add(' ) as ea_materiales_tmp group by idarticulof ');
                  qaux.execsql;
               end;
             end;}
             qaux.sql.clear;
             qaux.sql.Add('select sum(cajas) from lotes_pesadas_tmp where idea=-1000 and idea2=-1000 and puesto='+tidbascula);
             qaux.open;
             lbultos.text:=qaux.Fields[0].asstring;


      ////////////////////////

             if edpeso_es.Text='0' then edpeso_es.SetFocus;
             qaux.sql.clear;
             qaux.sql.Add('select sum(peso) from ea_materiales_tmp where ide='+dm.qlotesidempresa.asstring+' and idea=-1000 and idea2=-1000 and puesto='+tidbascula);
             qaux.open;
             ltara.Text:=floattostr(qaux.Fields[0].AsFloat);
             lneto.text:=floattostr(strtofloat(edpeso_es.Text)-strtofloat(ltara.Text)-strtofloat(ltaraanterior.Text));
             tbultos:=StringReplace(lbultos.text, '.', ',',[rfReplaceAll, rfIgnoreCase]);lbultos.Text;
             bruto:=strtofloat(edpeso_es.text);
             tara:=strtofloat(ltara.text);
             neto:=strtofloat(lneto.text);
             tneto:= StringReplace(lneto.text, ',', '.',[rfReplaceAll, rfIgnoreCase]);
             if tbultos<>'0' then
             begin
                qaux.SQL.Clear;
                qaux.SQL.Add('update lotes_pesadas_tmp set pesoneto_real=cajas/'+tbultos+'*'+tneto+' where idea=-1000 and idea2=-1000 and puesto='+tidbascula);
                qaux.ExecSQL;
             end;
             if tbultos<>'0' then
             begin
                if qcajasfacturar_pesofijo.AsInteger=0 then
                begin
                    qaux.SQL.Clear;
                    qaux.SQL.Add('update lotes_pesadas_tmp set pesoneto_teorico=cajas/'+tbultos+'*'+tneto+' where idea=-1000 and idea2=-1000 and puesto='+tidbascula);
                    qaux.ExecSQL;
                end else
                begin
                    pesoteoricocaja:=qcajaspeso_venta.AsFloat;
                    tpesoteoricocaja:=StringReplace(floattostr(pesoteoricocaja), ',', '.',[rfReplaceAll, rfIgnoreCase]);
                    qaux.SQL.Clear;
                    qaux.SQL.Add('update lotes_pesadas_tmp set pesoneto_teorico=cajas*'+tpesoteoricocaja+' where idea=-1000 and idea2=-1000 and puesto='+tidbascula);
                    qaux.ExecSQL;

                end;
              end;
              qpesadaslotesentradas.refresh;
              qaux.sql.clear;
              qaux.sql.Add('select sum(pesoneto_teorico),sum(cajas) from lotes_pesadas_tmp where idea=-1000 and idea2=-1000 and puesto='+tidbascula);
              qaux.open;
              lbultos.text:=inttostr(trunc(qaux.Fields[1].asinteger*multiplicador));
              lventa_es.Text:=floattostr(qaux.Fields[0].AsFloat);


         end;
         if esentrada=0 then
         begin
             if qpalets2facturar_pesofijo.AsInteger=0 then
             begin
                 pesoteoricocaja:=0;//dm.tpesadaspeso_neto.AsFloat/dm.tpesadasnum_envases.AsInteger;
                 tpesoteoricocaja:=floattostr(pesoteoricocaja);
                 tpesoteoricocaja:=StringReplace(tpesoteoricocaja, ',', '.',[rfReplaceAll, rfIgnoreCase]);
             end;
             if qpalets2facturar_pesofijo.asInteger=1 then
             begin
                 pesoteoricocaja:=qpalets2peso_venta.asfloat;
                 tpesoteoricocaja:=floattostr(pesoteoricocaja);
                 tpesoteoricocaja:=StringReplace(tpesoteoricocaja, ',', '.',[rfReplaceAll, rfIgnoreCase]);

             end;
////
             if esmultiple=1 then num_envases:=strtoint(lporpalet.text) else num_envases:=strtoint(lenvases_es.text);
             pesoteorico:=num_envases*pesoteoricocaja*multiplicador;
             pesoreal:=num_envases*pesoreal*multiplicador;
             qpesadaslotessalidas.sql.Clear;
             qpesadaslotessalidas.SQL.Add('select * from lotes_pesadas_tmp where idea=-2000 and idea2=0 and puesto='+tidbascula);
             qpesadaslotessalidas.Open;
             qpesadaslotessalidas.Append;
             qpesadaslotessalidaside.Value:=dm.qlotessalidasidempresa.asinteger;
             qpesadaslotessalidasidea.Value:=-2000;//dm.tpesadasid.AsInteger;
             qpesadaslotessalidasidea2.Value:=0;
             qpesadaslotessalidaslote.value:=dm.qlotessalidaslote.asinteger;
             qpesadaslotessalidasmprima.Value:=dm.qlotessalidasMPRIMA.AsString;
             qpesadaslotessalidascajas.value:=num_envases;
             qpesadaslotessalidasresto_cajas.value:=num_envases;
             qpesadaslotessalidaspesoneto_teorico.Value:=pesoteorico;
             qpesadaslotessalidaspesoneto_real.Value:=pesoreal;
             qpesadaslotessalidases_entrada.value:=esentrada;
             qpesadaslotessalidasid_envase.value:=qpalets2id.AsString;
             qpesadaslotessalidasid_formato.value:=qformatoscajasid.Asinteger;
             qpesadaslotessalidasdesc_envase.value:=qpalets2descripcion.AsString;
             qpesadaslotessalidasdesc_formato.value:=qformatoscajasdescripcion_1.AsString;
             qpesadaslotessalidascalibrecalidad.value:=qcalibresid.Asinteger;
             qpesadaslotessalidasdesc_calibre.value:=qcalibresdescripcion.AsString;
             qpesadaslotessalidaspuesto.Value:=strtoint(tidbascula);
             qpesadaslotessalidas.Post;
      //////////////////////// INSERTO LOS MATERIALES DE LAS CAJAS SEGUN EL FORMATO
             qaux.Close;
             qaux.sql.clear;
             qaux.sql.Add('delete from ea_materiales_tmp where ide='+dm.qlotessalidasidempresa.asstring+' and idea=-2000 and idea2=0 and puesto='+tidbascula);
             qaux.execsql;
             tmultiplicador:=StringReplace(floattostr(multiplicador), ',', '.',[rfReplaceAll, rfIgnoreCase]);
             tide:=dm.qlotessalidasidempresa.asstring;
             if qpesadaslotessalidas.RecordCount>0 then
             begin
               if combopalets_es.keyvalue<>null then
               begin
      // inserto los materiales de los palets
                   if esmultiple=1 then palets:=1 else palets:=strtoint(edpalets_es.Text);
                   insertarmaterialestmp(qinsertarmaterialestmp,-2000,0,strtoint(tidbascula),palets,strtoint(tide),qpalets1codigo.asstring,multiplicador);

                   {
                   qinsertarmaterialestmp.Prepare;
                   qinsertarmaterialestmp.ParamByName('ID').AsInteger:=-2000;
                   qinsertarmaterialestmp.ParamByName('IDEA').AsInteger:=0;
                   qinsertarmaterialestmp.ParamByName('PUESTO').AsInteger:=STRTOINT(TIDBASCULA);
                   qinsertarmaterialestmp.ParamByName('ENVASES').AsInteger:=palets;
                   qinsertarmaterialestmp.ParamByName('IDENVASE').AsInteger:=qpalets1id.asinteger;
                   qinsertarmaterialestmp.ParamByName('TIPO').Asstring:='ENVASE';
                   qinsertarmaterialestmp.ExecSQL;
                   qpesadaslotessalidas.first;
                   while not qpesadaslotessalidas.Eof do
                   begin
                     qaux.Close;
                     qaux.sql.clear;
                     qaux.sql.Add('select id from articulos_almacen where codigo='+''''+qpesadaslotessalidasid_envase.AsString+'''');
                     qaux.open;
        // inserto los materiales de los envases
                     qinsertarmaterialestmp.Prepare;
                     qinsertarmaterialestmp.ParamByName('ID').AsInteger:=-2000;
                     qinsertarmaterialestmp.ParamByName('IDEA').AsInteger:=0;
                     qinsertarmaterialestmp.ParamByName('MULTIPLICADOR').Asfloat:=multiplicador;
                     qinsertarmaterialestmp.ParamByName('PUESTO').AsInteger:=STRTOINT(TIDBASCULA);
                     qinsertarmaterialestmp.ParamByName('ENVASES').AsInteger:=qpesadaslotessalidascajas.asinteger;
                     qinsertarmaterialestmp.ParamByName('IDENVASE').AsInteger:=qaux.Fields[0].AsInteger;
                     qinsertarmaterialestmp.ParamByName('TIPO').Asstring:='ENVASE';
                     qinsertarmaterialestmp.ExecSQL;
        // inserto los materiales de los formatos
                     qinsertarmaterialestmp.Prepare;
                     qinsertarmaterialestmp.ParamByName('ID').AsInteger:=-2000;
                     qinsertarmaterialestmp.ParamByName('IDEA').AsInteger:=0;
                     qinsertarmaterialestmp.ParamByName('MULTIPLICADOR').Asfloat:=multiplicador;
                     qinsertarmaterialestmp.ParamByName('PUESTO').AsInteger:=STRTOINT(TIDBASCULA);
                     qinsertarmaterialestmp.ParamByName('ENVASES').AsInteger:=qpesadaslotessalidascajas.AsInteger;
                     qinsertarmaterialestmp.ParamByName('IDENVASE').AsInteger:=qpesadaslotessalidasid_formato.asinteger;
                     qinsertarmaterialestmp.ParamByName('TIPO').Asstring:='PRESENTACION';
                     qinsertarmaterialestmp.ExecSQL;
                     qpesadaslotessalidas.Next
                   end;
}
                  {qaux.Close;
                  qaux.SQL.Clear;
                  qaux.SQL.Add('insert into ea_materiales_tmp ');
                  qaux.SQL.Add('select idempresa,-2000 as idea,0 as idea2,idarticulof,sum(cantidadtotal) as cantidadtotal,sum(pesototal) as pesototal,null,sum(preciototal) as preciototal,0 as recuperado,'+tidbascula+' as puesto 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_tmp lp,articulos_almacen aa where aa.ide=lp.ide and aa.codigo=lp.id_envase ');
                  qaux.SQL.Add(' and lp.ide='+qpesadaslotessalidaside.AsString+' and lp.idea=-2000 and lp.idea2=0 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_tmp lp, ');
                  qaux.SQL.Add(' configuraciones aa where aa.ide=lp.ide and aa.id=lp.id_formato and lp.ide='+qpesadaslotessalidaside.AsString+' and lp.idea=-2000 and lp.idea2=0 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*'+edpalets_es.Text+') as cantidadtotal,(ac.peso*'+edpalets_es.Text+') as pesototal,(ac.coste*'+edpalets_es.Text+') as preciototal');
                  qaux.SQL.Add(' FROM articulos_componentes ac where ac.idempresa='+qpesadaslotessalidaside.AsString+' and ac.idarticuloalmacen='+qpalets1id.asstring);
                  qaux.SQL.Add(' ) as ea_materiales_tmp group by idarticulof ');
                  qaux.execsql;}
{                  if esmultiple=1 then palets:=1 else palets:=strtoint(edpalets_es.Text);

                  qinsertarmateriales.Prepare;
                  qinsertarmateriales.ParamByName('BASCULA').AsInteger:=strtoint(tidbascula);
                  qinsertarmateriales.ParamByName('MULTIPLICADOR').Asfloat:=multiplicador;
                  qinsertarmateriales.ParamByName('EMPRESA').AsInteger:=qpesadaslotessalidaside.AsInteger;
                  qinsertarmateriales.ParamByName('NUMPALETS').AsInteger:=palets;
                  qinsertarmateriales.ParamByName('IDPALET').Asstring:=qpalets1id.asstring;
                  qinsertarmateriales.ExecSQL; }

               end;
             end;
      ////////////////////////
                 qpesadaslotessalidas.refresh;

                 qaux.sql.clear;
                 qaux.sql.Add('select sum(cajas) from lotes_pesadas_tmp where idea=-2000 and idea2=0 and puesto='+tidbascula);
                 qaux.open;
                 lbultos.text:=inttostr(trunc(qaux.Fields[0].asinteger*multiplicador));
                 qaux.sql.clear;
                 qaux.sql.Add('select sum(peso) from ea_materiales_tmp where idea=-2000 and idea2=0 and puesto='+tidbascula);
                 qaux.open;
                 ltara.Text:=floattostr(qaux.Fields[0].AsFloat);
                 tara:=strtofloat(ltara.text);

                 if qpalets2facturar_pesofijo.AsInteger=0 then
                 begin
                     pesoteoricocaja:=0;//dm.tpesadaspeso_neto.AsFloat/dm.tpesadasnum_envases.AsInteger;
                 end;
                 if qpalets2facturar_pesofijo.asInteger=1 then
                 begin
                     pesoteoricocaja:=qpalets2peso_venta.asfloat;
                 end;
                 qaux.sql.clear;
                 qaux.sql.Add('select sum(pesoneto_teorico) from lotes_pesadas_tmp where idea=-2000 and idea2=0 and puesto='+tidbascula);
                 qaux.open;

                 lventa_es.Text:=floattostr(qaux.Fields[0].AsFloat);
                 tventa:=lventa_es.Text;
                 venta:=strtofloat(lventa_es.Text);
                 if esmultiple=1 then edpeso_es.text:=floattostr(tara+venta);
                 lneto.text:=floattostr(strtofloat(edpeso_es.Text)-strtofloat(ltara.Text)-strtofloat(ltaraanterior.Text));
                 tbultos:=StringReplace(lbultos.text, '.', ',',[rfReplaceAll, rfIgnoreCase]);
                 bruto:=strtofloat(edpeso_es.text);
                  tventa:=floattostr(venta);
                  neto:=strtofloat(lneto.text);
                  tneto:= StringReplace(lneto.text, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  tventa:=StringReplace(tventa, ',', '.',[rfReplaceAll, rfIgnoreCase]);
                  if tbultos<>'0' then
                  begin
                    if qpalets2facturar_pesofijo.AsInteger=1 then
                    begin
                         qaux.SQL.Clear;
                         qaux.SQL.Add('update lotes_pesadas_tmp set pesoneto_teorico='+tpesoteoricocaja+'*cajas*'+tmultiplicador+',pesoneto_real=('+tneto+'*'+tmultiplicador+'/'+tbultos+')*cajas where idea=-2000 and idea2=0 and puesto='+tidbascula);
                         qaux.ExecSQL;
                    end;
                  end;
                  if tbultos<>'0' then
                  begin
                    if qpalets2facturar_pesofijo.AsInteger=0 then
                    begin
                        qaux.SQL.Clear;
                        qaux.SQL.Add('update lotes_pesadas_tmp set pesoneto_teorico=('+tneto+'*'+tmultiplicador+'/'+tbultos+')*cajas,pesoneto_real=('+tneto+'*'+tmultiplicador+'/'+tbultos+')*cajas where idea=-2000 and idea2=0 and puesto='+tidbascula);
                        qaux.ExecSQL;
                    end;
                  end;
                 qaux.close;
                 qaux.sql.clear;
                 qaux.sql.Add('select sum(pesoneto_teorico),sum(cajas) from lotes_pesadas_tmp where idea=-2000 and idea2=0 and puesto='+tidbascula);
                 qaux.open;
                 lventa_es.Text:=floattostr(qaux.Fields[0].AsFloat);
                  qpesadaslotessalidas.refresh;
                  if edpeso_es.Text='0' then edpeso_es.SetFocus;
             end;
       end else edpeso_es.SetFocus;
end;

procedure Tgeneral.Button5Click(Sender: TObject);
begin
    tpartidas.Open;
    tpartidas.Append;

end;

procedure Tgeneral.Button6Click(Sender: TObject);
var vsgg,vsdop,vsigp,vsifs,vsbrc:string;
begin

    dm.qetiquetas.Close;
    dm.qetiquetas.SQL.Clear;
    dm.qetiquetas.SQL.Add('select * from ea_pesadas ');
    dm.qetiquetas.SQL.Add('where id='+dm.qpesadassalidasid.asstring+' and idempresa='+dm.qpesadassalidasidempresa.asstring+' and idea='+dm.qpesadassalidasidea.asstring);
    dm.qetiquetas.open;
    dm.qlotespesadas.SQL.Clear;
    dm.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 ');
    dm.qlotespesadas.SQL.Add(',l.sgg,l.sdop,l.sigp,l.sifs,l.sbrc ');
    dm.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);
    dm.qlotespesadas.open;
    if dm.qlotespesadassgg.AsString='' then vsgg:='' else vsgg:='GLOBALGAP' + dm.qlotespesadassgg.Asstring;
    if dm.qlotespesadassdop.AsString='' then vsdop:='' else vsdop:='DOP' + dm.qlotespesadassdop.Asstring;
    if dm.qlotespesadassigp.AsString='' then vsigp:='' else vsigp:='IGP' + dm.qlotespesadassigp.Asstring;
    if dm.qlotespesadassifs.AsString='' then vsifs:='' else vsifs:='IFS' + dm.qlotespesadassifs.Asstring;
    if dm.qlotespesadassbrc.AsString='' then vsbrc:='' else vsbrc:='BRC' + dm.qlotespesadassbrc.Asstring;

    informedb.Datasource:=DM.dsqetiquetas;
    informedb2.DataSource:=dm.dsqlotespesadas;
    informes.Report.Clear;
    informes.LoadFromFile('c:\agrigest\informes\etiquetamovimientos2.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('PARTIDA: '+qpartidasid.asstring+ ' FECHA: '+datetostr(tfecha.Date)+' PARCELA: '+qinfpartidasnombre.AsString+' VARIEDAD: '+qinfpartidasdescripcion.AsString);
//    informes.PrintOptions.Printer.Empty
    informes.Report.PrepareReport(true);
//    informes.PrintOptions.ShowDialog:=false;
//     informes.Report.ShowReport();
    informes.Print;
end;

procedure Tgeneral.combocajasCloseUp(Sender: TObject);
begin
    lenvases_es.SetFocus;
end;

procedure Tgeneral.combocajasEnter(Sender: TObject);
begin
    qcajas.Close;
    qcajas.Open;
end;

procedure Tgeneral.combocalibre_esCloseUp(Sender: TObject);
begin
//    comboentradas_es.setfocus;
end;

procedure Tgeneral.combocalibre_esEnter(Sender: TObject);
begin
    qcalibres.Close;
    qcalibres.Open;
end;

procedure Tgeneral.combodestinoEnter(Sender: TObject);
begin
    if qdestinos.State in [dsbrowse] then qdestinos.Refresh;
end;

procedure Tgeneral.combodestinoExit(Sender: TObject);
begin
   if (combodestino.KeyValue<>null) and (comboorigen.keyvalue<>null) then
   begin
      panel19.Visible:=true;
      btactuallote.SetFocus;
   end else
   begin
      combodestino.SetFocus
   end;
   timer2.Enabled:=false;
end;

procedure Tgeneral.combodestinosEnter(Sender: TObject);
begin
    if qdestinos.State in [dsbrowse] then qdestinos.Refresh;
end;

procedure Tgeneral.combodestino_esCloseUp(Sender: TObject);
begin
    if plotes.Visible=true then
        if (edpeso_es.Enabled=true) then edpeso_es.SetFocus else combolotes_es.SetFocus;
    if (combopalets_es.KeyValue=null) and (combodestino_es.keyvalue=null) then
    begin
      plotes.Visible:=false;
      plotes2.Visible:=false;
    end else
    begin
      plotes.Visible:=true;
      plotes2.Visible:=true;
    end;
end;

procedure Tgeneral.comboentradaCloseUp(Sender: TObject);
var v_ide,v_id,v_idea,vneto,vbruto,vventa,vpesomedio,vtara,vbultos:string;
    v_bultos:integer;
    v_tara,v_taraanterior,v_pesoneto,v_pesobruto,v_pesoventa,v_pesomedio:real;
begin
    if dm.qpesadasresto_cajas.asfloat>0 then
    begin
            v_ide:=dm.qpesadasidempresa.AsString;
            v_id:=dm.qpesadasid.AsString;
            v_idea:=dm.qpesadasidea.AsString;

            dm.qpesadaslotes.Close;
            dm.qpesadaslotes.SQL.Clear;
            dm.qpesadaslotes.sql.Add('select * from lotes_pesadas where ide='+v_ide+' and idea='+v_id+' and idea2='+v_idea);
            dm.qpesadaslotes.Open;
            if dm.qpesadasresto_cajas.asfloat>0 then
            begin
                dm.qpesadastmp.Close;
                comboorigen.KeyValue:=dm.qpesadasiddestino.asstring;
                numpalets:=dm.qpesadasnum_palets.Asinteger;
                restocajas:=dm.qpesadasresto_cajas.asinteger;
                combodestino.KeyValue:=null;
                pesobruto:=dm.qpesadaspeso_bruto.AsFloat;
                combodestino.SetFocus;
                qaux.close;
                qaux.SQL.Clear;
                qaux.SQL.Add('insert into ea_pesadas_tmp select *,'+tidbascula+' from ea_pesadas where idempresa='+v_ide+' and id='+v_id+' and idea='+v_idea);
                qaux.ExecSQL;
                dm.qpesadastmp.Open;
            end else
            begin
                showmessage('ENTRADA USADA POR COMPLETO');
                tid.SetFocus;
            end;
            teclado.Visible:=false;
             //////////////////////// INSERTO LOS MATERIALES DE LAS CAJAS SEGUN EL FORMATO Y EL PALET
            qaux.Close;
            qaux.sql.clear;
            qaux.sql.Add('delete from ea_materiales_tmp where ide='+v_ide+' and idea='+v_id+' and idea2='+v_idea);
            qaux.execsql;
            insertarmaterialestmp(qinsertarmaterialestmp,strtoint(v_id),strtoint(v_idea),strtoint(tidbascula),dm.qpesadasnum_palets.asinteger,strtoint(v_ide),dm.qpesadasid_palet.asstring,1.0);
{            qaux.Close;
            qaux.SQL.Clear;
            qaux.SQL.Add('insert into ea_materiales_tmp ');
            qaux.SQL.Add('select idempresa,'+v_id+' as idea,'+v_idea+' as idea2,idarticulof,sum(cantidadtotal) as cantidadtotal,sum(pesototal) as pesototal,null,sum(preciototal) as preciototal,0 as recuperado,null as identrada,'+tidbascula+' as puesto 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='+v_ide+' and lp.idea='+v_id+' and lp.idea2='+v_idea+' 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) 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='+v_ide+' and lp.idea='+v_id+' and lp.idea2='+v_idea+' 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*'+dm.qpesadasnum_palets.AsString+') as cantidadtotal,(ac.peso*'+dm.qpesadasnum_palets.AsString+') as pesototal,(ac.coste*'+dm.qpesadasnum_palets.AsString+') as preciototal');
            qaux.SQL.Add(' FROM articulos_componentes ac where ac.idempresa='+v_ide+' and ac.idarticuloalmacen=(select id from articulos_almacen where codigo='+''''+dm.qpesadasid_palet.AsString+''''+')');
            qaux.SQL.Add(' ) as ea_materiales_tmp group by idarticulof ');
            qaux.execsql;
}
            qaux.sql.clear;
            qaux.sql.Add('select sum(pesoneto_teorico),sum(cajas),sum(pesoneto_real) from lotes_pesadas_tmp where idea='+v_id+' and idea2='+v_idea);
            qaux.open;

            v_bultos:=qaux.Fields[1].asinteger;
            v_pesoventa:=qaux.Fields[0].AsFloat;
            v_pesoneto:=qaux.Fields[2].AsFloat;
            if v_bultos=0 then v_pesomedio:=0 else v_pesomedio:=v_pesoneto/v_bultos;
            ////////////////////////
            qaux.sql.clear;
            qaux.sql.Add('select sum(peso) from ea_materiales_tmp where ide='+v_ide+' and idea='+v_id+' and idea2='+v_idea);
            qaux.open;
            v_tara:=qaux.Fields[0].AsFloat;
            v_pesobruto:=v_tara+v_pesoneto;
            vtara:=floattostr(v_tara);
            vtara:= StringReplace(vtara, ',', '.',[rfReplaceAll, rfIgnoreCase]);
            vneto:=floattostr(v_pesoneto);
            vneto:= StringReplace(vneto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
            vbruto:=floattostr(v_pesobruto);
            vbruto:= StringReplace(vbruto, ',', '.',[rfReplaceAll, rfIgnoreCase]);
            vventa:=floattostr(v_pesoventa);
            vventa:= StringReplace(vventa, ',', '.',[rfReplaceAll, rfIgnoreCase]);
            vpesomedio:=floattostr(v_pesomedio);
            vpesomedio:= StringReplace(vpesomedio, ',', '.',[rfReplaceAll, rfIgnoreCase]);

            qaux.close;
            qaux.SQL.Clear;
            qaux.SQL.Add('update ea_pesadas_tmp set peso_bruto='+vbruto+',tara='+vtara+',peso_neto='+vneto+',peso_neto_teorico='+vventa+',iddestino='+qdestinosid.AsString+',destino='+''''+qdestinosnombre.AsString+''''+' where idempresa='+v_ide+' and id='+v_id+' and idea='+v_idea);
            qaux.ExecSQL;
            dm.qpesadastmp.Close;
            dm.qpesadastmp.Open;

    end;
end;

procedure Tgeneral.comboentradas_esEnter(Sender: TObject);
begin
    qentradas.Close;
    qentradas.SQL.Clear;
    qentradas.SQL.Add('select * from entradas_almacen where partida='+qpartidasid.asstring+' order by id desc ');
    qentradas.Open;
end;

procedure Tgeneral.comboenvasesEnter(Sender: TObject);
begin
    if qpalets2.State in [dsbrowse] then qpalets2.Refresh;
end;

procedure Tgeneral.comboformatos_esCloseUp(Sender: TObject);
begin
    combocalibre_es.SetFocus;
end;

procedure Tgeneral.comboformatos_esEnter(Sender: TObject);
begin
    qformatoscajas.Close;
    qformatoscajas.Open;
end;

procedure Tgeneral.comboloteCloseUp(Sender: TObject);
begin
    button15.SetFocus;
end;

procedure Tgeneral.comboloteEnter(Sender: TObject);
begin
    if dm.qlotessalidas.State in [dsbrowse] then dm.qlotessalidas.Refresh;
end;

procedure Tgeneral.comboorigenCloseUp(Sender: TObject);
begin
   if (combodestino.KeyValue<>null) and (comboorigen.keyvalue<>null) then
   begin
      panel19.Visible:=true;
   end else
   begin
      panel19.Visible:=false;
   end;
end;

procedure Tgeneral.comboorigenEnter(Sender: TObject);
begin
    if qorigenes.State in [dsbrowse] then qorigenes.Refresh;
   // timer2.Enabled:=false;
end;

procedure Tgeneral.comboorigen_esCloseUp(Sender: TObject);
var anyo,mes,dia:word;
      vanyo,vmes,vdia,vfecha,vfecha2:string;
begin
   if dm.qlotes_pesadas.Active=true then dm.qlotes_pesadas.Refresh;

end;

procedure Tgeneral.combopalets1CloseUp(Sender: TObject);
begin
    edpalets_es.setfocus;

end;

procedure Tgeneral.combopalets1Enter(Sender: TObject);
begin
    if qpalets1.State in [dsbrowse] then qpalets1.Refresh;
    qaux.SQL.Clear;
    qaux.SQL.Add('select * from ea_materiales_tmp where ide=1 and idea=-1000 and idea2=-1000 and puesto='+tidbascula+' and idaf in (select idarticulof from articulos_componentes where idarticuloalmacen='+qpalets1id.AsString+')');
    qaux.open;
    if qaux.recordcount>0 then
    begin
        qaux.SQL.Clear;
        qaux.SQL.Add('delete from ea_materiales_tmp where ide=1 and idea=-1000 and idea2=-1000 and puesto='+tidbascula+' and idaf in (select idarticulof from articulos_componentes where idarticuloalmacen='+qpalets1id.AsString+')');
        qaux.execsql;
    end;
    qorigenes.Close;
    qorigenes.Open;
end;

procedure Tgeneral.combopaletsEnter(Sender: TObject);
begin
    if qpalets1.State in [dsbrowse] then qpalets1.Refresh;
end;

procedure Tgeneral.combopalets_esDragDrop(Sender, Source: TObject; X,
  Y: Integer);
begin
    if (combopalets_es.KeyValue=null) and (combodestino_es.keyvalue=null) then
    begin
      plotes.Visible:=false;
      plotes2.Visible:=false;
    end else
    begin
      plotes.Visible:=true;
      plotes2.Visible:=true;
    end;
end;

procedure Tgeneral.combopalets_esExit(Sender: TObject);
begin
    qaux.SQL.Clear;
    qaux.SQL.Add('select * from ea_materiales_tmp where ide=1 and idea=-1000 and idea2=-1000 and puesto='+tidbascula+' and idaf in (select idarticulof from articulos_componentes where idarticuloalmacen='+qpalets1id.AsString+')');
    qaux.open;
    if qaux.recordcount>0 then
    begin
        qaux.SQL.Clear;
        qaux.SQL.Add('delete from ea_materiales_tmp where ide=1 and idea=-1000 and idea2=-1000 and puesto='+tidbascula+' and idaf in (select idarticulof from articulos_componentes where idarticuloalmacen='+qpalets1id.AsString+')');
        qaux.execsql;
    end;
    qorigenes.Close;
    qorigenes.Open;
end;

procedure Tgeneral.combopartidasDropDown(Sender: TObject);
begin
   if qpartidas.State in [dsbrowse] then qpartidas.Refresh else qpartidas.open;
end;

procedure Tgeneral.combovariedadsCloseUp(Sender: TObject);
var anyo,mes,dia:word;
      vanyo,vmes,vdia,vfecha,vfecha2:string;
begin
   //tfechatrabajo.Date:=tfecha.Date;
   decodedate(tfecha.Date,anyo,mes,dia);
   vanyo:=floattostr(anyo);
   vmes:=floattostr(mes);
   vdia:=floattostr(dia);
   if length(vmes)=1 then vmes:='0'+vmes;
   if length(vdia)=1 then vdia:='0'+vdia;
   vfecha:=vdia+'/'+vmes+'/'+vanyo;//+'/'+vmes+'/'+vdia;
   decodedate(tfecha.Date-5,anyo,mes,dia);
   vanyo:=floattostr(anyo);
   vmes:=floattostr(mes);
   vdia:=floattostr(dia);
   if length(vmes)=1 then vmes:='0'+vmes;
   if length(vdia)=1 then vdia:='0'+vdia;

   vfecha2:=vanyo+'-'+vmes+'-'+vdia;

   if 'edpesosalida'='' then
   begin
   end else  button15.SetFocus;

end;

procedure Tgeneral.combovariedadsEnter(Sender: TObject);
begin
   if qmprimas.State in [dsbrowse] then qmprimas.Refresh;
end;

procedure Tgeneral.combovariedad_esCloseUp(Sender: TObject);
begin
    combopalets_es.SetFocus;
end;

procedure Tgeneral.combovariedad_esDropDown(Sender: TObject);
begin
    qmprimas.Close;
    if rdesechos.Checked then
    begin
      qmprimas.SQL.Clear;
      qmprimas.SQL.Add('select * from materias_primas where basculas=1 and activo=1 and desechos=1 order by id');
    end;
    if renvasados.Checked then
    begin
      qmprimas.SQL.Clear;
      qmprimas.SQL.Add('select * from materias_primas where basculas=1 and activo=1 and desechos=0 order by id');
    end;
    if rentradas.Checked then
    begin
      qmprimas.SQL.Clear;
      qmprimas.SQL.Add('select * from materias_primas where basculas=1 and activo=1 order by id');
    end;
    if rmultiples.Checked then
    begin
      qmprimas.SQL.Clear;
      qmprimas.SQL.Add('select * from materias_primas where basculas=1 and activo=1 and desechos=0 order by id');
    end;
    qmprimas.Open;
end;

procedure Tgeneral.combovariedad_esExit(Sender: TObject);
var anyo,mes,dia:word;
      vanyo,vmes,vdia,vfecha,vfecha2:string;
begin
   //tfechatrabajo.Date:=tfecha.Date;

   decodedate(tfecha.Date,anyo,mes,dia);
   vanyo:=floattostr(anyo);
   vmes:=floattostr(mes);
   vdia:=floattostr(dia);
   if length(vmes)=1 then vmes:='0'+vmes;
   if length(vdia)=1 then vdia:='0'+vdia;
   vfecha:=''''+vdia+'/'+vmes+'/'+vanyo+'''';//+'/'+vmes+'/'+vdia;
   decodedate(tfecha.Date,anyo,mes,dia);
   vanyo:=floattostr(anyo);
   vmes:=floattostr(mes);
   vdia:=floattostr(dia);
   if length(vmes)=1 then vmes:='0'+vmes;
   if length(vdia)=1 then vdia:='0'+vdia;
   vfecha2:=''''+vanyo+'-'+vmes+'-'+vdia+'''';
   if qmprimascompuesto.AsInteger=1 then
   begin
       escompuesta:=1;
       dm.qaux.SQL.Clear;
       dm.qaux.SQL.Add('select * from mp_compuestas where idmp='+''''+qmprimasid.asstring+'''');
       dm.qaux.Open;
       if dm.qaux.RecordCount>0 then
       begin

         dm.qlotessalidas.SQL.Clear;
         dm.qlotessalidas.sql.Add('select concat(codigo,'+''''''+') as lote,fecha,parcela as origen,mprima,idempresa,porc_merma,merma from lotes where codigo in (select distinct(lote) from restos_dia where fecha='+vfecha2+' and idalmacen='+qorigenesid.asstring);
         dm.qlotessalidas.SQL.Add(' and mprima in (select idmpc from mp_compuestas where idmp='+''''+qmprimasid.asstring+''''+')) order by codigo desc,fecha desc');
         dm.qlotessalidas.Open;
       end else showmessage('ESTA MATERIA PRIMA COMPUESTA NO ESTA BIEN CONFIGURADA');
   end;
  if general.qmprimascompuesto.AsInteger=0 then
   begin
     if pseparartraza_es=0 then
     begin
       escompuesta:=0;
       dm.qlotessalidas.SQL.Clear;
       dm.qlotessalidas.sql.Add('select concat(codigo,'+''''''+') as lote,fecha,parcela as origen,mprima,idempresa,porc_merma,merma from lotes where codigo in (select distinct(lote) from restos_dia where fecha='+vfecha2+' and idalmacen='+qorigenesid.asstring+') order by codigo desc,fecha desc');
       dm.qlotessalidas.Open;
     end else
     begin
       escompuesta:=0;
       dm.qlotessalidas.SQL.Clear;
       dm.qlotessalidas.sql.Add('select concat(trazabilidad,'+''''''+') as lote,fecha,parcela as origen,mprima,idempresa,porc_merma,merma from lotes where fecha='+vfecha2+' and parcela=:ALMACEN order by codigo desc,fecha desc');//codigo in (select distinct(lote) from restos_dia where fecha='+vfecha2+' and idalmacen='+qorigenesid.asstring+') order by codigo desc,fecha desc');
       dm.qlotessalidas.Prepare;
       dm.qlotessalidas.ParamByName('ALMACEN').AsString:=qorigenescentrocoste_asociado.asstring;
       dm.qlotessalidas.Open;
     end;
   end;
end;

procedure Tgeneral.comdata1Packet(Sender: TObject; const Str: string);
var pos1,pos2:integer;
    peso2:real;
begin
if ttipobascula='2' then
begin
 Pos1 := System.Pos(comdata1.StartString, str);
 pos2 := pos1+7;
 cadena:=copy(str,pos1,8);
 cadena:= StringReplace(cadena, '.', ',',[rfReplaceall, rfIgnoreCase]);
 cadena:= StringReplace(cadena, ' ', '',[rfReplaceAll, rfIgnoreCase]);

 try
    peso2:=strtofloat(cadena);
    cadena:=FormatFloat('0.0', peso2);
 except
     on error: exception do
        begin
           peso2:=0;
        end;
  end;
  lpeso2.caption :=cadena;
end;

if ttipobascula='6' then
begin
 Pos1 := System.Pos(comdata1.StartString, str);
 pos2 := pos1+7;
 cadena:=copy(str,pos1,8);
 cadena:= StringReplace(cadena, '.', ',',[rfReplaceall, rfIgnoreCase]);
 cadena:= StringReplace(cadena, ' ', '',[rfReplaceAll, rfIgnoreCase]);

 try
    peso2:=strtofloat(cadena);
    cadena:=FormatFloat('0.0', peso2);
 except
     on error: exception do
        begin
           peso2:=0;
        end;
  end;
  lpeso2.caption :=cadena;
end;
if ttipobascula='7' then
begin
 Pos1 := System.Pos(comdata1.StartString, str);
 pos2 := pos1+7;
 cadena:=copy(str,pos1,8);
 cadena:= StringReplace(cadena, '.', ',',[rfReplaceall, rfIgnoreCase]);
 cadena:= StringReplace(cadena, '=', '',[rfReplaceAll, rfIgnoreCase]);

 try
    peso2:=strtofloat(cadena);
    cadena:=FormatFloat('0.0', peso2);
 except
     on error: exception do
        begin
           peso2:=0;
        end;
  end;
  lpeso2.caption :=cadena;
end;


end;

procedure Tgeneral.comdata2Packet(Sender: TObject; const Str: string);
var pos1,pos2:integer;
    peso2:real;
begin
if ttipobascula='6' then
begin
 Pos1 := System.Pos(comdata2.StartString, str);
 pos2 := pos1+7;
 cadena:=copy(str,pos1,8);
 cadena:= StringReplace(cadena, '.', ',',[rfReplaceAll, rfIgnoreCase]);
 cadena:= StringReplace(cadena, ' ', '',[rfReplaceAll, rfIgnoreCase]);
 visor:=cadena;
  try
    peso2:=strtofloat(cadena);
    peso2:=peso2*-1;
    cadena:=FormatFloat('0.0', peso2);
    except
        on error: exception do
        begin
           peso2:=0;
        end;
    end;
  if peso2<0 then cadena:='ˇˇERRORˇˇ';
  lpeso2.caption :=cadena;

end;

end;

procedure Tgeneral.DBGrid7DrawColumnCell(Sender: TObject; const Rect: TRect;
  DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
    if qpedidospendientescantidadservida.Asinteger>qpedidospendientescantidad.Asinteger then
    begin
        dbgrid7.Canvas.brush.Color := rojo;
    end;
    if qpedidospendientescantidadservida.Asinteger=qpedidospendientescantidad.Asinteger then
    begin
        dbgrid7.Canvas.brush.Color := verde;
    end;

    dbgrid7.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;

procedure Tgeneral.tpaletsEnter(Sender: TObject);
begin
//    dm.qpesadastmpnum_palets.Value:=null;
//    tpalets.Text:='';
    teclado.Visible:=true;
    teclado.Top:=tpalets.Top+131;
    teclado.left:=tpalets.Left+650;
end;

procedure Tgeneral.tpaletsExit(Sender: TObject);
var cajas,newcajas,newpalets:integer;
    pneto,newpneto,preal,newpreal,tara:real;
begin
   teclado.Visible:=false;
   if tpalets.Text='' then tpalets.Text:=dm.qpesadasnum_palets.AsString;
   if dm.qpesadastmp.State in [dsedit,dsinsert] then
   begin
     dm.qpesadastmp.post;
     qaux.Close;
     qaux.SQL.Clear;
     qaux.SQL.Add('select sum(pesoneto_teorico) from lotes_pesadas_tmp');
     qaux.Open;
     newpneto:=qaux.Fields[0].AsFloat;
     qaux.Close;
     qaux.SQL.Clear;
     qaux.SQL.Add('select sum(pesoneto_real) from lotes_pesadas_tmp');
     qaux.Open;
     newpreal:=qaux.Fields[0].AsFloat;
     qaux.SQL.Clear;
     qaux.SQL.Add('select compuesto from materias_primas where id='+''''+dm.qpesadastmpmprima.asstring+'''');
     qaux.Open;
     if qaux.Fields[0].Asinteger=1 then
     begin
       qaux.Close;
       qaux.SQL.Clear;
       qaux.SQL.Add('select sum(cajas*(porcentaje/100)) from lotes_pesadas_tmp l,mp_compuestas m where l.mprima=m.idmpc and l.ide=m.idempresa');
       qaux.Open;
     end else
     begin
       qaux.Close;
       qaux.SQL.Clear;
       qaux.SQL.Add('select sum(cajas) from lotes_pesadas_tmp');
       qaux.Open;
     end;

     newcajas:=qaux.Fields[0].Asinteger;
     qaux.Close;
     qaux.SQL.Clear;
     qaux.SQL.Add('select tara from articulos_almacen where codigo='+''''+dm.qpesadastmpid_envase.asstring+'''');
     qaux.Open;
     tara:=qaux.Fields[0].Asfloat*newcajas;
     qaux.Close;
     qaux.SQL.Clear;
     qaux.SQL.Add('select tara from articulos_almacen where codigo='+''''+dm.qpesadastmpid_palet.asstring+'''');
     qaux.Open;
     tara:=tara+(qaux.Fields[0].AsFloat*dm.qpesadastmpnum_palets.AsInteger);

     qaux.Close;
     qaux.SQL.Clear;
     qaux.SQL.Add('update ea_pesadas_tmp set num_envases='+inttostr(newcajas)+',resto_cajas='+inttostr(newcajas)+',peso_neto='+stringReplace(floattostr(newpreal), ',', '.',[rfReplaceAll, rfIgnoreCase])+',peso_neto_teorico='+stringReplace(floattostr(newpneto), ',', '.',[rfReplaceAll, rfIgnoreCase])+',tara='+stringReplace(floattostr(tara), ',', '.',[rfReplaceAll, rfIgnoreCase])+',peso_bruto='+stringReplace(floattostr(newpreal+tara), ',', '.',[rfReplaceAll, rfIgnoreCase]));
     qaux.ExecSQL;
     dm.qpesadastmp.Refresh;


   end;
end;

procedure Tgeneral.timepedidosTimer(Sender: TObject);
var id,ide:string;
begin
    id:=qpedidospendientesid.Asstring;
    ide:=qpedidospendienteside.asstring;
    qpedidospendientes.Refresh;
    qpedidospendientes.Locate('ide;id',vararrayof([ide,id]),[locaseinsensitive]);

end;

procedure Tgeneral.combolotesentradaDropDown(Sender: TObject);
begin
//  if dm.qlotes.State in [dsbrowse] then dm.qlotes.Refresh;
//   if dm.qlotessalidas.State in [dsbrowse] then dm.qlotessalidas.Refresh;

end;

procedure Tgeneral.btguardarClick(Sender: TObject);
var pesopalets,pesocajas:real;
    anyo,mes,dia:word;
    vanyo,vmes,vdia,vfecha,vpesobruto,vpesoneto,vcajas,tipotrabajo:string;
    vfecha2,mprima,lote,observaciones,tpesoneto,tpesonetoteorico:string;
    tcostocosechar,tcostocamara,tcostosinmt,tcostomateriales,idalmacen,almacen,idalmacenintermedio,almacenintermedio,numid:string;
    tpesobruto,ideaviejo,tmultiplicador,tcea,tidea,tidea2,identrada:string;
    idorigen,idea,escompuesta_es,num_id:integer;
    pesoneto,pesonetoteorico,peso1,pesomedio,pesomedioteorico,kiloscampocamara,jornalescampocamara,costocosechar,costocamara,costosinmt,costomateriales:real;
    cajas1,cajas2,cajas,cajasiniciales,dias,cajastotales,cajasporpalet:integer;
    pesocaja,palet,pesolets,pesobruto,multiplicador:real;
    error:integer;
begin

    if esentrada=1 then
    begin
      qpesadaslotesentradas.open;
      qaux.sql.clear;
      qaux.sql.add('delete from ea_pesadas_tmp where puesto='+tidbascula);//+dm.qlotesidempresa.asstring);
      qaux.execsql;

       comboentradas_es.Visible:=true;
       btnuevaentrada.visible:=true;
       label61.Visible:=true;
       dbtext9.Visible:=true;
       if qdestinostipo_trabajo.asstring<>'' then
       begin
          tipotrabajo:=qdestinostipo_trabajo.asstring;
       end;
       decodedate(tfecha.Date,anyo,mes,dia);
       vanyo:=floattostr(anyo);
       vmes:=floattostr(mes);
       vdia:=floattostr(dia);
       if length(vmes)=1 then vmes:='0'+vmes;
       if length(vdia)=1 then vdia:='0'+vdia;
       vfecha:=''''+vanyo+'-'+vmes+'-'+vdia+'''';
       qparcelas.Open;
       qparcelas.Locate('codpar',qpartidasid_parcela.asstring,[locaseinsensitive,lopartialkey]);
        dm.qpesadastmp.open;
        dm.qpesadastmp.Append;
        dm.qpesadastmpid.Value:=-1000-strtoint(tidbascula);
        dm.qpesadastmppuesto.value:=strtoint(tidbascula);
        dm.qpesadastmpidea.value:=qentradasid.AsInteger;
        dm.qpesadastmpid_palet.value:=qpalets1codigo.asstring;
        dm.qpesadastmpnum_palets.value:=strtoint(edpalets_es.Text);
        dm.qpesadastmpid_envase.value:=qcajascodigo.asstring;
        dm.qpesadastmpnum_envases.value:=strtoint(lbultos.Text);
        if qdestinosfinal.AsInteger=1 then
        begin
            dm.qpesadastmpiddestino.Value:=qdestinosalmacen_asociado.AsInteger;
            qaux.Close;
            qaux.SQL.Clear;
            qaux.SQL.Add('select nombre from almacenes where id='+qdestinosalmacen_asociado.Asstring);
            qaux.Open;
            dm.qpesadastmpdestino.value:=qaux.Fields[0].asstring;
            dm.qpesadastmprecuperar_envases.Value:=1;
        end
        else
        begin
          dm.qpesadastmpiddestino.Value:=qdestinosid.AsInteger;
          dm.qpesadastmpdestino.value:=qdestinosnombre.asstring;
          dm.qpesadastmprecuperar_envases.Value:=0;
        end;
        edpeso_es.Text:=StringReplace(edpeso_es.text, '.', ',',[rfReplaceAll, rfIgnoreCase]);
        ltaraanterior.Text:=StringReplace(ltaraanterior.text, '.', ',',[rfReplaceAll, rfIgnoreCase]);
        dm.qpesadastmppeso_bruto.value:=strtofloat(edpeso_es.text);
        dm.qpesadastmptara0.value:=STRTOFLOAT(ltaraanterior.Text);
        ltara.Text:=StringReplace(ltara.text, '.', ',',[rfReplaceAll, rfIgnoreCase]);
        dm.qpesadastmptara.value:=strtofloat(ltara.text);
        lneto.Text:=StringReplace(lneto.text, '.', ',',[rfReplaceAll, rfIgnoreCase]);
        dm.qpesadastmppeso_neto.value:=strtofloat(lneto.Text);
        lventa_es.Text:=StringReplace(lventa_es.text, '.', ',',[rfReplaceAll, rfIgnoreCase]);
        dm.qpesadastmppeso_neto_teorico.value:=strtofloat(lventa_es.text);
        dm.qpesadastmppeso_medio.Value:=dm.qpesadastmppeso_neto.AsFloat/dm.qpesadastmpnum_envases.AsInteger;
        dm.qpesadastmptemperatura.value:=strtofloat(ltemperatura.Text);
        dm.qpesadastmpcalibre.value:=0;
        dm.qpesadastmporigen.Value:=dm.qlotesparcela.Asstring;
        dm.qpesadastmphora.value:=time();
        dm.qpesadastmpfecha.Value:=tfecha.date;
        dm.qpesadastmpfechatrabajo.value:=tfecha.Date;
        vpesobruto:=Format ('%.*d', [5,trunc(dm.qpesadastmppeso_bruto.AsFloat*10)]);
        if dm.qpesadastmppeso_neto.asfloat<0 then dm.qpesadastmppeso_neto.asfloat:=-dm.qpesadastmppeso_neto.asfloat;
        vpesoneto:=Format ('%.*d', [5,trunc(dm.qpesadastmppeso_neto.AsFloat*10)]);
        vcajas:=Format ('%.*d', [3,dm.qpesadastmpnum_envases.asinteger]);
        dm.qpesadastmpcea.Value:=tidbascula+vanyo+vmes+vdia+vpesoneto+vcajas;
        dm.qpesadastmpmprima.value:=dm.qlotesmprima.asstring;
        dm.qpesadastmpgen_caja.Value:=0;
        dm.qpesadastmpcosto.Value:=qparcelascoste_kg_ref.AsFloat;
        dm.qpesadastmplote.Value:=dm.qlotescodigo.AsInteger;
        dm.qpesadastmptipo_trabajo.value:=tipotrabajo;
        dm.qpesadastmpidempresa.value:=dm.qlotesidempresa.asinteger;
        dm.qpesadastmpOBSERVACIONES.value:=datetostr(tfecha.Date)+'-'+dm.qpesadastmpparcela.AsString+'-->'+dm.qpesadastmpdestino.asstring;;
        qaux.SQL.Clear;
        qaux.SQL.Add('select sum(precio) from ea_materiales_tmp where idea=-1000 and idea2=-1000 and puesto='+tidbascula);
        qaux.open;
        dm.qpesadastmpcosto_materiales.value:=qaux.Fields[0].asfloat;
//        if combogrupos.keyvalue<>null then dm.qpesadastmpidgrupo.value:=combogrupos.keyvalue;

    ///actualizo la parcela y el lote detallado

        dm.qaux.SQL.Clear;
        dm.qaux.sql.add('select count(*) from lotes_pesadas_tmp where ide='+dm.qpesadastmpidempresa.asstring+' and idea=-1000 and idea2=-1000 and puesto='+tidbascula);
        dm.qaux.open;
        if dm.qaux.Fields[0].asinteger>0 then
        begin
           dm.qaux.Close;
           dm.qaux.SQL.Clear;
           dm.qaux.sql.add('select distinct(lp.lote),l.parcela from lotes_pesadas_tmp lp,lotes l where lp.ide=l.idempresa and lp.lote=l.codigo and ide='+dm.qpesadastmpidempresa.asstring+' and idea=-1000 and idea2=-1000 and puesto='+tidbascula);
           dm.qaux.open;
           dm.qaux.First;
           dm.qpesadastmp.edit;
           while not dm.qaux.Eof do
           begin
             dm.qpesadastmplotes_detalle.Value:=dm.qpesadastmplotes_detalle.AsString+dm.qaux.Fields[0].AsString+'/';
             dm.qpesadastmpparcela.Value:=dm.qaux.Fields[1].AsString+'/';
             dm.qaux.Next;
           end;
        end;
        tcea:='';
        tcea:=dm.qpesadastmpCEA.AsString;
        dm.qpesadastmp.Post;
        qaux.SQL.Clear;
        qaux.SQL.Add('insert into ea_pesadas select * from vea_pesadas_tmp where cea='+tidbascula+vanyo+vmes+vdia+vpesoneto+vcajas);
        qaux.ExecSQL;

        qaux.Close;
        qaux.SQL.Clear;
        qaux.SQL.Add('select idempresa,id,idea from ea_pesadas where cea='+''''+tcea+''''+' order by id desc limit 1');
        qaux.open;
//        dm.qpesadastmp.Refresh;
        tidea:=qaux.fields[1].asstring;
        tidea2:=qaux.fields[2].asstring;
        qaux.SQL.Clear;
        qaux.SQL.Add('update lotes_pesadas_tmp set idea='+tidea+',idea2='+tidea2+' where idea=-1000 and idea2=-1000 and puesto='+tidbascula);// and es_entrada=1');
        qaux.ExecSQL;

        qaux.SQL.Clear;
        qaux.SQL.Add('update ea_materiales_tmp set idea='+tidea+',idea2='+tidea2+' where idea=-1000 and idea2=-1000 and puesto='+tidbascula);// and es_entrada=1');
        qaux.ExecSQL;

        qaux.SQL.Clear;
        qaux.SQL.Add('insert into lotes_pesadas select * from v_lotespesadastmp where idea='+tidea+' and idea2='+tidea2);// where es_entrada=1');
        qaux.ExecSQL;

        qaux.SQL.Clear;
        qaux.SQL.Add('insert into ea_materiales select * from v_eamaterialestmp where idea='+tidea+' and idea2='+tidea2);// where es_entrada=1');
        qaux.ExecSQL;

        if qdestinosfinal.AsInteger=1 then
        begin
          qaux.SQL.Clear;
          qaux.SQL.Add('update ea_materiales set recuperado=-1 where idea='+tidea+' and idea2='+tidea2);// and es_entrada=1');
          qaux.ExecSQL;
          observaciones:=dm.qpesadastmpOBSERVACIONES.asstring+'-'+datetostr(tfecha.Date)+'-->'+qdestinosnombre.AsString;;

          qaux.SQL.Clear;
          qaux.SQL.Add('update ea_pesadas_tmp set recuperar_envases=0,id='+tidea+',idea=0,idorigen='+qdestinosalmacen_asociado.asstring+',iddestino='+qdestinosid.Asstring+',destino='+''''+qdestinosnombre.asstring+''''+',observaciones='+''''+observaciones+''''+' where idea='+tidea2);
          qaux.ExecSQL;
            qaux.SQL.Clear;
            qaux.SQL.Add('insert into ea_pesadas select * from v_eapesadastmp where cea='+''''+tcea+''''+' and idea=0');
            qaux.ExecSQL;

            qaux.Close;
            qaux.SQL.Clear;
            qaux.SQL.Add('select idempresa,id,idea from ea_pesadas where id='+tidea+' and idea=0 ');
            qaux.open;
            tidea:=qaux.fields[1].asstring;
//            tidea2:=qaux.fields[2].asstring;
            qaux.SQL.Clear;
            qaux.SQL.Add('update lotes_pesadas_tmp set idea='+tidea+',idea2=0 where idea='+tidea+' and idea2='+tidea2);// and es_entrada=1');
            qaux.ExecSQL;

            qaux.SQL.Clear;
            qaux.SQL.Add('update ea_materiales_tmp set idea='+tidea+',idea2=0 where idea='+tidea+' and idea2='+tidea2);// and es_entrada=1');
            qaux.ExecSQL;

            qaux.SQL.Clear;
            qaux.SQL.Add('insert into lotes_pesadas select * from v_lotespesadastmp where idea='+tidea+' and idea2=0');// where es_entrada=1');
            qaux.ExecSQL;

            qaux.SQL.Clear;
            qaux.SQL.Add('insert into ea_materiales select * from v_eamaterialestmp where idea='+tidea+' and idea2=0');// where es_entrada=1');
            qaux.ExecSQL;
            qaux.SQL.Clear;
            qaux.SQL.Add('delete from ea_pesadas_tmp where id='+tidea);
            qaux.ExecSQL;

            qaux.SQL.Clear;
            qaux.SQL.Add('delete from lotes_pesadas_tmp where puesto='+tidbascula);// where es_entrada=1');
            qaux.ExecSQL;

            qaux.SQL.Clear;
            qaux.SQL.Add('delete from ea_materiales_tmp where puesto='+tidbascula);// where es_entrada=1');
            qaux.ExecSQL;

        end;



        qaux.SQL.Clear;
        qaux.SQL.Add('delete from ea_pesadas_tmp where puesto='+tidbascula);
        qaux.ExecSQL;

        qaux.SQL.Clear;
        qaux.SQL.Add('delete from lotes_pesadas_tmp where puesto='+tidbascula);// where es_entrada=1');
        qaux.ExecSQL;

        qaux.SQL.Clear;
        qaux.SQL.Add('delete from ea_materiales_tmp where puesto='+tidbascula);// where es_entrada=1');
        qaux.ExecSQL;
        identrada:=qentradasid.AsString;
        qentradas.Refresh;
        qentradas.Locate('id',identrada,[locaseinsensitive]);
        timer1.Enabled:=true;
        timer2.Enabled:=true;
        dm.qpesadasentradas.Refresh;
        dm.qpesadasentradas.First;
        qpesadaslotesentradas.refresh;
      //  combolotes_es.KeyValue:=null;
        edpalets_es.setfocus;
        btnuevolote.SetFocus;
    end;
    if esentrada=0 then
    begin
/////////  ultima modificacion
      if esmultiple=0 then
      begin
      qpesadaslotessalidas.open;
      qaux.sql.clear;
      qaux.sql.add('delete from ea_pesadas_tmp where id=-2000');//+dm.qlotesidempresa.asstring);
      qaux.execsql;

       comboentradas_es.Visible:=false;
       btnuevaentrada.visible:=false;
       label61.Visible:=false;
       dbtext9.Visible:=true;
       if qdestinostipo_trabajo.asstring<>'' then
       begin
          tipotrabajo:=qdestinostipo_trabajo.asstring;
       end;
       decodedate(tfecha.Date,anyo,mes,dia);
       vanyo:=floattostr(anyo);
       vmes:=floattostr(mes);
       vdia:=floattostr(dia);
       if length(vmes)=1 then vmes:='0'+vmes;
       if length(vdia)=1 then vdia:='0'+vdia;
       vfecha:=''''+vanyo+'-'+vmes+'-'+vdia+'''';
       qparcelas.Open;
       qparcelas.Locate('codpar',qpartidasid_parcela.asstring,[locaseinsensitive,lopartialkey]);
        dm.qpesadastmp.open;
        dm.qpesadastmp.Append;
        dm.qpesadastmpid.Value:=-2000;
        dm.qpesadastmpidea.value:=0;//-2000;
        dm.qpesadastmpid_palet.value:=qpalets1codigo.asstring;
        dm.qpesadastmpnum_palets.value:=strtoint(edpalets_es.Text);
        dm.qpesadastmpid_envase.value:=qpalets2codigo.asstring;
        dm.qpesadastmpnum_envases.value:=strtoint(lbultos.Text);
        dm.qpesadastmpiddestino.Value:=qdestinosid.AsInteger;
        dm.qpesadastmpdestino.value:=qdestinosnombre.asstring;
        edpeso_es.Text:=StringReplace(edpeso_es.text, '.', ',',[rfReplaceAll, rfIgnoreCase]);
        ltaraanterior.Text:=StringReplace(ltaraanterior.text, '.', ',',[rfReplaceAll, rfIgnoreCase]);
        dm.qpesadastmppeso_bruto.value:=strtofloat(edpeso_es.text);
        dm.qpesadastmptara0.value:=STRTOFLOAT(ltaraanterior.Text);
        ltara.Text:=StringReplace(ltara.text, '.', ',',[rfReplaceAll, rfIgnoreCase]);
        dm.qpesadastmptara.value:=strtofloat(ltara.text);
        lneto.Text:=StringReplace(lneto.text, '.', ',',[rfReplaceAll, rfIgnoreCase]);
        dm.qpesadastmppeso_neto.value:=strtofloat(lneto.Text);
        lventa_es.Text:=StringReplace(lventa_es.text, '.', ',',[rfReplaceAll, rfIgnoreCase]);
        dm.qpesadastmppeso_neto_teorico.value:=strtofloat(lventa_es.text);
        dm.qpesadastmppeso_medio.Value:=dm.qpesadastmppeso_neto.AsFloat/dm.qpesadastmpnum_envases.AsInteger;
        dm.qpesadastmptemperatura.value:=strtofloat(ltemperatura.Text);
        dm.qpesadastmpcalibre.value:=0;
        dm.qpesadastmporigen.Value:=qpartidasid_parcela.Asstring;
        dm.qpesadastmphora.value:=time();
        dm.qpesadastmpfecha.Value:=tfecha.date;
        dm.qpesadastmpfechatrabajo.value:=tfecha.Date;
        vpesobruto:=Format ('%.*d', [5,trunc(dm.qpesadastmppeso_bruto.AsFloat*10)]);
        vpesoneto:=Format ('%.*d', [5,trunc(dm.qpesadastmppeso_neto.AsFloat*10)]);
        vcajas:=Format ('%.*d', [3,dm.qpesadastmpnum_envases.asinteger]);
        dm.qpesadastmpcea.Value:=tidbascula+vanyo+vmes+vdia+vpesoneto+vcajas;
        dm.qpesadastmpidorigen.value:=qorigenesid.Asinteger;
        dm.qpesadastmporigen.value:=qorigenesnombre.AsString;
        dm.qpesadastmpgen_caja.Value:=0;
        dm.qpesadastmpcosto.Value:=qparcelascoste_kg_ref.AsFloat;
        dm.qpesadastmplote.Value:=dm.qlotessalidaslote.AsInteger;
        dm.qpesadastmpmprima.Value:=qmprimasid.AsString;
        dm.qpesadastmptipo_trabajo.value:='';//tipotrabajo;
        dm.qpesadastmpidempresa.value:=dm.qlotessalidasidempresa.asinteger;
        dm.qpesadastmpparcela.value:=dm.qlotessalidasorigen.AsString;
        dm.qpesadastmppuesto.Value:=strtoint(tidbascula);
        dm.qpesadastmpOBSERVACIONES.value:=datetostr(tfecha.Date)+'-'+dm.qpesadastmpparcela.AsString+'-->'+dm.qpesadastmpdestino.asstring;;
        qaux.SQL.Clear;
        qaux.SQL.Add('select sum(precio) from ea_materiales_tmp where idea=-2000 and idea2=0');
        qaux.open;
        dm.qpesadastmpcosto_materiales.value:=qaux.Fields[0].asfloat;

    ///actualizo la parcela y el lote detallado

        dm.qaux.SQL.Clear;
        dm.qaux.sql.add('select count(*) from lotes_pesadas_tmp where ide='+dm.qpesadastmpidempresa.asstring+' and idea=-2000 and idea2=0');
        dm.qaux.open;
        if dm.qaux.Fields[0].asinteger>0 then
        begin
           dm.qaux.Close;
           dm.qaux.SQL.Clear;
           dm.qaux.sql.add('select distinct(lp.lote),l.parcela from lotes_pesadas_tmp lp,lotes l where lp.ide=l.idempresa and lp.lote=l.codigo and ide='+dm.qpesadastmpidempresa.asstring+' and idea=-2000 and idea2=0');
           dm.qaux.open;
           dm.qaux.First;
           dm.qpesadastmp.edit;
           while not dm.qaux.Eof do
           begin
             dm.qpesadastmplotes_detalle.Value:=dm.qpesadastmplotes_detalle.AsString+dm.qaux.Fields[0].AsString+'/';
             dm.qpesadastmpparcela.Value:=dm.qaux.Fields[1].AsString+'/';
             dm.qaux.Next;
           end;
        end;
        tcea:='';
        tcea:=dm.qpesadastmpCEA.AsString;
        dm.qpesadastmp.Post;
        qaux.SQL.Clear;
        qaux.SQL.Add('insert into ea_pesadas select * from vea_pesadas_tmp where idea=0 and cea='+tidbascula+vanyo+vmes+vdia+vpesoneto+vcajas);
        qaux.ExecSQL;
        qaux.SQL.Clear;
        qaux.SQL.Add('delete from ea_pesadas_tmp where id=-2000 and idea=0');
        qaux.ExecSQL;
        qaux.Close;
        qaux.SQL.Clear;
        qaux.SQL.Add('select idempresa,id,idea from ea_pesadas where cea='+''''+tcea+''''+' order by id desc limit 1');
        qaux.open;
        dm.qpesadastmp.Refresh;
        tidea:=qaux.fields[1].asstring;
        tidea2:=qaux.fields[2].asstring;
        qaux.SQL.Clear;
        qaux.SQL.Add('update lotes_pesadas_tmp set idea='+tidea+',idea2='+tidea2+' where idea=-2000 and idea2=0');// and es_entrada=1');
        qaux.ExecSQL;

        qaux.SQL.Clear;
        qaux.SQL.Add('update ea_materiales_tmp set idea='+tidea+',idea2='+tidea2+' where idea=-2000 and idea2=0');// and es_entrada=1');
        qaux.ExecSQL;

        qaux.SQL.Clear;
        qaux.SQL.Add('insert into lotes_pesadas select * from v_lotespesadastmp where idea='+tidea+' and idea2='+tidea2);// where es_entrada=1');
        qaux.ExecSQL;

        qaux.SQL.Clear;
        qaux.SQL.Add('insert into ea_materiales select * from v_eamaterialestmp where idea='+tidea+' and idea2='+tidea2);// where es_entrada=1');
        qaux.ExecSQL;
        qaux.SQL.Clear;
        qaux.SQL.Add('delete from ea_pesadas_tmp where puesto='+tidbascula);
        qaux.ExecSQL;

        qaux.SQL.Clear;
        qaux.SQL.Add('delete from lotes_pesadas_tmp where puesto='+tidbascula);// where es_entrada=1');
        qaux.ExecSQL;

        qaux.SQL.Clear;
        qaux.SQL.Add('delete from ea_materiales_tmp where puesto='+tidbascula);;// where es_entrada=1');
        qaux.ExecSQL;


        qpesadaslotessalidas.Refresh;
        timer1.Enabled:=true;
        timer2.Enabled:=true;
        dm.qpesadassalidas.Refresh;
        dm.qpesadassalidas.First;
        plotes.Visible:=false;
        plotes2.Visible:=false;
        combopalets_es.KeyValue:=null;
        comboenvases_es.KeyValue:=null;
        combovariedad_es.KeyValue:=null;
        comboorigen_es.KeyValue:=null;
        combodestino_es.KeyValue:=null;
        combolotes_es.KeyValue:=null;
      end else     //////   insertamos palets multiples
      begin
      cajastotales:=strtoint(lenvases_es.Text);
      cajasporpalet:=strtoint(lporpalet.Text);

      qpesadaslotessalidas.open;
      qaux.sql.clear;
      qaux.sql.add('delete from ea_pesadas_tmp where id=-2000');//+dm.qlotesidempresa.asstring);
      qaux.execsql;

       comboentradas_es.Visible:=false;
       btnuevaentrada.visible:=false;
       label61.Visible:=false;
       dbtext9.Visible:=true;
       if qdestinostipo_trabajo.asstring<>'' then
       begin
          tipotrabajo:=qdestinostipo_trabajo.asstring;
       end;
       decodedate(tfecha.Date,anyo,mes,dia);
       vanyo:=floattostr(anyo);
       vmes:=floattostr(mes);
       vdia:=floattostr(dia);
       if length(vmes)=1 then vmes:='0'+vmes;
       if length(vdia)=1 then vdia:='0'+vdia;
       vfecha:=''''+vanyo+'-'+vmes+'-'+vdia+'''';
       qparcelas.Open;
       qparcelas.Locate('codpar',qpartidasid_parcela.asstring,[locaseinsensitive,lopartialkey]);
        dm.qpesadastmp.open;
        dm.qpesadastmp.Append;
        dm.qpesadastmpid.Value:=-2000;
        dm.qpesadastmpidea.value:=0;//-2000;
        dm.qpesadastmpid_palet.value:=qpalets1codigo.asstring;
        dm.qpesadastmpnum_palets.value:=1;
        dm.qpesadastmpid_envase.value:=qpalets2codigo.asstring;
        dm.qpesadastmpnum_envases.value:=cajasporpalet;
        dm.qpesadastmpiddestino.Value:=qdestinosid.AsInteger;
        dm.qpesadastmpdestino.value:=qdestinosnombre.asstring;
        edpeso_es.Text:=StringReplace(edpeso_es.text, '.', ',',[rfReplaceAll, rfIgnoreCase]);
        ltaraanterior.Text:=StringReplace(ltaraanterior.text, '.', ',',[rfReplaceAll, rfIgnoreCase]);
        dm.qpesadastmppeso_bruto.value:=strtofloat(edpeso_es.text);
        dm.qpesadastmptara0.value:=STRTOFLOAT(ltaraanterior.Text);
        ltara.Text:=StringReplace(ltara.text, '.', ',',[rfReplaceAll, rfIgnoreCase]);
        dm.qpesadastmptara.value:=strtofloat(ltara.text);
        lneto.Text:=StringReplace(lneto.text, '.', ',',[rfReplaceAll, rfIgnoreCase]);
        dm.qpesadastmppeso_neto.value:=strtofloat(lneto.Text);
        lventa_es.Text:=StringReplace(lventa_es.text, '.', ',',[rfReplaceAll, rfIgnoreCase]);
        dm.qpesadastmppeso_neto_teorico.value:=strtofloat(lventa_es.text);
        dm.qpesadastmppeso_medio.Value:=dm.qpesadastmppeso_neto.AsFloat/dm.qpesadastmpnum_envases.AsInteger;
        dm.qpesadastmptemperatura.value:=strtofloat(ltemperatura.Text);
        dm.qpesadastmpcalibre.value:=0;
        dm.qpesadastmporigen.Value:=qpartidasid_parcela.Asstring;
        dm.qpesadastmphora.value:=time();
        dm.qpesadastmpfecha.Value:=tfecha.date;
        dm.qpesadastmpfechatrabajo.value:=tfecha.Date;
        vpesobruto:=Format ('%.*d', [5,trunc(dm.qpesadastmppeso_bruto.AsFloat*10)]);
        vpesoneto:=Format ('%.*d', [5,trunc(dm.qpesadastmppeso_neto.AsFloat*10)]);
        vcajas:=Format ('%.*d', [3,dm.qpesadastmpnum_envases.asinteger]);
        dm.qpesadastmpcea.Value:=vanyo+vmes+vdia+vpesobruto+vpesoneto+vcajas;
        dm.qpesadastmpidorigen.value:=qorigenesid.Asinteger;
        dm.qpesadastmporigen.value:=qorigenesnombre.AsString;
        dm.qpesadastmpgen_caja.Value:=0;
        dm.qpesadastmpcosto.Value:=qparcelascoste_kg_ref.AsFloat;
        dm.qpesadastmplote.Value:=dm.qlotessalidaslote.AsInteger;
        dm.qpesadastmpmprima.Value:=qmprimasid.AsString;
        dm.qpesadastmptipo_trabajo.value:='';//tipotrabajo;
        dm.qpesadastmpidempresa.value:=dm.qlotessalidasidempresa.asinteger;
        dm.qpesadastmpparcela.value:=dm.qlotessalidasorigen.AsString;
        dm.qpesadastmppuesto.Value:=strtoint(tidbascula);
        dm.qpesadastmpOBSERVACIONES.value:=datetostr(tfecha.Date)+'-'+dm.qpesadastmpparcela.AsString+'-->'+dm.qpesadastmpdestino.asstring;;
        qaux.SQL.Clear;
        qaux.SQL.Add('select sum(precio) from ea_materiales_tmp where idea=-2000 and idea2=0');
        qaux.open;
        dm.qpesadastmpcosto_materiales.value:=qaux.Fields[0].asfloat;

    ///actualizo la parcela y el lote detallado

        dm.qaux.SQL.Clear;
        dm.qaux.sql.add('select count(*) from lotes_pesadas_tmp where ide='+dm.qpesadastmpidempresa.asstring+' and idea=-2000 and idea2=0');
        dm.qaux.open;
        if dm.qaux.Fields[0].asinteger>0 then
        begin
           dm.qaux.Close;
           dm.qaux.SQL.Clear;
           dm.qaux.sql.add('select distinct(lp.lote),l.parcela from lotes_pesadas_tmp lp,lotes l where lp.ide=l.idempresa and lp.lote=l.codigo and ide='+dm.qpesadastmpidempresa.asstring+' and idea=-2000 and idea2=0');
           dm.qaux.open;
           dm.qaux.First;
           dm.qpesadastmp.edit;
           while not dm.qaux.Eof do
           begin
             dm.qpesadastmplotes_detalle.Value:=dm.qpesadastmplotes_detalle.AsString+dm.qaux.Fields[0].AsString+'/';
             dm.qpesadastmpparcela.Value:=dm.qaux.Fields[1].AsString+'/';
             dm.qaux.Next;
           end;
        end;
        tcea:='';
        tcea:=dm.qpesadastmpCEA.AsString;
        dm.qpesadastmp.Post;
        while cajastotales>=cajasporpalet do
        begin

        qaux.SQL.Clear;
        qaux.SQL.Add('insert into ea_pesadas select * from vea_pesadas_tmp where idea=0');
        qaux.ExecSQL;
        qaux.Close;
        qaux.SQL.Clear;
        qaux.SQL.Add('select idempresa,id,idea from ea_pesadas where cea='+''''+tcea+''''+' order by id desc limit 1');
        qaux.open;
        tidea:=qaux.fields[1].asstring;
        tidea2:=qaux.fields[2].asstring;
        qaux.SQL.Clear;
        qaux.SQL.Add('update lotes_pesadas_tmp set idea='+tidea+',idea2='+tidea2+' where idea=-2000 and idea2=0');// and es_entrada=1');
        qaux.ExecSQL;

        qaux.SQL.Clear;
        qaux.SQL.Add('update ea_materiales_tmp set idea='+tidea+',idea2='+tidea2+' where idea=-2000 and idea2=0');// and es_entrada=1');
        qaux.ExecSQL;

        qaux.SQL.Clear;
        qaux.SQL.Add('insert into lotes_pesadas select * from v_lotespesadastmp where idea='+tidea+' and idea2='+tidea2);// where es_entrada=1');
        qaux.ExecSQL;

        qaux.SQL.Clear;
        qaux.SQL.Add('insert into ea_materiales select * from v_eamaterialestmp where idea='+tidea+' and idea2='+tidea2);// where es_entrada=1');
        qaux.ExecSQL;
        qaux.SQL.Clear;
        qaux.SQL.Add('update lotes_pesadas_tmp set idea=-2000,idea2=0 where idea='+tidea+' and idea2='+tidea2);// and es_entrada=1');
        qaux.ExecSQL;

        qaux.SQL.Clear;
        qaux.SQL.Add('update ea_materiales_tmp set idea=-2000,idea2=0 where idea='+tidea+' and idea2='+tidea2);// and es_entrada=1');
        qaux.ExecSQL;
        cajastotales:=cajastotales-cajasporpalet;
        lenvases_es.Text:=inttostr(cajastotales);
      end;
      if (cajastotales>0) and (cajastotales<cajasporpalet) then
      begin
        cajasporpalet:=cajastotales;
        lporpalet.text:=inttostr(cajasporpalet);
        btborrarlote.Click;
        btnuevolote.Click;
        btguardar.Click;
      end;

        qaux.SQL.Clear;
        qaux.SQL.Add('delete from lotes_pesadas_tmp where puesto='+tidbascula);// where es_entrada=1');
        qaux.ExecSQL;

        qaux.SQL.Clear;
        qaux.SQL.Add('delete from ea_materiales_tmp where puesto='+tidbascula);;// where es_entrada=1');
        qaux.ExecSQL;


        qpesadaslotessalidas.Refresh;
        timer1.Enabled:=true;
        timer2.Enabled:=true;
        dm.qpesadassalidas.Refresh;
        dm.qpesadassalidas.First;
        plotes.Visible:=false;
        plotes2.Visible:=false;
        combopalets_es.KeyValue:=null;
        comboenvases_es.KeyValue:=null;
        combovariedad_es.KeyValue:=null;
        comboorigen_es.KeyValue:=null;
        combodestino_es.KeyValue:=null;
        combolotes_es.KeyValue:=null;

      end;



    end;
    btguardar.Visible:=false;
    ltaraanterior.Text:='0';

end;

procedure Tgeneral.btguardarentradaClick(Sender: TObject);
begin
    qentradashora.Value:=time();
    qentradaside.Value:=1;
    qentradasfecha.Value:=tfecha.Date;
    qentradashora.Value:=time();
    qentradaspartida.Value:=qpartidasid.asinteger;
    qentradasnum_palets.Value:=0;
    qentradasnum_cajas.Value:=0;
    qentradaspeso_bruto.Value:=0;
    qentradaspeso_neto.Value:=0;
    qentradasmprima.Value:=qpartidasid_mprimas.asstring;
    qentradas.Post;
    qentradas.Refresh;
    qentradas.First;

    timer1.Enabled:=true;
    timer2.Enabled:=true;
end;

procedure Tgeneral.dsentradasStateChange(Sender: TObject);
begin
    if dsentradas.State in [dsinsert] then
    begin
       vehiculos.Open;
    end;
    if dsentradas.State in [dsedit,dsbrowse] then
    begin
       vehiculos.close;

    end;
end;

procedure Tgeneral.dspartidasDataChange(Sender: TObject; Field: TField);
begin
if qpartidas.RecordCount>0 then
    begin
        qentradas.Close;
        qentradas.SQL.Clear;
        qentradas.SQL.Add('select * from entradas_almacen where partida='+qpartidasid.asstring+' order by id desc ');
        qentradas.Open;
    end;
end;

procedure Tgeneral.dsqpedidospendientesDataChange(Sender: TObject;
  Field: TField);
begin
    dtlinpedidos.Close;
    dtlinpedidos.SQL.Clear;
    dtlinpedidos.SQL.Add('select * from pedidosdetalle where id='+qpedidospendientesid.AsString);
    dtlinpedidos.Open;
    qenvasados2.Close;
    qenvasados2.SQL.Clear;
    qenvasados2.SQL.Add('select * from ea_pesadas where iddestino in (select id from almacenes where final=1) and idpedido='+qpedidospendientesid.AsString+' ORDER BY `id`  DESC');
    qenvasados2.Open;

end;

procedure Tgeneral.dsqpesadaslotesDataChange(Sender: TObject; Field: TField);
begin
    tbultos.Text:=dm.qpesadaslotesresto_cajas.Asstring;
end;

procedure Tgeneral.dsqpesadaslotesmovDataChange(Sender: TObject; Field: TField);
begin
   qaux.Close;
   qaux.SQL.Clear;
   qaux.sql.add('select * from lotes_pesadas_tmp where puesto='+tidbascula+' and idea2='+dm.qpesadaslotesidea2.asstring);
   qaux.open;

   if qaux.RecordCount>0 then
   begin
//      btotrosdatos.Visible:=false;
      btguardar.Visible:=true;
   end else
   begin
     btguardar.Visible:=false;
//     btotrosdatos.Visible:=false;
   end;
end;

procedure Tgeneral.dsqpesadaslotessalidasDataChange(Sender: TObject;
  Field: TField);
begin
   qaux.Close;
   qaux.SQL.Clear;
   qaux.sql.add('select * from lotes_pesadas_tmp where idea=-2000 and idea2=0');
   qaux.open;

   if qaux.RecordCount>0 then
   begin
      //btotrosdatos.Visible:=false;
      btguardar.Visible:=true;
   end else
   begin
     btguardar.Visible:=false;
     //btotrosdatos.Visible:=false;
   end;
end;

procedure Tgeneral.dsqpesadaslotesentradasDataChange(Sender: TObject;
  Field: TField);
begin
   qaux.Close;
   qaux.SQL.Clear;
   qaux.sql.add('select * from lotes_pesadas_tmp where idea=-1000 and idea2=-1000 and puesto='+tidbascula);
   qaux.open;

   if qaux.RecordCount>0 then
   begin
   //   btotrosdatos.Visible:=false;
      btguardar.Visible:=true;
   end else
   begin
     btguardar.Visible:=false;
   //  btotrosdatos.Visible:=false;
   end;
end;

procedure Tgeneral.dstpartidasStateChange(Sender: TObject);
begin
    if dstpartidas.State in [dsinsert] then
    begin
        qparcelas.Open;
    qmprimas.Close;
    if rdesechos.Checked then
    begin
      qmprimas.SQL.Clear;
      qmprimas.SQL.Add('select * from materias_primas where basculas=1 and activo=1 and desechos=1 order by id');
    end;
    if renvasados.Checked then
    begin
      qmprimas.SQL.Clear;
      qmprimas.SQL.Add('select * from materias_primas where basculas=1 and activo=1 and desechos=0 order by id');
    end;
    if rentradas.Checked then
    begin
      qmprimas.SQL.Clear;
      qmprimas.SQL.Add('select * from materias_primas where basculas=1 and activo=1 order by id');
    end;
    qmprimas.Open;
    end;
    if dstpartidas.State in [dsedit,dsbrowse] then
    begin
        qparcelas.close;
        qmprimas.close;
    end;
end;

procedure Tgeneral.edpalets_esEnter(Sender: TObject);
begin
    edpalets_es.Text:='';
    teclado.Visible:=true;
    teclado.BringToFront;
    teclado.Top:=edpalets_es.Top+135;
    teclado.left:=edpalets_es.left+68;
end;

procedure Tgeneral.edpalets_esExit(Sender: TObject);
begin
   if edpalets_es.text='' then edpalets_es.Text:='1';
   teclado.Visible:=false;
   if esentrada=1 then
   begin
     if dm.qlotes.RecordCount>0 then
     begin
     end else
           begin
              showmessage('ˇˇˇ NO HAY LOTES CREADOS EN EL DIA ACTUAL ˇˇˇ');
              tfecha.SetFocus;
              edpalets_es.text:='0';
              combopalets_es.KeyValue:=null;
           end;
   end;
   if esentrada=0 then
   begin
     if dm.qlotessalidas.RecordCount>0 then
     begin
     end else
           begin
              showmessage('ˇˇˇ NO HAY LOTES CREADOS EN EL DIA ACTUAL ˇˇˇ');
              tfecha.SetFocus;
              edpalets_es.text:='0';
              combopalets_es.KeyValue:=null;
           end;
   end;

end;

procedure Tgeneral.ltemperaturaEnter(Sender: TObject);
begin
    ltemperatura.Text:='';
    teclado.Visible:=true;
    teclado.Top:=ltemperatura.Top+135;
    teclado.left:=ltemperatura.left+68;
end;

procedure Tgeneral.ltemperaturaExit(Sender: TObject);
begin
   if ltemperatura.text='' then ltemperatura.Text:='0';
   teclado.Visible:=false;
end;

procedure Tgeneral.lenvases_esEnter(Sender: TObject);
begin
    lenvases_es.Text:='';
    teclado.Visible:=true;
    teclado.Top:=lenvases_es.Top+135;
    teclado.left:=lenvases_es.Left+50+225;
end;

procedure Tgeneral.lenvases_esExit(Sender: TObject);
begin
    teclado.Visible:=false;
end;

procedure Tgeneral.lporpaletEnter(Sender: TObject);
begin
    lporpalet.Text:='';
    teclado.Visible:=true;
    teclado.Top:=lporpalet.Top+135;
    teclado.left:=lporpalet.Left+50+225;
end;

procedure Tgeneral.lporpaletExit(Sender: TObject);
begin
    teclado.Visible:=false;
    comboformatos_es.setfocus;
end;

procedure Tgeneral.ltaraanteriorEnter(Sender: TObject);
begin
    ltaraanterior.Text:='';
    teclado.Visible:=true;
    teclado.Top:=ltaraanterior.Top+135;
    teclado.left:=ltaraanterior.left+68;
end;

procedure Tgeneral.ltaraanteriorExit(Sender: TObject);
var idea2:string;
begin

    if esentrada=1 then
    begin
        qaux.close;
        qaux.sql.clear;
        qaux.sql.Add('delete from ea_materiales_tmp where idea=-1000 and idea2=-1000 and puesto='+tidbascula);
        qaux.execsql;
        qaux.close;
        qaux.sql.clear;
        qaux.sql.Add('delete from lotes_pesadas_tmp where idea=-1000 and idea2=-1000 and puesto='+tidbascula);
        qaux.execsql;
        qpesadaslotesentradas.close;
        qpesadaslotesentradas.open;
        if ltaraanterior.text='' then ltaraanterior.Text:='0';
        teclado.Visible:=false;
        qaux.Close;
        qaux.sql.clear;
        qaux.sql.Add('select sum(peso),count(*) from ea_materiales_tmp where idea=-1000 and idea2=-1000 and puesto='+tidbascula);
        qaux.open;
        if qaux.Fields[1].AsInteger>0 then ltara.Text:=qaux.Fields[0].Asstring else ltara.Text:='0';
        lneto.text:=floattostr(strtofloat(edpeso_es.Text)-strtofloat(ltara.Text)-strtofloat(ltaraanterior.Text));
    end;
    if esentrada=0 then
    begin
        qaux.close;
        qaux.sql.clear;
        qaux.sql.Add('delete from ea_materiales_tmp where idea=-2000 and idea2=0');
        qaux.execsql;
        qaux.close;
        qaux.sql.clear;
        qaux.sql.Add('delete from lotes_pesadas_tmp where idea=-2000 and idea2=0');
        qaux.execsql;
        qpesadaslotessalidas.close;
        qpesadaslotessalidas.open;
        if ltaraanterior.text='' then ltaraanterior.Text:='0';
        teclado.Visible:=false;
        qaux.Close;
        qaux.sql.clear;
        qaux.sql.Add('select sum(peso), count(*) from ea_materiales_tmp where idea=-2000 and idea2=0');
        qaux.open;
        if qaux.Fields[1].AsInteger>0 then ltara.Text:=qaux.Fields[0].Asstring else ltara.Text:='0';
        lneto.text:=floattostr(strtofloat(edpeso_es.Text)-strtofloat(ltara.Text)-strtofloat(ltaraanterior.Text));
    end;
end;

procedure Tgeneral.Edit1Enter(Sender: TObject);
begin
   tid.Text:='';
end;

procedure Tgeneral.tidEnter(Sender: TObject);
begin
    tid.Text:='';
    qaux.Close;
    qaux.SQL.Clear;
    qaux.SQL.Add('delete from ea_pesadas_tmp where puesto='+tidbascula);
    qaux.ExecSQL;
    qaux.SQL.Clear;
    qaux.SQL.Add('delete from lotes_pesadas_tmp where puesto='+tidbascula);
    qaux.ExecSQL;
    qaux.SQL.Clear;
    qaux.SQL.Add('delete from ea_materiales_tmp where puesto='+tidbascula);
    qaux.ExecSQL;
    dm.qpesadas.close;
    dm.qpesadaslotes.close;
    dm.qpesadastmp.close;
    qpesadaslotessalidas.close;
    if qpesadaslotesmov.Active then qpesadaslotesmov.close;
    teclado.Visible:=true;
    teclado.Top:=tid.Top+140;
    teclado.left:=tid.Left+145;


end;

procedure Tgeneral.tidExit(Sender: TObject);
var v_ide,v_id,v_idea,vneto,vbruto,vventa,vpesomedio,vtara,vbultos:string;
    v_bultos:integer;
    v_tara,v_taraanterior,v_pesoneto,v_pesobruto,v_pesoventa,v_pesomedio:real;
begin
    qaux.close;
    qaux.SQL.Clear;
    qaux.SQL.Add('delete from ea_pesadas_tmp where puesto='+tidbascula);
    qaux.ExecSQL;
    if tid.Text<>'' then
    begin
        timer1.Enabled:=false;
        timer2.enabled:=false;

        dm.qpesadas.Close;
        dm.qpesadas.SQL.Clear;
        dm.qpesadas.sql.Add('select * from ea_pesadas where id='+tid.Text+' and resto_cajas>0 order by idea');
        dm.qpesadas.Open;

        if dm.qpesadas.RecordCount>1 then
        begin
           comboentrada.Visible:=true;
           comboentrada.SetFocus;
           comboentrada.DropDown;
           teclado.Visible:=false;
        end;

        if dm.qpesadas.RecordCount=1 then
        begin
            v_ide:=dm.qpesadasidempresa.AsString;
            v_id:=dm.qpesadasid.AsString;
            v_idea:=dm.qpesadasidea.AsString;

            dm.qpesadaslotes.Close;
            dm.qpesadaslotes.SQL.Clear;
            dm.qpesadaslotes.sql.Add('select * from lotes_pesadas where ide='+v_ide+' and idea='+v_id+' and idea2='+v_idea);
            dm.qpesadaslotes.Open;
            if dm.qpesadasresto_cajas.asfloat>0 then
            begin
                dm.qpesadastmp.Close;
                comboorigen.KeyValue:=dm.qpesadasiddestino.asstring;
                numpalets:=dm.qpesadasnum_palets.Asinteger;
                restocajas:=dm.qpesadasresto_cajas.asinteger;
                combodestino.KeyValue:=null;
                pesobruto:=dm.qpesadaspeso_bruto.AsFloat;
                combodestino.SetFocus;
                qaux.close;
                qaux.SQL.Clear;
                qaux.SQL.Add('insert into ea_pesadas_tmp select *,'+tidbascula+' as puesto from ea_pesadas where idempresa='+v_ide+' and id='+v_id+' and idea='+v_idea);
                qaux.ExecSQL;
                dm.qpesadastmp.Open;
            end else
            begin
                showmessage('ENTRADA USADA POR COMPLETO');
                tid.SetFocus;
            end;
            teclado.Visible:=false;
            dm.qpesadastmp.Close;
            dm.qpesadastmp.Open;

        end;
        if dm.qpesadas.RecordCount=0 then
            begin
                showmessage('ENTRADA NO ENCONTRADA');
                tid.SetFocus;
            end;
    end else
    begin
        comboorigen.KeyValue:=null;
        comboorigen.SetFocus;
        combodestino.KeyValue:=null;
    end;
    teclado.Visible:=false;

end;

procedure Tgeneral.edpeso_esChange(Sender: TObject);
var tara,tara2,bruto,neto:real;
    bultos:integer;
begin
    //timer1.Enabled:=false;
    bultos:=strtoint(lbultos.text);
    if edpeso_es.Text='' then bruto:=0 else bruto:=strtofloat(edpeso_es.text);
    tara:=strtofloat(ltara.text);
    tara2:=strtofloat(ltaraanterior.Text);
    neto:=bruto-tara-tara2;
    lneto.Text:=floattostr(neto);


end;

procedure Tgeneral.edpeso_esEnter(Sender: TObject);
begin
    timer1.Enabled:=false;
    edpeso_es.Text:='';
    teclado.Visible:=true;
    teclado.BringToFront;
    teclado.Top:=edpeso_es.Top+400;
    teclado.left:=edpeso_es.left+60+450;
end;

procedure Tgeneral.edpeso_esExit(Sender: TObject);
begin
    if edpeso_es.Text='' then edpeso_es.Text:='0';
    teclado.Visible:=false;
    combolotes_es.setfocus;
end;

procedure Tgeneral.edpeso_esKeyPress(Sender: TObject; var Key: Char);
begin
     if (key='.') then key:=',';
end;

procedure Tgeneral.FormKeyPress(Sender: TObject; var Key: Char);
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='lprecio' then key:=',';
       if  (activecontrol as tedit).Name='limporteanticipos' then key:=',';
       if  (activecontrol as tedit).Name='limporteanticipos' then key:=',' ;
       if  (activecontrol as tedit).Name='ltaraanterior' then key:=',';
       if  (activecontrol as tedit).Name='ed_peso_es' then key:=',';
       if  (activecontrol as tedit).Name='ed_palets_es' then key:=',';
       if  (activecontrol as tedit).Name='ltemperatura' then key:=',';

    end;
    if (key=#13) then
    begin
        Perform(WM_NextDLGCtl,0,0);
        key:=#0;
    end;

end;

procedure Tgeneral.FormShow(Sender: TObject);
var F: TextFile;
    sLinea,thost,tuser,tpass,tpuerto,tbaudios,tparidad,tbitparada,tbd:string;

    hora1,hora2,hora3:ttime;

begin
  visor:='';
  estable:=false;

  leer:=true;
  AssignFile( F, ExtractFilePath( Application.ExeName ) + 'basculas.ini' );
  Reset( F );
  Memo1.Clear;
  while not Eof( F ) do
  begin
    ReadLn( F, sLinea );
    Memo1.Lines.Add( sLinea );
  end;

  CloseFile( F );
    thost:=memo1.lines[0];
    tuser:=memo1.lines[1];
    tpass:=memo1.lines[2];
    tpuerto:=memo1.lines[3];
    ttipobascula:=memo1.Lines[4];
    tidbascula:=memo1.Lines[5];
    tbd:=memo1.Lines[6];

    DM.dbagrigest2.Connected:=false;
    DM.dbagrigest2.HostName:=thost;
    DM.dbagrigest2.User:=tuser;
    DM.dbagrigest2.Password:=tpass;
    dm.dbagrigest2.Database:=tbd;
    DM.dbagrigest2.connected:=true;

    //puerto1.Connected:=FALSE;
    //puerto1.Close;
    puerto2.Connected:=FALSE;
    puerto2.Close;
    tfecha.Date:=date();

    if ttipobascula='0' then
    begin
       puerto2.BaudRate:=br9600;
       puerto2.DataBits:=dbEight;
       puerto2.Parity.Bits:=prnone;
       puerto2.Port:='COM'+tpuerto;
       puerto2.StopBits:=sbOneStopBit;
       puerto2.TriggersOnRxChar:=true;
       comdata1.ComPort:=nil;
       comdata2.ComPort:=nil;
       try
         puerto2.Open;
       except on error: exception do
         showmessage('Bascula no conectada en puerto COM'+tpuerto);
       end;
    end;
    if ttipobascula='1' then
    begin
       puerto2.BaudRate:=br9600;
       puerto2.DataBits:=dbEight;
       puerto2.Parity.Bits:=prnone;
       puerto2.Port:='COM'+tpuerto;
       puerto2.StopBits:=sbOneStopbit;
       puerto2.TriggersOnRxChar:=true;
       comdata1.ComPort:=nil;
       comdata2.ComPort:=nil;
       try
         puerto2.Open;
       except on error: exception do
         showmessage('Bascula no conectada en puerto COM'+tpuerto);
       end;
    end;
 {   if ttipobascula='2' then   /// cooperativa novelda entradas
    begin

       puerto2.BaudRate:=br9600;
       puerto2.DataBits:=dbEight;
       puerto2.Parity.Bits:=prnone;
       puerto2.Port:='COM'+tpuerto;
       puerto2.StopBits:=sbTwoStopbits;
       puerto2.TriggersOnRxChar:=false;
       comdata1.ComPort:=puerto2;
       comdata1.MaxBufferSize:=18;
       comdata1.Size:=18;
       comdata1.startstring:='= ';
       comdata1.StopString:=#13;
       comdata2.ComPort:=puerto2;
       comdata2.MaxBufferSize:=18;
       comdata2.Size:=18;
       comdata2.startstring:='=-';
       comdata2.StopString:=#13;
       try
         puerto2.Open;
       except on error: exception do
         showmessage('Bascula no conectada en puerto COM'+tpuerto);
       end;
    end;}
    if ttipobascula='2' then
    begin
       puerto2.BaudRate:=br9600;
       puerto2.DataBits:=dbEight;
       puerto2.Parity.Bits:=prnone;
       puerto2.Port:='COM'+tpuerto;
       puerto2.StopBits:=sbTwoStopbits;
       puerto2.TriggersOnRxChar:=true;
       comdata1.ComPort:=nil;
       comdata2.ComPort:=nil;
       try
         puerto2.Open;
       except on error: exception do
         showmessage('Bascula no conectada en puerto COM'+tpuerto);
       end;
    end;
    if ttipobascula='3' then           // enrique bascula de entradas
    begin
       puerto2.BaudRate:=br2400;
       puerto2.DataBits:=dbSeven;
       puerto2.Parity.Bits:=prnone;
       puerto2.Port:='COM'+tpuerto;
       puerto2.StopBits:=sbTwoStopbits;
       puerto2.TriggersOnRxChar:=true;
       comdata1.ComPort:=nil;
       comdata2.ComPort:=nil;
       try
         puerto2.Open;
       except on error: exception do
         showmessage('Bascula no conectada en puerto COM'+tpuerto);
       end;
    end;

    if ttipobascula='4' then
    begin
       puerto2.BaudRate:=br9600;
       puerto2.DataBits:=dbEight;
       puerto2.Parity.Bits:=prnone;
       puerto2.Port:='COM'+tpuerto;
       puerto2.StopBits:=sbTwoStopbits;
       puerto2.TriggersOnRxChar:=true;
       comdata1.ComPort:=nil;
       comdata2.ComPort:=nil;
       try
         puerto2.Open;
       except on error: exception do
         showmessage('Bascula no conectada en puerto COM'+tpuerto);
       end;
    end;
    if ttipobascula='5' then
    begin
       puerto2.BaudRate:=br9600;
       puerto2.DataBits:=dbEight;
       puerto2.Parity.Bits:=prnone;
       puerto2.Port:='COM'+tpuerto;
       puerto2.StopBits:=sbTwoStopbits;
       puerto2.TriggersOnRxChar:=true;
       comdata1.ComPort:=nil;
       comdata2.ComPort:=nil;
       try
         puerto2.Open;
       except on error: exception do
         showmessage('Bascula no conectada en puerto COM'+tpuerto);
       end;
    end;
    if ttipobascula='6' then
    begin
       puerto2.BaudRate:=br9600;
       puerto2.DataBits:=dbEight;
       puerto2.Parity.Bits:=prnone;
       puerto2.Port:='COM'+tpuerto;
       puerto2.StopBits:=sboneStopbit;
       puerto2.TriggersOnRxChar:=false;
       comdata1.ComPort:=puerto2;
       comdata2.ComPort:=puerto2;
       try
         puerto2.Open;
       except on error: exception do
         showmessage('Bascula no conectada en puerto COM'+tpuerto);
       end;
    end;
    if ttipobascula='7' then
    begin

       puerto2.BaudRate:=br9600;
       puerto2.DataBits:=dbEight;
       puerto2.Parity.Bits:=prnone;
       puerto2.Port:='COM'+tpuerto;
       puerto2.StopBits:=sboneStopbit;
       puerto2.TriggersOnRxChar:=false;
       comdata1.ComPort:=puerto2;
       comdata1.MaxBufferSize:=8;
       comdata1.Size:=8;
       comdata1.startstring:='= ';
       comdata1.StopString:=#13;
       comdata2.ComPort:=puerto2;
       comdata2.MaxBufferSize:=8;
       comdata2.Size:=8;
       comdata2.startstring:='=-';
       comdata2.StopString:=#13;




       try
         puerto2.Open;
       except on error: exception do
         showmessage('Bascula no conectada en puerto COM'+tpuerto);
       end;
    end;
    dm.qempresas.Open;
    pide:=dm.qempresasid.asinteger;
    pseparartraza_es:=dm.qempresasseparartraza_e_s.AsInteger;
end;


procedure Tgeneral.gridpesadasalidasDrawColumnCell(Sender: TObject;
  const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
    if dm.qpesadassalidaspeso_neto.AsFloat<dm.qpesadassalidaspeso_neto_teorico.AsFloat then
    begin
        gridpesadasalidas.Canvas.brush.Color := rojo;
    end;
   gridpesadasalidas.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;

procedure Tgeneral.btnuevaentradaClick(Sender: TObject);
begin
    fentradas := Tfentradas.Create(nil);
    try
      fentradas.showmodal();
    finally
      fentradas.Free;
    end;
end;

procedure Tgeneral.Puerto2RxBuf(Sender: TObject; const Buffer; Count: Integer);
var str:string;
begin
if ttipobascula='2' then
    begin
      puerto2.Readstr(Str, Count);
    end;

if ttipobascula='4' then
    begin
      puerto2.Readstr(Str, Count);
    end;
if ttipobascula='7' then
    begin
      puerto2.Readstr(Str, Count);
    end;
end;

procedure Tgeneral.Puerto2RxChar(Sender: TObject; Count: Integer);
var
  Str: String;
  peso2:real;
  letra,x:integer;
begin

if ttipobascula='1' then //// enrique salidas br80
begin
if count>10 then
begin
  puerto2.ReadStr(Str, Count);
  str:= StringReplace(str, '.', ',',[rfReplaceAll, rfIgnoreCase]);
  str:= StringReplace(str, '= ', '',[rfReplaceAll, rfIgnoreCase]);
  delete(str,8,length(str)-7);
  cadena:=str;
  if visor=cadena then estable:=true else estable:=false;

  visor:=cadena;
  try
    peso2:=strtofloat(cadena);
    cadena:=floattostr(peso2);
    lpeso2.caption :=cadena;
    except
        on error: exception do
        begin
           peso2:=0;
        end;
    end;
end;
end;

if ttipobascula='2' then   // cooperativa novelda entradas
begin
  if count>=10 then
  begin
      puerto2.Readstr(Str, count);
      str:= StringReplace(str, '.', ',',[rfReplaceAll, rfIgnoreCase]);
      str:= StringReplace(str, '=','',[rfReplaceAll, rfIgnoreCase]);
      str:= StringReplace(str, '+', '',[rfReplaceAll, rfIgnoreCase]);
      if str[1]=#2 then
      begin
      cadena:=str;
      cadena:=copy(cadena,6,5);
      if visor=cadena then
      begin
        estable:=true;
        try
        peso2:=strtofloat(cadena);
        except
              on error: exception do
              begin
                 peso2:=0;
                 cadena:='------';
              end;
        end;
        cadena:=floattostr(peso2);
        lpeso2.caption:=cadena;
      end
      else
          begin
           estable:=false;
          end;
      visor:=cadena;
     end;
   end;
end;

if ttipobascula='0' then /// don ciro bascula entradas dibal 2 digitos o *100
begin
if count>10 then
begin
  puerto2.ReadStr(Str, Count);
  str:= StringReplace(str, '.', ',',[rfReplaceAll, rfIgnoreCase]);
  str:= StringReplace(str, '= ', '',[rfReplaceAll, rfIgnoreCase]);
  delete(str,8,length(str)-7);
  cadena:=str;
  if visor=cadena then estable:=true else estable:=false;

  visor:=cadena;
  try
    peso2:=strtofloat(cadena);
    peso2:=peso2*100;
    cadena:=floattostr(peso2);
    lpeso2.caption :=cadena;
    except
        on error: exception do
        begin
           peso2:=0;
        end;
    end;
end;
end;
if ttipobascula='3' then      ////   enrique entradas
begin
  cadena:='';
  puerto2.ReadStr(Str, 10);
  str:= StringReplace(str, '.', ',',[rfReplaceAll, rfIgnoreCase]);
  if length(str)>5 then
  begin
      for x := 1 to 9 do
      begin

        if str[x] in ['0','1','2','3','4','5','6','7','8','9',','] then
        begin
           cadena:=cadena+str[x];
        end
      end;
 try
    peso2:=strtofloat(cadena);
    except
        on error: exception do
        begin
           peso2:=0;
        end;
    end;

  lpeso2.caption :=floattostr(peso2);
  end;
end;

if ttipobascula='4' then
begin
    cadena:='';
    puerto2.ReadStr(Str, 10);
    str:= StringReplace(str, '.', ',',[rfReplaceAll, rfIgnoreCase]);

    if length(str)>5 then
    begin
        for x := 1 to 9 do
        begin

          if str[x] in ['0','1','2','3','4','5','6','7','8','9',','] then
          begin
             cadena:=cadena+str[x];
          end
        end;

    try
      peso2:=strtofloat(cadena);
      except
          on error: exception do
          begin
             peso2:=0;
          end;
      end;

    lpeso2.caption :=floattostr(peso2);

    end;
  end;
if ttipobascula='5' then // entradas la torre
begin
    cadena:='';
    puerto2.ReadStr(Str, 10);
    str:= StringReplace(str, '.', ',',[rfReplaceAll, rfIgnoreCase]);

    if length(str)>5 then
    begin
        for x := 1 to 9 do
        begin

          if str[x] in ['0','1','2','3','4','5','6','7','8','9',','] then
          begin
             cadena:=cadena+str[x];
          end
        end;
    try
      peso2:=strtofloat(cadena)*1000;
      except
          on error: exception do
          begin
             peso2:=0;
          end;
      end;

    lpeso2.caption :=floattostr(peso2);

    end;
  end;

end;

procedure Tgeneral.rentradasClick(Sender: TObject);
var anyo,mes,dia:word;
      vanyo,vmes,vdia,vfecha:string;
begin
   timer1.Enabled:=true;
   eporpalet.Visible:=false;
   lporpalet.Visible:=false;
   lgrupos.Visible:=true;
   combogrupos.Visible:=true;
   timepedidos.Enabled:=false;
   pexpediciones.Visible:=false;
   pexpedicionesdetalle.Visible:=false;

   gridlotestmp.DataSource:=dsqpesadaslotesentradas;
   plotes.Visible:=false;
   plotes2.Visible:=false;
   esentrada:=1;
   esmultiple:=0;
   //tfechatrabajo.Date:=tfecha.Date;
   decodedate(tfecha.Date,anyo,mes,dia);
   vanyo:=floattostr(anyo);
   vmes:=floattostr(mes);
   vdia:=floattostr(dia);
   if length(vmes)=1 then vmes:='0'+vmes;
   if length(vdia)=1 then vdia:='0'+vdia;
   vfecha:=''''+vanyo+'-'+vmes+'-'+vdia+'''';

  Pbajo.Visible:=true;

  combolotes_es.ListField:='';
  combolotes_es.KeyField:='';
  combolotes_es.ListSource:=dm.dsqlotes;
  combolotes_es.ListField:='codigo;parcela;mprima';
  combolotes_es.KeyField:='codigo';
  comboenvases_es.ListSource:=dscajas;

  PEntradasDetalle.Visible:=true;
  PSalidasdetalle.Visible:=false;
  Pentradassalidas.Visible:=true;
  porigenmatprima.Visible:=false;
  comboentradas_es.Visible:=true;
  btnuevaentrada.visible:=true;
  label61.Visible:=true;
  dbtext9.Visible:=true;
  Petiquetas.Visible:=true;
  petiquetas2.Visible:=false;

   qpartidas.Close;
   dm.qlotes.prepare;
   dm.qlotes.ParamByName('PFECHA').AsDate:=tfecha.Date;
   if dm.qlotes.Active then dm.qlotes.Refresh else dm.qlotes.Open;

   qpartidas.prepare;
   qpartidas.parambyname('PFECHA').AsDate:=tfecha.Date; //SQL.Add('select * from partidas where fecha='+vfecha+' order by id desc');
   if qpartidas.active then qpartidas.Refresh else qpartidas.Open;

   if qpartidas.RecordCount>0 then
   begin
    qentradas.Close;
    qentradas.SQL.Clear;
    qentradas.SQL.Add('select * from entradas_almacen where partida='+qpartidasid.asstring+' order by id desc ');
    qentradas.Open;
   end else qentradas.close;


  dm.qpesadasentradas.close;
  dm.qpesadasentradas.sql.clear;
  dm.qpesadasentradas.SQL.Add('select * from v_ea_pesadaslotes where idea>0 and fecha='+vfecha+' order by id desc' );
  dm.qpesadasentradas.Open;

  qpalets1.Open;
  qcajas.Open;
  qformatoscajas.MasterSource:=dscajas;
  qformatoscajas.Open;
  qcalibres.open;
  qdestinos.Open;
    qmprimas.Close;
    if rdesechos.Checked then
    begin
      qmprimas.SQL.Clear;
      qmprimas.SQL.Add('select * from materias_primas where basculas=1 and activo=1 and desechos=1 order by id');
    end;
    if renvasados.Checked then
    begin
      qmprimas.SQL.Clear;
      qmprimas.SQL.Add('select * from materias_primas where basculas=1 and activo=1 and desechos=0 order by id');
    end;
    if rentradas.Checked then
    begin
      qmprimas.SQL.Clear;
      qmprimas.SQL.Add('select * from materias_primas where basculas=1 and activo=1 order by id');
    end;
    qmprimas.Open;
  dm.qlotessalidas.Open;
  qaux.sql.clear;
  qaux.sql.add('delete from ea_pesadas_tmp where id=-1000 and puesto='+tidbascula);//+dm.qlotesidempresa.asstring);
  qaux.execsql;
  qaux.sql.clear;
  qaux.sql.add('delete from lotes_pesadas_tmp where idea=-1000 and puesto='+tidbascula);// where es_entrada=1');//+dm.qlotesidempresa.asstring);
  qaux.execsql;
  qaux.sql.clear;
  qaux.sql.add('delete from ea_materiales_tmp where idea=-1000 and puesto='+tidbascula);// where es_entrada=1');//+dm.qlotesidempresa.asstring);
  qaux.execsql;
  qentradas.open;
  dm.qpesadastmp.Open;
  qgrupos.Open;
  combolotes_es.ListField:='';
  combolotes_es.KeyField:='';
  combolotes_es.ListSource:=dm.dsqlotes;
  combolotes_es.ListField:='codigo;parcela;mprima';
  combolotes_es.KeyField:='codigo';
  combodestino_es.KeyValue:=null;
  combolotes_es.KeyValue:=null;
  comboenvases_es.KeyValue:=null;
  comboformatos_es.KeyValue:=null;
  combocalibre_es.KeyValue:=null;
  comboentradas_es.KeyValue:=null;
  combopalets_es.KeyValue:=null;
  combogrupos.KeyValue:=null;

end;

procedure Tgeneral.renvasadosClick(Sender: TObject);
var anyo,mes,dia:word;
      vanyo,vmes,vdia,vfecha,vfecha2:string;
begin
   timer1.Enabled:=true;
   eporpalet.Visible:=false;
   lporpalet.Visible:=false;
   timepedidos.Enabled:=false;
   lgrupos.Visible:=false;
   combogrupos.Visible:=false;
   pexpediciones.Visible:=false;
   pexpedicionesdetalle.Visible:=false;
   gridlotestmp.DataSource:=dsqpesadaslotessalidas;
   esentrada:=0;
   esmultiple:=0;
   plotes.Visible:=false;
   plotes2.Visible:=false;
   decodedate(tfecha.Date,anyo,mes,dia);
   vanyo:=floattostr(anyo);
   vmes:=floattostr(mes);
   vdia:=floattostr(dia);
   if length(vmes)=1 then vmes:='0'+vmes;
   if length(vdia)=1 then vdia:='0'+vdia;
   vfecha:=''''+vdia+'/'+vmes+'/'+vanyo+'''';//+'/'+vmes+'/'+vdia;
   decodedate(tfecha.Date,anyo,mes,dia);
   vanyo:=floattostr(anyo);
   vmes:=floattostr(mes);
   vdia:=floattostr(dia);
   if length(vmes)=1 then vmes:='0'+vmes;
   if length(vdia)=1 then vdia:='0'+vdia;
   vfecha2:=''''+vanyo+'-'+vmes+'-'+vdia+'''';

   if dm.qlotes_pesadas.Active=true then dm.qlotes_pesadas.Refresh;

  Pmedio.Visible:=true;
  Pbajo.Visible:=true;
  Pmovimientos.visible:=false;
  pentradassalidas.Visible:=true;
  porigenmatprima.Visible:=true;
  PEntradasDetalle.Visible:=false;
  PSalidasDetalle.Visible:=true;
  Petiquetas.Visible:=false;
  Petiquetas2.Visible:=true;
  comboentradas_es.Visible:=false;
  btnuevaentrada.visible:=false;
  label61.Visible:=false;
  dbtext9.Visible:=false;
  qorigenes.Close;
  qorigenes.SQL.Clear;
  qorigenes.sql.Add('select * from almacenes where activo=1 and produccion=1 order by nombre');
  qorigenes.Open;
  qdestinos.Open;
  combolotes_es.ListField:='';
  combolotes_es.KeyField:='';
  combolotes_es.ListSource:=dm.dsqlotessalidas;
  combolotes_es.ListField:='lote;fecha;MPRIMA;origen;merma';
  combolotes_es.KeyField:='lote';
  comboenvases_es.ListSource:=dsqpalets2;
  qaux.sql.clear;
  qaux.sql.add('delete from ea_pesadas_tmp where idea<=0');
  qaux.execsql;//+dm.qlotesidempresa.asstring);
  qaux.SQL.Clear;
  qaux.sql.add('delete from lotes_pesadas_tmp where idea2<=0');// where es_entrada=0');//+dm.qlotesidempresa.asstring);
  qaux.execsql;
  qaux.sql.clear;
  qaux.sql.add('delete from ea_materiales_tmp where idea2<=0');// where es_entrada=0');//+dm.qlotesidempresa.asstring);
  qaux.execsql;

  dm.qpesadassalidas.close;
  dm.qpesadassalidas.sql.clear;
  dm.qpesadassalidas.SQL.Add('select * from v_ea_pesadaslotes where idea<=0 and fecha='+vfecha2+' order by id desc' );
  dm.qpesadassalidas.Open;
  qpalets1.open;
  qpalets2.Open;
    qmprimas.Close;
    if rdesechos.Checked then
    begin
      qmprimas.SQL.Clear;
      qmprimas.SQL.Add('select * from materias_primas where basculas=1 and activo=1 and desechos=1 order by id');
    end;
    if renvasados.Checked then
    begin
      qmprimas.SQL.Clear;
      qmprimas.SQL.Add('select * from materias_primas where basculas=1 and activo=1 and desechos=0 order by id');
    end;
    if rentradas.Checked then
    begin
      qmprimas.SQL.Clear;
      qmprimas.SQL.Add('select * from materias_primas where basculas=1 and activo=1 order by id');
    end;
    qmprimas.Open;
  qformatoscajas.MasterSource:=dsqpalets2;
  qformatoscajas.open;
  qcalibres.Open;
  comboorigen_es.KeyValue:=null;
  combodestino_es.KeyValue:=null;
  combovariedad_es.KeyValue:=null;
  combolotes_es.KeyValue:=null;
  comboenvases_es.KeyValue:=null;
  comboformatos_es.KeyValue:=null;
  combocalibre_es.KeyValue:=null;
  comboentradas_es.KeyValue:=null;
  combopalets_es.KeyValue:=null;
  qpartidas.Close;

end;

procedure Tgeneral.rmultiplesClick(Sender: TObject);
var anyo,mes,dia:word;
      vanyo,vmes,vdia,vfecha,vfecha2:string;
begin
   timer1.Enabled:=false;
   eporpalet.Visible:=true;
   lporpalet.Visible:=true;
   timepedidos.Enabled:=false;
   pexpediciones.Visible:=false;
   pexpedicionesdetalle.Visible:=false;
   gridlotestmp.DataSource:=dsqpesadaslotessalidas;
   esentrada:=0;
   esmultiple:=1;
   plotes.Visible:=false;
   plotes2.Visible:=false;
   decodedate(tfecha.Date,anyo,mes,dia);
   vanyo:=floattostr(anyo);
   vmes:=floattostr(mes);
   vdia:=floattostr(dia);
   if length(vmes)=1 then vmes:='0'+vmes;
   if length(vdia)=1 then vdia:='0'+vdia;
   vfecha:=''''+vdia+'/'+vmes+'/'+vanyo+'''';//+'/'+vmes+'/'+vdia;
   decodedate(tfecha.Date,anyo,mes,dia);
   vanyo:=floattostr(anyo);
   vmes:=floattostr(mes);
   vdia:=floattostr(dia);
   if length(vmes)=1 then vmes:='0'+vmes;
   if length(vdia)=1 then vdia:='0'+vdia;
   vfecha2:=''''+vanyo+'-'+vmes+'-'+vdia+'''';

   if dm.qlotes_pesadas.Active=true then dm.qlotes_pesadas.Refresh;

  Pmedio.Visible:=true;
  Pbajo.Visible:=true;
  Pmovimientos.visible:=false;
  pentradassalidas.Visible:=true;
  porigenmatprima.Visible:=true;
  PEntradasDetalle.Visible:=false;
  PSalidasDetalle.Visible:=true;
  Petiquetas.Visible:=false;
  Petiquetas2.Visible:=true;
  comboentradas_es.Visible:=false;
  btnuevaentrada.visible:=false;
  label61.Visible:=false;
  dbtext9.Visible:=false;
  qorigenes.Close;
  qorigenes.SQL.Clear;
  qorigenes.sql.Add('select * from almacenes where activo=1 and produccion=1 order by nombre');
  qorigenes.Open;
  qdestinos.Open;
  combolotes_es.ListField:='';
  combolotes_es.KeyField:='';
  combolotes_es.ListSource:=dm.dsqlotessalidas;
  combolotes_es.ListField:='lote;fecha;MPRIMA;origen;merma';
  combolotes_es.KeyField:='lote';
  comboenvases_es.ListSource:=dsqpalets2;
  qaux.sql.clear;
  qaux.sql.add('delete from ea_pesadas_tmp where idea<=0');
  qaux.execsql;//+dm.qlotesidempresa.asstring);
  qaux.SQL.Clear;
  qaux.sql.add('delete from lotes_pesadas_tmp where idea2<=0');// where es_entrada=0');//+dm.qlotesidempresa.asstring);
  qaux.execsql;
  qaux.sql.clear;
  qaux.sql.add('delete from ea_materiales_tmp where idea2<=0');// where es_entrada=0');//+dm.qlotesidempresa.asstring);
  qaux.execsql;

  dm.qpesadassalidas.close;
  dm.qpesadassalidas.sql.clear;
  dm.qpesadassalidas.SQL.Add('select * from v_ea_pesadaslotes where idea<=0 and fecha='+vfecha2+' order by id desc' );
  dm.qpesadassalidas.Open;
  qpalets1.open;
  qpalets2.Open;
    qmprimas.Close;
    if rdesechos.Checked then
    begin
      qmprimas.SQL.Clear;
      qmprimas.SQL.Add('select * from materias_primas where basculas=1 and activo=1 and desechos=1 order by id');
    end;
    if renvasados.Checked then
    begin
      qmprimas.SQL.Clear;
      qmprimas.SQL.Add('select * from materias_primas where basculas=1 and activo=1 and desechos=0 order by id');
    end;
    if rentradas.Checked then
    begin
      qmprimas.SQL.Clear;
      qmprimas.SQL.Add('select * from materias_primas where basculas=1 and activo=1 order by id');
    end;
    qmprimas.Open;
  qformatoscajas.MasterSource:=dsqpalets2;
  qformatoscajas.open;
  qcalibres.Open;
  comboorigen_es.KeyValue:=null;
  combodestino_es.KeyValue:=null;
  combovariedad_es.KeyValue:=null;
  combolotes_es.KeyValue:=null;
  comboenvases_es.KeyValue:=null;
  comboformatos_es.KeyValue:=null;
  combocalibre_es.KeyValue:=null;
  comboentradas_es.KeyValue:=null;
  combopalets_es.KeyValue:=null;
  qpartidas.Close;

end;

procedure Tgeneral.rmovimientosClick(Sender: TObject);
begin
  timepedidos.Enabled:=false;
  pexpediciones.Visible:=false;
  pexpedicionesdetalle.Visible:=false;

  pmedio.Visible:=true;
  pmovimientos.Visible:=true;
  pexpediciones.Visible:=false;
  pentradassalidas.Visible:=false;
  pbajo.visible:=false;
  comboorigen_es.KeyValue:=null;
  combodestino_es.KeyValue:=null;
  qorigenes.Close;
  qorigenes.SQL.Clear;
  qorigenes.sql.Add('select * from almacenes where activo=1 order by nombre');
  qorigenes.Open;
  qdestinos.Open;
  tid.SetFocus;
  timer1.Enabled:=false;


end;

procedure Tgeneral.RadioButton4Click(Sender: TObject);
begin
    pbajo.Visible:=true;
    pexpediciones.Visible:=true;
    pexpedicionesdetalle.Visible:=true;
    pentradassalidas.Visible:=false;
    pmovimientos.Visible:=false;
    psalidasdetalle.Visible:=false;
    pentradasdetalle.Visible:=false;
    qpedidospendientes.Close;
    qpedidospendientes.Open;
    qenvasados.Close;
    qenvasados.open;
    qenvasados2.Close;
    qenvasados2.open;
    timepedidos.enabled:=true;
//    timer1.Enabled:=false;
end;

procedure Tgeneral.tbultosEnter(Sender: TObject);
begin
    tbultos.Text:='';
    teclado.Visible:=true;
    teclado.Top:=lenvases_es.Top+170;
    teclado.left:=lenvases_es.Left+550;
end;

procedure Tgeneral.tbultosExit(Sender: TObject);
begin
   teclado.Visible:=false;
   btactuallote.SetFocus;
end;

procedure Tgeneral.tbuscarenvasadoChange(Sender: TObject);
begin
    if tbuscarenvasado.Text<>'' then
    begin
        qenvasados.Close;
        qenvasados.SQL.Clear;
        qenvasados.SQL.Add('select * from ea_pesadas where  iddestino<>0 and (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 iddestino<>0 and (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 Tgeneral.tbuscarenvasadoEnter(Sender: TObject);
begin
    tbuscarenvasado.Text:='';
    teclado.Visible:=true;
    teclado.BringToFront;
    teclado.Top:=tbuscarenvasado.Top+335;
    teclado.left:=tbuscarenvasado.left+168;
end;

procedure Tgeneral.tbuscarenvasadoExit(Sender: TObject);
begin
  if tbuscarenvasado.Text<>'' then   btalnuevo.SetFocus;
  teclado.Visible:=false;
end;

procedure Tgeneral.tfechaChange(Sender: TObject);
var anyo,mes,dia:word;
      vanyo,vmes,vdia,vfecha:string;
begin
   //tfechatrabajo.Date:=tfecha.Date;
   decodedate(tfecha.Date,anyo,mes,dia);
   vanyo:=floattostr(anyo);
   vmes:=floattostr(mes);
   vdia:=floattostr(dia);
   vfecha:=''''+vanyo+'-'+vmes+'-'+vdia+'''';
   if renvasados.Checked or rentradas.Checked then
   begin
     qpartidas.Close;
     dm.qlotes.prepare;
     dm.qlotes.ParamByName('PFECHA').AsDate:=tfecha.Date;
     if dm.qlotes.Active then dm.qlotes.Refresh else dm.qlotes.Open;

     qpartidas.prepare;
     qpartidas.parambyname('PFECHA').AsDate:=tfecha.Date; //SQL.Add('select * from partidas where fecha='+vfecha+' order by id desc');
     if qpartidas.active then qpartidas.Refresh else qpartidas.Open;

     if qpartidas.RecordCount>0 then
     begin
      qentradas.Close;
      qentradas.SQL.Clear;
      qentradas.SQL.Add('select * from entradas_almacen where partida='+qpartidasid.asstring+' order by id desc ');
      qentradas.Open;
     end else qentradas.close;
   end;
   if renvasados.Checked then
   begin

       dm.qpesadassalidas.Close;
       dm.qpesadassalidas.SQL.Clear;
       dm.qpesadassalidas.SQL.Add('select * from v_ea_pesadaslotes where idea=0 and fecha='+vfecha+' order by id desc ');
       dm.qpesadassalidas.Open;
       if dm.qlotessalidas.Active then dm.qlotessalidas.Refresh else dm.qlotessalidas.Open;
   end;
   if rentradas.Checked then
   begin

       dm.qpesadasentradas.Close;
       dm.qpesadasentradas.SQL.Clear;
       dm.qpesadasentradas.SQL.Add('select * from v_ea_pesadaslotes where idea>0 and fecha='+vfecha+' order by id desc ');
       dm.qpesadasentradas.open;
   end;

    if rmovimientos.Checked then
    begin
       qorigenes.open;
       dm.qlotessalidas.parambyname('PFECHA').asdate:=tfecha.date;
       dm.qlotessalidas.parambyname('PALMACEN').AsInteger:=qorigenesid.Asinteger;
    end;

end;

procedure Tgeneral.Timer1Timer(Sender: TObject);
begin
   if lpeso2.Caption='NO CONECT' then
   begin
     edpeso_es.text:='0';
     edpeso_es.Enabled:=true;
   end else
   begin
     edpeso_es.Text:=lpeso2.Caption;
     edpeso_es.Enabled:=false;
   end;
   LHORA.Caption:=TIMETOSTR(TIME);

end;

procedure Tgeneral.Timer2Timer(Sender: TObject);
begin
//
    if (dm.qpesadasentradas.State in [dsbrowse]) or (dm.qpesadassalidas.State in [dsbrowse]) then
    begin
       if rentradas.Checked then
       begin
        dm.qpesadasentradas.Refresh;
//        dm.qpesadasentradas.First;
       end;
       if renvasados.Checked then
       begin
        dm.qpesadassalidas.Refresh;
//        dm.qpesadassalidas.First;
       end;
    end;
    if qpartidas.State in [dsbrowse] then qpartidas.Refresh;


end;

end.
