unit uAlbaranInterempresaService;

interface

uses
  System.SysUtils, System.Classes, System.Generics.Collections, Data.DB,
  FireDAC.Comp.Client, FireDAC.Stan.Param;

type
  TAlbaranInterempresaService = class
  public
    /// <summary>
    /// Crea o sincroniza (actualiza/elimina) los albaranes de venta interempresas asociados a un albarán original
    /// cuando existen bultos preparados desde almacenes propiedad de otras empresas.
    /// </summary>
    class procedure SincronizarAlbaranesInterempresas(const AAlbaranId: Integer);

    /// <summary>
    /// Elimina los albaranes de venta interempresas vinculados a un albarán original.
    /// Devuelve False si alguno de ellos ya está facturado.
    /// </summary>
    class function EliminarAlbaranesInterempresas(const AAlbaranId: Integer; out AMsgError: string): Boolean;
  end;

implementation

uses
  dmg_Main;

class procedure TAlbaranInterempresaService.SincronizarAlbaranesInterempresas(const AAlbaranId: Integer);
var
  QryAlb, QryItems, QryEmp, QryCli, QryNum, QryExist, QryExec: TFDQuery;
  LEmpresaAlbaran, LEmpVendId, LClienteId, LNextNum, LTargetAlbId, LArtId, LPos: Integer;
  LSerie, LAlbRefStr, LNombreComp, LCifComp, LObs, LLote, LFaltantesFacturados: string;
  LCant, LPrecio, LTipoIva, LBase, LTotal, LTotBase, LTotIva, LTotDoc, LIvaCant: Double;
  LHasSeriesRow, LEsFacturado: Boolean;
  LEmpVendList, LEmpExistList: TList<Integer>;
  LEmpToAlbMap: TDictionary<Integer, Integer>;
  LEmpFactMap: TDictionary<Integer, Boolean>;
  LPair: TPair<Integer, Integer>;
begin
  if AAlbaranId <= 0 then Exit;

  QryAlb := TFDQuery.Create(nil);
  QryItems := TFDQuery.Create(nil);
  QryEmp := TFDQuery.Create(nil);
  QryCli := TFDQuery.Create(nil);
  QryNum := TFDQuery.Create(nil);
  QryExist := TFDQuery.Create(nil);
  QryExec := TFDQuery.Create(nil);
  LEmpVendList := TList<Integer>.Create;
  LEmpExistList := TList<Integer>.Create;
  LEmpToAlbMap := TDictionary<Integer, Integer>.Create;
  LEmpFactMap := TDictionary<Integer, Boolean>.Create;
  try
    QryAlb.Connection := dmgMain.dbConn;
    QryItems.Connection := dmgMain.dbConn;
    QryEmp.Connection := dmgMain.dbConn;
    QryCli.Connection := dmgMain.dbConn;
    QryNum.Connection := dmgMain.dbConn;
    QryExist.Connection := dmgMain.dbConn;
    QryExec.Connection := dmgMain.dbConn;

    // 1. Obtener datos del albarán original
    QryAlb.SQL.Text := 'SELECT empresa_id, serie, numero FROM ge_albaranes WHERE id = :alb';
    QryAlb.ParamByName('alb').AsInteger := AAlbaranId;
    QryAlb.Open;
    if QryAlb.IsEmpty then Exit;

    LEmpresaAlbaran := QryAlb.FieldByName('empresa_id').AsInteger;
    LAlbRefStr := QryAlb.FieldByName('serie').AsString + '-' + QryAlb.FieldByName('numero').AsString;
    LObs := 'Albarán de venta interempresas generado automáticamente por traspaso desde almacén compartido para el albarán original ' + LAlbRefStr;

    // 2. Localizar albaranes interempresas ya existentes para este albarán original
    QryExist.SQL.Text :=
      'SELECT id, empresa_id, serie, numero, COALESCE(facturado, 0) AS facturado, COALESCE(id_factura, 0) AS id_factura ' +
      'FROM ge_albaranes ' +
      'WHERE observaciones1 = :obs';
    QryExist.ParamByName('obs').AsString := LObs;
    QryExist.Open;
    while not QryExist.Eof do
    begin
      LEmpVendId := QryExist.FieldByName('empresa_id').AsInteger;
      LEsFacturado := (QryExist.FieldByName('facturado').AsInteger <> 0) or
                      (QryExist.FieldByName('id_factura').AsInteger > 0);
      if not LEmpToAlbMap.ContainsKey(LEmpVendId) then
      begin
        LEmpToAlbMap.Add(LEmpVendId, QryExist.FieldByName('id').AsInteger);
        LEmpFactMap.Add(LEmpVendId, LEsFacturado);
        LEmpExistList.Add(LEmpVendId);
      end;
      QryExist.Next;
    end;

    // 3. Obtener artículos y lotes preparados agrupados por empresa propietaria del almacén (con fallback al obrador del lote)
    QryItems.SQL.Text :=
      'SELECT t.articulo_id, t.descripcion, t.precio, t.tipo_iva, t.lote, t.fecha_caducidad, ' +
      '       SUM(t.cantidad) AS cantidad_total, t.empresa_propietaria ' +
      'FROM ( ' +
      '  SELECT al.articulo_id, al.descripcion, al.precio, COALESCE(al.tipo_iva, 0) AS tipo_iva, ' +
      '         COALESCE(lb.lote, '''') AS lote, lb.fecha_caducidad, lb.cantidad, ' +
      '         COALESCE( ' +
      '           (SELECT alm.id_empresa ' +
      '            FROM ge_stock_envasado se ' +
      '            INNER JOIN ge_almacenes alm ON se.id_almacen = alm.id ' +
      '            LEFT JOIN ge_lotes l ON se.id_lote = l.id ' +
      '            WHERE se.id_articulo = COALESCE(NULLIF(a.id_maestro, 0), al.articulo_id) ' +
      '              AND ( ' +
      '                (COALESCE(NULLIF(lb.lote_interno, ''''), NULLIF(lb.lote, ''''), '''') <> '''' ' +
      '                 AND (l.codigo = COALESCE(NULLIF(lb.lote_interno, ''''), lb.lote) ' +
      '                      OR l.codigo_antiguo = COALESCE(NULLIF(lb.lote_interno, ''''), lb.lote))) ' +
      '                OR COALESCE(NULLIF(lb.lote_interno, ''''), NULLIF(lb.lote, ''''), '''') = '''' ' +
      '              ) ' +
      '            ORDER BY (se.cantidad_unidades > 0) DESC, se.id DESC LIMIT 1), ' +
      '           (SELECT COALESCE(NULLIF(obr.id_empresa, 0), alm_o.id_empresa) ' +
      '            FROM ge_lotes l ' +
      '            INNER JOIN ge_obradores obr ON l.id_obrador = obr.id ' +
      '            LEFT JOIN ge_almacenes alm_o ON obr.id_almacen = alm_o.id ' +
      '            WHERE COALESCE(NULLIF(lb.lote_interno, ''''), NULLIF(lb.lote, ''''), '''') <> '''' ' +
      '              AND (l.codigo = COALESCE(NULLIF(lb.lote_interno, ''''), lb.lote) ' +
      '                   OR l.codigo_antiguo = COALESCE(NULLIF(lb.lote_interno, ''''), lb.lote)) ' +
      '            ORDER BY l.id DESC LIMIT 1), ' +
      '           0 ' +
      '         ) AS empresa_propietaria ' +
      '  FROM ge_albaranes_lineas_bultos lb ' +
      '  INNER JOIN ge_albaranes_lineas al ON lb.linea_albaran_id = al.id ' +
      '  LEFT JOIN ge_articulos a ON a.id = al.articulo_id ' +
      '  WHERE al.albaran_id = :alb ' +
      ') t ' +
      'GROUP BY t.articulo_id, t.descripcion, t.precio, t.tipo_iva, t.lote, t.fecha_caducidad, t.empresa_propietaria';
    QryItems.ParamByName('alb').AsInteger := AAlbaranId;
    QryItems.Open;

    QryItems.First;
    while not QryItems.Eof do
    begin
      LEmpVendId := QryItems.FieldByName('empresa_propietaria').AsInteger;
      if (LEmpVendId > 0) and (LEmpVendId <> LEmpresaAlbaran) and (not LEmpVendList.Contains(LEmpVendId)) then
        LEmpVendList.Add(LEmpVendId);
      QryItems.Next;
    end;

    // 4. Eliminar albaranes interempresas existentes que ya no tienen líneas servidas (y no estén facturados)
    LFaltantesFacturados := '';
    for LPair in LEmpToAlbMap do
    begin
      if not LEmpVendList.Contains(LPair.Key) then
      begin
        if LEmpFactMap.ContainsKey(LPair.Key) and LEmpFactMap[LPair.Key] then
        begin
          if LFaltantesFacturados <> '' then LFaltantesFacturados := LFaltantesFacturados + ', ';
          LFaltantesFacturados := LFaltantesFacturados + 'ID #' + IntToStr(LPair.Value);
        end
        else
        begin
          QryExec.Close;
          QryExec.SQL.Text := 'DELETE FROM ge_albaranes_lineas WHERE albaran_id = :alb';
          QryExec.ParamByName('alb').AsInteger := LPair.Value;
          QryExec.ExecSQL;

          QryExec.Close;
          QryExec.SQL.Text := 'DELETE FROM ge_albaranes WHERE id = :alb';
          QryExec.ParamByName('alb').AsInteger := LPair.Value;
          QryExec.ExecSQL;
        end;
      end;
    end;

    if LEmpVendList.Count = 0 then Exit;

    // 5. Obtener datos de la empresa compradora (la que vende al cliente final)
    QryEmp.SQL.Text := 'SELECT nombre, cif_nif, direccion, cp, poblacion FROM ge_empresas WHERE id = :id';
    QryEmp.ParamByName('id').AsInteger := LEmpresaAlbaran;
    QryEmp.Open;
    if not QryEmp.IsEmpty then
    begin
      LNombreComp := QryEmp.FieldByName('nombre').AsString;
      LCifComp    := Trim(QryEmp.FieldByName('cif_nif').AsString);
    end
    else
    begin
      LNombreComp := 'Empresa ID ' + IntToStr(LEmpresaAlbaran);
      LCifComp    := '';
    end;

    // 6. Crear o actualizar el albarán de cada empresa propietaria del almacén
    for var iEmpIdx := 0 to LEmpVendList.Count - 1 do
    begin
      LEmpVendId := LEmpVendList[iEmpIdx];
      LTargetAlbId := 0;
      if LEmpToAlbMap.TryGetValue(LEmpVendId, LTargetAlbId) then
      begin
        if LEmpFactMap.ContainsKey(LEmpVendId) and LEmpFactMap[LEmpVendId] then
          Continue; // Albarán interempresas ya facturado: no alterar

        // Limpiar líneas anteriores para regenerarlas con las cantidades/bultos actuales
        QryExec.Close;
        QryExec.SQL.Text := 'DELETE FROM ge_albaranes_lineas WHERE albaran_id = :alb';
        QryExec.ParamByName('alb').AsInteger := LTargetAlbId;
        QryExec.ExecSQL;
      end
      else
      begin
        // Buscar o crear cliente para la empresa compradora
        LClienteId := 0;
        if LCifComp <> '' then
        begin
          QryCli.Close;
          QryCli.SQL.Text := 'SELECT id FROM ge_clientes WHERE nif = :cif LIMIT 1';
          QryCli.ParamByName('cif').AsString := LCifComp;
          QryCli.Open;
          if not QryCli.IsEmpty then
            LClienteId := QryCli.FieldByName('id').AsInteger;
        end;

        if LClienteId = 0 then
        begin
          QryCli.Close;
          QryCli.SQL.Text := 'SELECT id FROM ge_clientes WHERE UPPER(nombre_fiscal) LIKE UPPER(:nom) LIMIT 1';
          QryCli.ParamByName('nom').AsString := '%' + LNombreComp + '%';
          QryCli.Open;
          if not QryCli.IsEmpty then
            LClienteId := QryCli.FieldByName('id').AsInteger;
        end;

        if LClienteId = 0 then
        begin
          QryExec.Close;
          QryExec.SQL.Text :=
            'INSERT INTO ge_clientes (nombre_fiscal, nif, domicilio, codigo_postal, poblacion, activo, id_user_creator, id_user_update) ' +
            'VALUES (:nom, :nif, :dom, :cp, :pob, 1, :user, :user)';
          QryExec.ParamByName('nom').AsString := LNombreComp;
          QryExec.ParamByName('nif').AsString := LCifComp;
          if not QryEmp.IsEmpty then
          begin
            QryExec.ParamByName('dom').AsString := QryEmp.FieldByName('direccion').AsString;
            QryExec.ParamByName('cp').AsString  := QryEmp.FieldByName('cp').AsString;
            QryExec.ParamByName('pob').AsString := QryEmp.FieldByName('poblacion').AsString;
          end
          else
          begin
            QryExec.ParamByName('dom').AsString := 'Venta Interempresas';
            QryExec.ParamByName('cp').AsString  := '';
            QryExec.ParamByName('pob').AsString := '';
          end;
          QryExec.ParamByName('user').AsString := dmgMain.CurrentUserId;
          QryExec.ExecSQL;

          QryExec.Close;
          QryExec.SQL.Text := 'SELECT LAST_INSERT_ID() AS id';
          QryExec.Open;
          LClienteId := QryExec.FieldByName('id').AsInteger;
        end;

        // Obtener serie y siguiente número de albarán
        LSerie := 'A';
        LNextNum := 0;
        LHasSeriesRow := False;

        QryNum.Close;
        QryNum.SQL.Text :=
          'SELECT serie, sig_numero_albaran FROM ge_series ' +
          'WHERE empresa_id = :emp AND activo = 1 ORDER BY por_defecto DESC, serie ASC LIMIT 1';
        QryNum.ParamByName('emp').AsInteger := LEmpVendId;
        QryNum.Open;

        if not QryNum.IsEmpty and (Trim(QryNum.FieldByName('serie').AsString) <> '') then
        begin
          LSerie := Trim(QryNum.FieldByName('serie').AsString);
          LNextNum := QryNum.FieldByName('sig_numero_albaran').AsInteger;
          if LNextNum <= 0 then LNextNum := 1;
          LHasSeriesRow := True;
        end
        else
        begin
          QryNum.Close;
          QryNum.SQL.Text := 'SELECT COALESCE(MAX(numero), 0) + 1 AS next_num FROM ge_albaranes WHERE empresa_id = :emp AND serie = :ser';
          QryNum.ParamByName('emp').AsInteger := LEmpVendId;
          QryNum.ParamByName('ser').AsString  := LSerie;
          QryNum.Open;
          LNextNum := QryNum.FieldByName('next_num').AsInteger;
        end;

        QryExec.Close;
        QryExec.SQL.Text :=
          'INSERT INTO ge_albaranes (empresa_id, cliente_id, serie, numero, fecha, facturado, observaciones1, id_forma_pago, id_user_creator, id_user_update) ' +
          'VALUES (:emp, :cli, :ser, :num, CURDATE(), 0, :obs, (SELECT id_forma_pago FROM ge_clientes WHERE id = :cli), :user, :user)';
        QryExec.ParamByName('emp').AsInteger := LEmpVendId;
        QryExec.ParamByName('cli').AsInteger := LClienteId;
        QryExec.ParamByName('ser').AsString  := LSerie;
        QryExec.ParamByName('num').AsInteger := LNextNum;
        QryExec.ParamByName('obs').AsString  := LObs;
        QryExec.ParamByName('user').AsString := dmgMain.CurrentUserId;
        QryExec.ExecSQL;

        QryExec.Close;
        QryExec.SQL.Text := 'SELECT LAST_INSERT_ID() AS id';
        QryExec.Open;
        LTargetAlbId := QryExec.FieldByName('id').AsInteger;

        if LHasSeriesRow then
        begin
          QryExec.Close;
          QryExec.SQL.Text :=
            'UPDATE ge_series SET sig_numero_albaran = :nextnum + 1 WHERE empresa_id = :emp AND serie = :ser AND activo = 1';
          QryExec.ParamByName('nextnum').AsInteger := LNextNum;
          QryExec.ParamByName('emp').AsInteger     := LEmpVendId;
          QryExec.ParamByName('ser').AsString      := LSerie;
          QryExec.ExecSQL;
        end;
      end;

      // Insertar líneas actualizadas de esta empresa propietaria
      LPos := 0;
      LTotBase := 0;
      LTotIva := 0;
      LTotDoc := 0;

      QryItems.First;
      while not QryItems.Eof do
      begin
        if QryItems.FieldByName('empresa_propietaria').AsInteger = LEmpVendId then
        begin
          Inc(LPos);
          LArtId   := QryItems.FieldByName('articulo_id').AsInteger;
          LCant    := QryItems.FieldByName('cantidad_total').AsFloat;
          LPrecio  := QryItems.FieldByName('precio').AsFloat;
          LTipoIva := QryItems.FieldByName('tipo_iva').AsFloat;
          LLote    := Trim(QryItems.FieldByName('lote').AsString);
          LBase    := LCant * LPrecio;
          LTotal   := LBase * (1.0 + (LTipoIva / 100.0));
          LIvaCant := LTotal - LBase;

          LTotBase := LTotBase + LBase;
          LTotIva  := LTotIva + LIvaCant;
          LTotDoc  := LTotDoc + LTotal;

          QryExec.Close;
          QryExec.SQL.Text :=
            'INSERT INTO ge_albaranes_lineas (albaran_id, articulo_id, articulo_codigo, posicion, descripcion, cantidad, precio, tipo_iva, base, iva, total, lotes, fecha_caducidad, id_user_creator, id_user_update) ' +
            'VALUES (:alb, :art, :cod, :pos, :desc, :cant, :precio, :iva_tipo, :base, :iva, :tot, :lote, :fcad, :user, :user)';
          QryExec.ParamByName('alb').AsInteger     := LTargetAlbId;
          QryExec.ParamByName('art').AsInteger     := LArtId;
          QryExec.ParamByName('cod').AsString      := IntToStr(LArtId);
          QryExec.ParamByName('pos').AsInteger     := LPos;
          QryExec.ParamByName('desc').AsString     := QryItems.FieldByName('descripcion').AsString;
          QryExec.ParamByName('cant').AsFloat      := LCant;
          QryExec.ParamByName('precio').AsFloat    := LPrecio;
          QryExec.ParamByName('iva_tipo').AsFloat  := LTipoIva;
          QryExec.ParamByName('base').AsFloat      := LBase;
          QryExec.ParamByName('iva').AsFloat       := LIvaCant;
          QryExec.ParamByName('tot').AsFloat       := LTotal;
          if LLote <> '' then
            QryExec.ParamByName('lote').AsString := LLote
          else
          begin
            QryExec.ParamByName('lote').Clear;
            QryExec.ParamByName('lote').DataType := ftString;
          end;

          if not QryItems.FieldByName('fecha_caducidad').IsNull then
            QryExec.ParamByName('fcad').AsDateTime := QryItems.FieldByName('fecha_caducidad').AsDateTime
          else
          begin
            QryExec.ParamByName('fcad').Clear;
            QryExec.ParamByName('fcad').DataType := ftDate;
          end;

          QryExec.ParamByName('user').AsString := dmgMain.CurrentUserId;
          QryExec.ExecSQL;
        end;
        QryItems.Next;
      end;

      // Recalcular totales de cabecera y actualizar fecha a la de finalización/sincronización
      QryExec.Close;
      QryExec.SQL.Text :=
        'UPDATE ge_albaranes SET fecha = CURDATE(), base_imponible = :base, iva = :iva, total = :tot, id_user_update = :user WHERE id = :alb';
      QryExec.ParamByName('base').AsFloat  := LTotBase;
      QryExec.ParamByName('iva').AsFloat   := LTotIva;
      QryExec.ParamByName('tot').AsFloat   := LTotDoc;
      QryExec.ParamByName('user').AsString := dmgMain.CurrentUserId;
      QryExec.ParamByName('alb').AsInteger := LTargetAlbId;
      QryExec.ExecSQL;
    end;
  finally
    QryAlb.Free;
    QryItems.Free;
    QryEmp.Free;
    QryCli.Free;
    QryNum.Free;
    QryExist.Free;
    QryExec.Free;
    LEmpVendList.Free;
    LEmpExistList.Free;
    LEmpToAlbMap.Free;
    LEmpFactMap.Free;
  end;
end;

class function TAlbaranInterempresaService.EliminarAlbaranesInterempresas(const AAlbaranId: Integer; out AMsgError: string): Boolean;
var
  QryAlb, QryInter, QryExec: TFDQuery;
  LAlbRefStr, LObs, LInterRef: string;
  LInterId: Integer;
begin
  Result := True;
  AMsgError := '';
  if AAlbaranId <= 0 then Exit;

  QryAlb := TFDQuery.Create(nil);
  QryInter := TFDQuery.Create(nil);
  QryExec := TFDQuery.Create(nil);
  try
    QryAlb.Connection := dmgMain.dbConn;
    QryInter.Connection := dmgMain.dbConn;
    QryExec.Connection := dmgMain.dbConn;

    QryAlb.SQL.Text := 'SELECT serie, numero FROM ge_albaranes WHERE id = :alb';
    QryAlb.ParamByName('alb').AsInteger := AAlbaranId;
    QryAlb.Open;
    if QryAlb.IsEmpty then Exit;

    LAlbRefStr := Trim(QryAlb.FieldByName('serie').AsString) + '-' + Trim(QryAlb.FieldByName('numero').AsString);
    var LAlbRefSlash := Trim(QryAlb.FieldByName('serie').AsString) + '/' + Trim(QryAlb.FieldByName('numero').AsString);
    LObs := 'Albarán de venta interempresas generado automáticamente por traspaso desde almacén compartido para el albarán original ' + LAlbRefStr;
    var LObsSlash := 'Albarán de venta interempresas generado automáticamente por traspaso desde almacén compartido para el albarán original ' + LAlbRefSlash;

    QryInter.SQL.Text :=
      'SELECT id, serie, numero, COALESCE(facturado, 0) AS facturado, COALESCE(id_factura, 0) AS id_factura ' +
      'FROM ge_albaranes ' +
      'WHERE observaciones1 = :obs ' +
      '   OR observaciones1 = :obs_slash ' +
      '   OR TRIM(observaciones1) LIKE CONCAT(''Albarán de venta interempresas%para el albarán original '', :ref_dash) ' +
      '   OR TRIM(observaciones1) LIKE CONCAT(''Albarán de venta interempresas%para el albarán original '', :ref_slash)';
    QryInter.ParamByName('obs').AsString := LObs;
    QryInter.ParamByName('obs_slash').AsString := LObsSlash;
    QryInter.ParamByName('ref_dash').AsString := LAlbRefStr;
    QryInter.ParamByName('ref_slash').AsString := LAlbRefSlash;
    QryInter.Open;

    // Comprobar primero si alguno está facturado
    while not QryInter.Eof do
    begin
      if (QryInter.FieldByName('facturado').AsInteger <> 0) or
         (QryInter.FieldByName('id_factura').AsInteger > 0) then
      begin
        LInterRef := QryInter.FieldByName('serie').AsString + '/' + QryInter.FieldByName('numero').AsString;
        AMsgError := 'No se puede eliminar porque el albarán interempresas vinculado (' + LInterRef + ') ya está facturado.';
        Exit(False);
      end;
      QryInter.Next;
    end;

    QryInter.First;
    while not QryInter.Eof do
    begin
      LInterId := QryInter.FieldByName('id').AsInteger;

      QryExec.Close;
      QryExec.SQL.Text := 'DELETE FROM ge_albaranes_lineas_bultos WHERE linea_albaran_id IN (SELECT id FROM ge_albaranes_lineas WHERE albaran_id = :id)';
      QryExec.ParamByName('id').AsInteger := LInterId;
      QryExec.ExecSQL;

      QryExec.Close;
      QryExec.SQL.Text := 'DELETE FROM ge_albaranes_bultos WHERE albaran_id = :id';
      QryExec.ParamByName('id').AsInteger := LInterId;
      QryExec.ExecSQL;

      QryExec.Close;
      QryExec.SQL.Text := 'DELETE FROM ge_albaranes_lineas WHERE albaran_id = :id';
      QryExec.ParamByName('id').AsInteger := LInterId;
      QryExec.ExecSQL;

      QryExec.Close;
      QryExec.SQL.Text := 'DELETE FROM ge_albaranes WHERE id = :id';
      QryExec.ParamByName('id').AsInteger := LInterId;
      QryExec.ExecSQL;

      QryInter.Next;
    end;
  finally
    QryAlb.Free;
    QryInter.Free;
    QryExec.Free;
  end;
end;

end.
