﻿unit fselectalbaranes;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset,
  ZAbstractDataset, ZDataset, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls;

type
  Tseleccionaralbaranes = class(TForm)
    Panel1: TPanel;
    Panel2: TPanel;
    Panel3: TPanel;
    DBGrid3: TDBGrid;
    Panel9: TPanel;
    btALnuevo: TButton;
    Button1: TButton;
    panelpedidos: TPanel;
    Panel6: TPanel;
    DBGrid2: TDBGrid;
    qaux: TZQuery;
    Button2: TButton;
    Button3: TButton;
    DBGrid1: TDBGrid;
    DBGrid4: TDBGrid;
    qinsertarfacturasdetalles: TZQuery;
    actualizaralbaranes: TZQuery;
    actualizaralbaranesdetalles: TZQuery;
    actualizarpedidosdetalle: TZQuery;
    procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure btALnuevoClick(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  seleccionaralbaranes: Tseleccionaralbaranes;
const
  rojo=$00AAAAFF;
  amarillo=$00B9FFFF;
  verde=$00C7FBAA;
  azul=$00FFFFBB;
implementation

{$R *.dfm}

uses ffacturas;


procedure Tseleccionaralbaranes.btALnuevoClick(Sender: TObject);
var
  serie, empresa, idfactura, idalbaran, observaciones: string;
  documento: string;
  facturado: integer;
begin
  documento := '';
  idfactura := facturas.facturasid.AsString;
  serie := facturas.facturasserie.AsString;
  empresa := facturas.facturasidempresa.AsString;
  idalbaran := facturas.qalbaranesid.AsString;
  observaciones := facturas.facturasobservaciones.AsString;

  facturas.facturas.Edit;
  facturas.facturasobservaciones.Value := Trim(observaciones + ' ' + facturas.qalbaranesobservaciones.AsString);
  facturas.facturas.Post;

  // Comprobar si ya existe cabecera para este albarán en la factura
  qaux.Close;
  qaux.SQL.Clear;
  qaux.SQL.Add('select count(*) from facturas_detalles where idempresa=' + empresa +
    ' and serie=''' + serie + ''' and idfactura=' + idfactura +
    ' and (idalbaran=' + idalbaran + ' or descripcion like ''Albaran ' + idalbaran + ' %'')');
  qaux.Open;
  if qaux.Fields[0].AsInteger = 0 then
  begin
    facturas.facturasdetalle.Append;
    facturas.facturasdetalleidempresa.Value := StrToInt(empresa);
    facturas.facturasdetalleserie.Value := serie;
    facturas.facturasdetalleidfactura.Value := StrToInt(idfactura);
    facturas.facturasdetalleidalbaran.Value := StrToInt(idalbaran);
    facturas.facturasdetalledescripcion.Value := 'Albaran ' + idalbaran + ' de fecha:' + facturas.qalbaranesfecha.AsString;
    facturas.facturasdetalletipoiva.Value := 0;
    facturas.facturasdetalle.Post;
  end;

  qaux.Close;
  qaux.SQL.Clear;
  qaux.SQL.Add('insert into facturas_detalles (idempresa,serie,idfactura,idarticulo,descripcion,cal,lote,bultos,cantidad,precio,descuento,totaldescuento,base,tipoiva,iva,total,idalbaran,coste_transporte,coste_comision,coste_otros,palets,');
  qaux.SQL.Add('pesobruto,envase,referencia,ean,unidadescaja,mprima,parcela,formato,pais,gg)');
  qaux.SQL.Add(' (SELECT ' + '''' + empresa + '''' + ' as idempresa,' + '''' + serie + '''' + ' as serie,' + '''' + idfactura + '''' + ' as idfactura,idarticulo,descripcion,cal,lote,bultos,cantidad,');
  qaux.SQL.Add('precio,descuento,totaldescuento,base,tipoiva,iva,total,' + idalbaran + ' as idalbaran,coste_transporte,coste_comision,coste_otros,palets,pesobruto,envase,referencia,ean,unidadescaja,mprima,parcela,formato,pais,gg');
  qaux.SQL.Add(' FROM albaranes_detalles where id=' + facturas.qalbaranesdetalleid.AsString + ')');
  qaux.ExecSQL;

  facturas.qalbaranesdetalle.Edit;
  facturas.qalbaranesdetalleidfactura.AsInteger := StrToInt(idfactura);
  facturas.qalbaranesdetalle.Post;
  facturas.qalbaranesdetalle.Refresh;

  if facturas.qalbaranesdetalle.RecordCount = 0 then
    facturado := 1
  else
    facturado := 0;

  actualizarpedidosdetalle.Close;
  actualizarpedidosdetalle.Prepare;
  actualizarpedidosdetalle.ParamByName('documento').AsString := serie + '/' + idfactura;
  actualizarpedidosdetalle.ParamByName('albaran').AsString := serie + '/' + idalbaran;
  actualizarpedidosdetalle.ExecSQL;

  qaux.Close;
  qaux.SQL.Clear;
  qaux.SQL.Add('select distinct(idfactura) from albaranes_detalles where idfactura=' + idfactura + ' and serie=''' + serie + '''');
  qaux.Open;
  if qaux.RecordCount > 0 then
    documento := documento + qaux.Fields[0].AsString + ' ';

  facturas.qalbaranes.Edit;
  facturas.qalbaranesidfactura.Value := facturas.facturasid.AsInteger;
  facturas.qalbaranesfacturado.Value := facturado;
  facturas.qalbaranesdocumento.Value := 'Factura Nº: ' + documento;
  facturas.qalbaranes.Post;

  facturas.RecalcularTotalesFactura(StrToInt(empresa), serie, StrToInt(idfactura));

  facturas.qalbaranes.Refresh;
  facturas.qalbaranesdetalle.Refresh;
  facturas.qalbaranes2.Refresh;
  facturas.qalbaranesdetalle2.Refresh;
  facturas.facturasdetalle.Refresh;
  facturas.facturas.DisableControls;
  try
    facturas.facturas.Refresh;
    if (serie <> '') and (idfactura <> '') then
      facturas.facturas.Locate('serie,id', VarArrayOf([serie, idfactura]), [loCaseInsensitive]);
  finally
    facturas.facturas.EnableControls;
  end;
  facturas.qfacturasiva.Refresh;
end;

procedure Tseleccionaralbaranes.Button1Click(Sender: TObject);
var
  serie, empresa, idalbaran, idfactura: string;
begin
  if facturas.facturasid.AsString <> '' then
  begin
    idfactura := facturas.facturasid.AsString;
    serie := facturas.facturasserie.AsString;
    empresa := facturas.facturasidempresa.AsString;
  end
  else
  begin
    serie := facturas.qalbaranes2serie.AsString;
    empresa := facturas.qalbaranes2idempresa.AsString;
    idfactura := facturas.qalbaranes2idfactura.AsString;
  end;
  idalbaran := facturas.qalbaranes2id.AsString;

  // Borrar la línea concreta en facturas_detalles
  qaux.Close;
  qaux.SQL.Clear;
  qaux.SQL.Add('delete from facturas_detalles where idempresa=' + empresa +
    ' and serie=''' + serie + ''' and idfactura=' + idfactura +
    ' and idalbaran=' + idalbaran +
    ' and idarticulo=(select idarticulo from albaranes_detalles where id=' + facturas.qalbaranesdetalle2id.AsString + ')' +
    ' and cantidad=(select cantidad from albaranes_detalles where id=' + facturas.qalbaranesdetalle2id.AsString + ')' +
    ' and coalesce(lote,'''')=(select coalesce(lote,'''') from albaranes_detalles where id=' + facturas.qalbaranesdetalle2id.AsString + ') limit 1');
  qaux.ExecSQL;

  qaux.Close;
  qaux.SQL.Clear;
  qaux.SQL.Add('update albaranes_detalles set idfactura=null where id=' + facturas.qalbaranesdetalle2id.AsString);
  qaux.ExecSQL;

  facturas.qalbaranes2.Edit;
  facturas.qalbaranes2facturado.Value := 0;
  facturas.qalbaranes2.Post;

  // Comprobar si aún quedan líneas de este albarán en la factura
  qaux.Close;
  qaux.SQL.Clear;
  qaux.SQL.Add('select count(*) from facturas_detalles where idempresa=' + empresa +
    ' and serie=''' + serie + ''' and idfactura=' + idfactura +
    ' and idalbaran=' + idalbaran + ' and idarticulo is not null');
  qaux.Open;
  if qaux.Fields[0].AsInteger = 0 then
  begin
    // No quedan líneas: eliminar la cabecera del albarán
    qaux.Close;
    qaux.SQL.Clear;
    qaux.SQL.Add('delete from facturas_detalles where idempresa=' + empresa +
      ' and serie=''' + serie + ''' and idfactura=' + idfactura +
      ' and (idalbaran=' + idalbaran + ' or descripcion like ''Albaran ' + idalbaran + ' %'')');
    qaux.ExecSQL;

    // Liberar albarán completo
    qaux.Close;
    qaux.SQL.Clear;
    qaux.SQL.Add('update albaranes set idfactura=null, facturado=0, documento=null where idempresa=' + empresa +
      ' and serie=''' + serie + ''' and id=' + idalbaran);
    qaux.ExecSQL;

    actualizarpedidosdetalle.Close;
    actualizarpedidosdetalle.Prepare;
    actualizarpedidosdetalle.ParamByName('documento').AsString := '';
    actualizarpedidosdetalle.ParamByName('albaran').AsString := serie + '/' + idalbaran;
    actualizarpedidosdetalle.ExecSQL;
  end;

  facturas.RecalcularTotalesFactura(StrToInt(empresa), serie, StrToInt(idfactura));

  facturas.qalbaranesdetalle.Refresh;
  facturas.qalbaranes.Refresh;
  facturas.qalbaranesdetalle2.Refresh;
  facturas.qalbaranes2.Refresh;
  facturas.facturasdetalle.Refresh;
  facturas.facturas.DisableControls;
  try
    facturas.facturas.Refresh;
    if (serie <> '') and (idfactura <> '') then
      facturas.facturas.Locate('serie,id', VarArrayOf([serie, idfactura]), [loCaseInsensitive]);
  finally
    facturas.facturas.EnableControls;
  end;
  facturas.qfacturasiva.Refresh;
end;

procedure Tseleccionaralbaranes.Button2Click(Sender: TObject);
var
  serie, empresa, idfactura, idalbaran, observaciones: string;
  pesobruto, pesoneto, pesonetoteorico, numpalets: string;
begin
  idfactura := facturas.facturasid.AsString;
  serie := facturas.facturasserie.AsString;
  empresa := facturas.facturasidempresa.AsString;
  idalbaran := facturas.qalbaranesid.AsString;
  observaciones := facturas.facturasobservaciones.AsString;

  facturas.facturas.Edit;
  facturas.facturasobservaciones.Value := Trim(observaciones + ' ' + facturas.qalbaranesobservaciones.AsString);
  facturas.facturascomision.Value := facturas.qalbaranescomision.AsFloat;
  facturas.facturas.Post;

  // Cabecera descriptiva del albarán vinculada con idalbaran
  facturas.facturasdetalle.Append;
  facturas.facturasdetalleidempresa.Value := StrToInt(empresa);
  facturas.facturasdetalleserie.Value := serie;
  facturas.facturasdetalleidfactura.Value := StrToInt(idfactura);
  facturas.facturasdetalleidalbaran.Value := StrToInt(idalbaran);
  facturas.facturasdetalledescripcion.Value := 'Albaran ' + idalbaran + ' de fecha:' + facturas.qalbaranesfecha.AsString;
  facturas.facturasdetalletipoiva.Value := 0;
  facturas.facturasdetalle.Post;

  qinsertarfacturasdetalles.Close;
  qinsertarfacturasdetalles.Prepare;
  qinsertarfacturasdetalles.ParamByName('EMPRESA').AsInteger := facturas.facturasidempresa.AsInteger;
  qinsertarfacturasdetalles.ParamByName('FACTURA').AsInteger := facturas.facturasid.AsInteger;
  qinsertarfacturasdetalles.ParamByName('ALBARAN').AsInteger := StrToInt(idalbaran);
  qinsertarfacturasdetalles.ParamByName('SERIE').AsString := facturas.facturasserie.AsString;
  qinsertarfacturasdetalles.ExecSQL;

  actualizaralbaranesdetalles.Close;
  actualizaralbaranesdetalles.Prepare;
  actualizaralbaranesdetalles.ParamByName('factura').AsInteger := facturas.facturasid.AsInteger;
  actualizaralbaranesdetalles.ParamByName('empresa').AsInteger := facturas.facturasidempresa.AsInteger;
  actualizaralbaranesdetalles.ParamByName('serie').AsString := facturas.facturasserie.AsString;
  actualizaralbaranesdetalles.ParamByName('albaran').AsInteger := StrToInt(idalbaran);
  actualizaralbaranesdetalles.ExecSQL;

  actualizaralbaranes.Close;
  actualizaralbaranes.Prepare;
  actualizaralbaranes.ParamByName('albaran').AsInteger := StrToInt(idalbaran);
  actualizaralbaranes.ParamByName('serie').AsString := facturas.facturasserie.AsString;
  actualizaralbaranes.ParamByName('documento').AsString := 'Factura Nº: ' + facturas.facturasid.AsString;
  actualizaralbaranes.ParamByName('factura').AsInteger := facturas.facturasid.AsInteger;
  actualizaralbaranes.ExecSQL;

  actualizarpedidosdetalle.Close;
  actualizarpedidosdetalle.Prepare;
  actualizarpedidosdetalle.ParamByName('documento').AsString := facturas.facturasserie.AsString + '/' + facturas.facturasid.AsString;
  actualizarpedidosdetalle.ParamByName('albaran').AsString := serie + '/' + idalbaran;
  actualizarpedidosdetalle.ExecSQL;

  // Recalcular totales e impuestos en la factura
  facturas.RecalcularTotalesFactura(StrToInt(empresa), serie, StrToInt(idfactura));

  // Recalcular pesos
  qaux.Close;
  qaux.SQL.Clear;
  qaux.SQL.Add('select coalesce(sum(peso_bruto-tara0),0), coalesce(sum(peso_neto),0), coalesce(sum(peso_neto_teorico),0), coalesce(sum(num_palets),0) ' +
    'from ea_pesadas where (idalbaran in (select distinct idalbaran from facturas_detalles where idempresa=' + empresa +
    ' and serie=''' + serie + ''' and idfactura=' + idfactura + ' and idalbaran is not null)' +
    ' or idalbaran in (select distinct concat(serie,''/'',idalbaran) from facturas_detalles where idempresa=' + empresa +
    ' and serie=''' + serie + ''' and idfactura=' + idfactura + ' and idalbaran is not null)) and idempresa=' + empresa);
  qaux.Open;
  if not qaux.Eof then
  begin
    pesobruto := StringReplace(FloatToStr(qaux.Fields[0].AsFloat), ',', '.', [rfReplaceAll]);
    pesoneto := StringReplace(FloatToStr(qaux.Fields[1].AsFloat), ',', '.', [rfReplaceAll]);
    pesonetoteorico := StringReplace(FloatToStr(qaux.Fields[2].AsFloat), ',', '.', [rfReplaceAll]);
    numpalets := StringReplace(FloatToStr(qaux.Fields[3].AsFloat), ',', '.', [rfReplaceAll]);
    qaux.Close;
    qaux.SQL.Clear;
    qaux.SQL.Add('update facturas set peso_bruto=' + pesobruto + ', kilos=' + pesoneto +
      ', kilosventa=' + pesonetoteorico + ', numpalets=' + numpalets +
      ' where idempresa=' + empresa + ' and serie=''' + serie + ''' and id=' + idfactura);
    qaux.ExecSQL;
  end;

  facturas.qalbaranesdetalle.Refresh;
  facturas.qalbaranes.Refresh;
  facturas.qalbaranes2.Refresh;
  facturas.qalbaranesdetalle2.Refresh;
  facturas.facturasdetalle.Refresh;
  facturas.facturas.DisableControls;
  try
    facturas.facturas.Refresh;
    if (serie <> '') and (idfactura <> '') then
      facturas.facturas.Locate('serie,id', VarArrayOf([serie, idfactura]), [loCaseInsensitive]);
  finally
    facturas.facturas.EnableControls;
  end;
  facturas.qfacturasiva.Refresh;
end;

procedure Tseleccionaralbaranes.Button3Click(Sender: TObject);
var
  serie, empresa, idalbaran, idfactura: string;
  pesobruto, pesoneto, pesonetoteorico, numpalets: string;
begin
  if facturas.facturasid.AsString <> '' then
  begin
    idfactura := facturas.facturasid.AsString;
    serie := facturas.facturasserie.AsString;
    empresa := facturas.facturasidempresa.AsString;
  end
  else
  begin
    serie := facturas.qalbaranes2serie.AsString;
    empresa := facturas.qalbaranes2idempresa.AsString;
    idfactura := facturas.qalbaranes2idfactura.AsString;
  end;
  idalbaran := facturas.qalbaranes2id.AsString;

  // Borrar líneas de detalle y la línea de cabecera asociadas al albarán en la factura
  qaux.SQL.Clear;
  qaux.SQL.Add('delete from facturas_detalles where idempresa=' + empresa +
    ' and serie=''' + serie + ''' and idfactura=' + idfactura +
    ' and (idalbaran=' + idalbaran + ' or descripcion like ''Albaran ' + idalbaran + ' %'')');
  qaux.ExecSQL;

  qaux.SQL.Clear;
  qaux.SQL.Add('update albaranes set idfactura=null, facturado=0, documento=null where idempresa=' +
    empresa + ' and serie=''' + serie + ''' and id=' + idalbaran);
  qaux.ExecSQL;

  qaux.SQL.Clear;
  qaux.SQL.Add('update albaranes_detalles set idfactura=null where idempresa=' +
    empresa + ' and serie=''' + serie + ''' and idalbaran=' + idalbaran);
  qaux.ExecSQL;

  actualizarpedidosdetalle.Close;
  actualizarpedidosdetalle.Prepare;
  actualizarpedidosdetalle.ParamByName('documento').AsString := '';
  actualizarpedidosdetalle.ParamByName('albaran').AsString := serie + '/' + idalbaran;
  actualizarpedidosdetalle.ExecSQL;

  // Recalcular totales e impuestos en la factura
  facturas.RecalcularTotalesFactura(StrToInt(empresa), serie, StrToInt(idfactura));

  // Recalcular pesos
  qaux.Close;
  qaux.SQL.Clear;
  qaux.SQL.Add('select coalesce(sum(peso_bruto-tara0),0), coalesce(sum(peso_neto),0), coalesce(sum(peso_neto_teorico),0), coalesce(sum(num_palets),0) ' +
    'from ea_pesadas where (idalbaran in (select distinct idalbaran from facturas_detalles where idempresa=' + empresa +
    ' and serie=''' + serie + ''' and idfactura=' + idfactura + ' and idalbaran is not null)' +
    ' or idalbaran in (select distinct concat(serie,''/'',idalbaran) from facturas_detalles where idempresa=' + empresa +
    ' and serie=''' + serie + ''' and idfactura=' + idfactura + ' and idalbaran is not null)) and idempresa=' + empresa);
  qaux.Open;
  if not qaux.Eof then
  begin
    pesobruto := StringReplace(FloatToStr(qaux.Fields[0].AsFloat), ',', '.', [rfReplaceAll]);
    pesoneto := StringReplace(FloatToStr(qaux.Fields[1].AsFloat), ',', '.', [rfReplaceAll]);
    pesonetoteorico := StringReplace(FloatToStr(qaux.Fields[2].AsFloat), ',', '.', [rfReplaceAll]);
    numpalets := StringReplace(FloatToStr(qaux.Fields[3].AsFloat), ',', '.', [rfReplaceAll]);
    qaux.Close;
    qaux.SQL.Clear;
    qaux.SQL.Add('update facturas set peso_bruto=' + pesobruto + ', kilos=' + pesoneto +
      ', kilosventa=' + pesonetoteorico + ', numpalets=' + numpalets +
      ' where idempresa=' + empresa + ' and serie=''' + serie + ''' and id=' + idfactura);
    qaux.ExecSQL;
  end;

  facturas.qalbaranes.Refresh;
  facturas.qalbaranesdetalle.Refresh;
  facturas.qalbaranes2.Refresh;
  facturas.qalbaranesdetalle2.Refresh;
  facturas.facturasdetalle.Refresh;
  facturas.facturas.DisableControls;
  try
    facturas.facturas.Refresh;
    if (serie <> '') and (idfactura <> '') then
      facturas.facturas.Locate('serie,id', VarArrayOf([serie, idfactura]), [loCaseInsensitive]);
  finally
    facturas.facturas.EnableControls;
  end;
  facturas.qfacturasiva.Refresh;
end;

procedure Tseleccionaralbaranes.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
    if (activecontrol is tdbgrid) then
    begin
        if Key = 13 then Key :=9;
    end;

end;

end.
