unit srvReferencias_Impl;

{----------------------------------------------------------------------------}
{ This unit was automatically generated by the RemObjects SDK after reading  }
{ the RODL file associated with this project .                               }
{                                                                            }
{ This is where you are supposed to code the implementation of your objects. }
{----------------------------------------------------------------------------}

{$I Remobjects.inc}

interface

uses
  {vcl:} Classes, SysUtils, 
  {RemObjects:} uROXMLIntf, uROClientIntf, uROTypes, uROServer, uROServerIntf, uROSessions,
  {Ancestor Implementation:} DataAbstractService_Impl,
  {Used RODLs:} DataAbstract4_Intf,
  {Generated:} FactuGES_Intf, uDADataStreamer, uDABin2DataStreamer, uDAClasses, uDAInterfaces;

type
  { TsrvReferencias }
  TsrvReferencias = class(TDataAbstractService, IsrvReferencias)
    Bin2DataStreamer: TDABin2DataStreamer;
    schReferencias: TDASchema;
    procedure DataAbstractServiceBeforeAcquireConnection(aSender: TObject;
      var aConnectionName: string);
    procedure DataAbstractServiceCreate(Sender: TObject);
  private
  public
    { IsrvReferencias methods }
    function DarNuevaReferencia(const NombreReferencia: String;
      const EmpresaID: Integer = -1; const TiendaID: Integer = -1): String;
    function IncrementarValorReferencia(const NombreReferencia: String;
      const Valor: String; const EmpresaID: Integer = -1; const TiendaID: Integer = -1): Boolean;
  end;

implementation

{$R *.dfm}
uses
  {Generated:} FactuGES_Invk, Variants, dialogs,
  uDataModuleServer, uROClasses, uReferenciasUtils;

procedure Create_srvReferencias(out anInstance : IUnknown);
begin
  anInstance := TsrvReferencias.Create(nil);
end;

{ srvReferencias }
function TsrvReferencias.DarNuevaReferencia(const NombreReferencia: String;
  const EmpresaID: Integer = -1; const TiendaID: Integer = -1): String;
var
  ASchema : TDASchema;
  AConn : IDAConnection;
  dsData: IDADataset;

  AWhere : TDAWhereExpression;
  AWhereExpr1: TDAWhereExpression;
  AWhereExpr2: TDAWhereExpression;
  AWhereExpr3: TDAWhereExpression;
begin
  Result := '';

  { Construir la expresión del Where a partir de los parámetros
    que se reciban.
  }
  with TDAWhereBuilder.Create do
    try
      AWhereExpr1 := NewBinaryExpression(NewField('', 'CODIGO'),
                      NewConstant(NombreReferencia, datString),
                      dboEqual);

      AWhere := AWhereExpr1;

      //Si se asigna IDEmpresa se añade condicion
      if (EmpresaID <> -1) then
      begin
        AWhereExpr2 := NewBinaryExpression(NewField('', 'ID_EMPRESA'),
                        NewConstant(EmpresaID, datInteger),
                        dboEqual);

        AWhere := NewBinaryExpression(AWhere, AWhereExpr2, dboAnd);
      end;

      //Si se asigna IDTienda se añade condicion
      if (TiendaID <> -1) then
      begin
        AWhereExpr3 := NewBinaryExpression(NewField('', 'ID_TIENDA'),
                        NewConstant(TiendaID, datInteger),
                        dboEqual);

        AWhere := NewBinaryExpression(AWhere, AWhereExpr3, dboAnd);
      end

    finally
      Free;
    end;

  ASchema := schReferencias;
  AConn := dmServer.ConnectionManager.NewConnection(dmServer.ConnectionManager.GetDefaultConnectionName);

  try
    try
      dsData := ASchema.NewDataset(AConn, 'Referencias', ['VALOR'], '', '', False, True);
      dsData.DynamicWhere.Expression := AWhere;
    except
      RaiseError('No existe la tabla REFERENCIAS');
    end;

    dsData.Active := True;

    if dsData.IsEmpty then
      RaiseError('No existe la referencia ' + NombreReferencia + ' en la tabla REFERENCIAS (Empresa ' + IntToStr(EmpresaID) + ', Tienda ' + IntToStr(TiendaID) + ')');

    Result := dsData.FieldByName('VALOR').AsString;
  finally
    dsData := NIL;
  end;
end;

procedure TsrvReferencias.DataAbstractServiceBeforeAcquireConnection(aSender: TObject; var aConnectionName: string);
begin
  ConnectionName := dmServer.ConnectionName;
end;

procedure TsrvReferencias.DataAbstractServiceCreate(Sender: TObject);
begin
  //SessionManager := dmServer.SessionManager;
end;

function TsrvReferencias.IncrementarValorReferencia(const NombreReferencia: String;
  const Valor: String; const EmpresaID: Integer = -1; const TiendaID: Integer = -1): Boolean;
var
  ASchema : TDASchema;
  AConn : IDAConnection;
  dsCommand: IDASQLCommand;

  AWhere : String;
begin
  Result := False;
  { Construir la expresión del Where a partir de los parámetros
    que se reciban.
  }
  AWhere := '';
  if (EmpresaID <> -1) then
     AWhere := AWhere + ' AND (ID_EMPRESA = ' + IntToStr(EmpresaID) + ')';

  if (TiendaID <> -1) then
     AWhere := AWhere + ' AND (ID_TIENDA = ' + IntToStr(TiendaID) + ')';

  ASchema := schReferencias;
  AConn := dmServer.ConnectionManager.NewConnection(dmServer.ConnectionManager.GetDefaultConnectionName);

  try
    try
      dsCommand := ASchema.NewCommand(AConn, 'ModificarValorReferencia');
      with dsCommand do
      begin
        ParamByName('CODIGO').AsString := NombreReferencia;
        ParamByName('VALOR').AsString := DarReferenciaSiguiente(Valor);
        dsCommand.SQL := dsCommand.SQL + AWhere;  //Asignamos las condiciones de empresa y tienda si es necesario
      end;
      dsCommand.Execute;
      AConn.CommitTransaction;
      Result := True;
    except
      RaiseError('Error al asignar la nueva referencia ' + Valor + ' en tablas');
      AConn.RollbackTransaction;
    end;
  finally
    dsCommand := NIL;
  end;
end;

initialization
  TROClassFactory.Create('srvReferencias', Create_srvReferencias, TsrvReferencias_Invoker);

finalization

end.
