{
===============================================================================
  Copyright (©) 2007. Rodax Software.
===============================================================================
  Los contenidos de este fichero son propiedad de Rodax Software titular del
  copyright. Este fichero sólo podrá ser copiado, distribuido y utilizado,
  en su totalidad o en parte, con el permiso escrito de Rodax Software, o de
  acuerdo con los términos y condiciones establecidas en el acuerdo/contrato
  bajo el que se suministra.
  -----------------------------------------------------------------------------
  Web:  www.rodax-software.com
===============================================================================
  Fecha primera versión: 
  Versión actual: 1.0.0
  Fecha versión actual: 
===============================================================================
  Modificaciones:

    Fecha         Comentarios
    ---------------------------------------------------------------------------
===============================================================================
}

unit uOscAddressBookController;

interface

uses
  Classes, SysUtils, uDADataTable, uControllerBase,

	// Descomentar esto si hay detalles 
	// uDetallesController,
	
  uBizOscAddressBook, uIDataModuleTiendaWeb;

type
  IOscAddressBookController = interface(IObservador)
  ['{0768DF4D-50C1-4C16-9C14-8B09DDECF1CB}']
    procedure AsignarID(AOscAddressBook: IBizOscAddressBook; IDCabecera: Integer; AEsNuevo:Boolean);
    function Localizar(AOscAddressBook: IBizOscAddressBook; AIDLocal : Integer): Boolean;
    
{    procedure Anadir(AOscAddressBook : IBizOscAddressBook);
    function Eliminar(AOscAddressBook : IBizOscAddressBook): Boolean; overload;
    function Guardar(AOscAddressBook : IBizOscAddressBook): Boolean;
    procedure DescartarCambios(AOscAddressBook : IBizOscAddressBook);
		function Duplicar(AOscAddressBook: IBizOscAddressBook): IBizOscAddressBook;

    function Buscar(const ID: Integer): IBizOscAddressBook;
	  function BuscarTodos: IBizOscAddressBook;
    procedure VerTodos(AOscAddressBook: IBizOscAddressBook);
    procedure Ver(AOscAddressBook: IBizOscAddressBook);
    function Localizar(AOscAddressBook: IBizOscAddressBook; ADescripcion:String): Boolean;
    function DarListaOscAddressBook: TStringList;
    function ExtraerSeleccionados(AOscAddressBook: IBizOscAddressBook) : IBizOscAddressBook;
    function ElegirOscAddressBook(AOscAddressBook: IBizOscAddressBook; AMensaje: String; AMultiSelect: Boolean): IBizOscAddressBook;}

    // Descomentar esto si hay informe
    // procedure Preview(AOscAddressBook : IBizOscAddressBook);
    // procedure Print(AOscAddressBook : IBizOscAddressBook);   
  end;

  TOscAddressBookController = class(TObservador, IOscAddressBookController)
  protected
    FDataModule : IDataModuleTiendaWeb;
  
  	// Descomentar esto si hay detalles 
    // FDetallesController : IOscAddressBookDetallesController;

    procedure RecibirAviso(ASujeto: ISujeto; ADataTable: IDAStronglyTypedDataTable); override;
	  function _Vacio : IBizOscAddressBook;

    function ValidarOscAddressBook(AOscAddressBook: IBizOscAddressBook): Boolean;
    procedure AsignarDataModule;
    procedure AsignarID(AOscAddressBook: IBizOscAddressBook; IDCabecera: Integer; AEsNuevo:Boolean);
  public
    constructor Create; virtual;
    destructor Destroy; override;

    procedure Anadir(AOscAddressBook : IBizOscAddressBook);
    function Eliminar(AOscAddressBook : IBizOscAddressBook): Boolean; overload;
    function Guardar(AOscAddressBook : IBizOscAddressBook): Boolean;
    procedure DescartarCambios(AOscAddressBook : IBizOscAddressBook);
    function Duplicar(AOscAddressBook: IBizOscAddressBook): IBizOscAddressBook;

	  function Buscar(const ID: Integer): IBizOscAddressBook;
    function BuscarTodos: IBizOscAddressBook;
    procedure VerTodos(AOscAddressBook: IBizOscAddressBook);
    procedure Ver(AOscAddressBook: IBizOscAddressBook);
    function Localizar(AOscAddressBook: IBizOscAddressBook; AIDLocal : Integer): Boolean;
    function ExtraerSeleccionados(AOscAddressBook: IBizOscAddressBook) : IBizOscAddressBook;
    function ElegirOscAddressBook(AOscAddressBook: IBizOscAddressBook; AMensaje: String; AMultiSelect: Boolean): IBizOscAddressBook;

    // Descomentar esto si hay informe
    // procedure Preview(AOscAddressBook : IBizOscAddressBook);
    // procedure Print(AOscAddressBook : IBizOscAddressBook);   
  end;

implementation

uses
  cxControls, DB, uEditorRegistryUtils, 
  uDAInterfaces, uDataTableUtils, 
  uDateUtils, uROTypes, DateUtils, Controls, Windows,
  
  // Descomentar esto si hay informe
  // uOscAddressBookReportController,
  
  schTiendaWebClient_Intf, uDataModuleTiendaWeb;

{ TOscAddressBookController }

procedure TOscAddressBookController.Anadir(AOscAddressBook: IBizOscAddressBook);
begin
  AOscAddressBook.Insert;
end;

procedure TOscAddressBookController.AsignarDataModule;
begin
  FDataModule := TDataModuleTiendaWeb.Create(Nil);
end;

procedure TOscAddressBookController.AsignarID(AOscAddressBook: IBizOscAddressBook;
  IDCabecera: Integer; AEsNuevo:Boolean);
begin
  if not Assigned(AOscAddressBook) then
    raise Exception.Create ('AddressBook no asignado');

  if AOscAddressBook.EsNuevo then
  begin
    AOscAddressBook.Edit;
    AOscAddressBook.customers_id := IDCabecera;
    AOscAddressBook.Post;
  end;
end;

function TOscAddressBookController.BuscarTodos: IBizOscAddressBook;
begin
//  Result := FDataModule.Get_
end;

constructor TOscAddressBookController.Create;
begin
  AsignarDataModule;
  
  // Descomentar esto si hay detalles 
  // FDetallesController := TDetallesController.Create;  
end;

function TOscAddressBookController.Buscar(const ID: Integer): IBizOscAddressBook;
begin
//  Result := (FDataModule as IDataModuleTiendaWeb).GetItem(ID);
end;

function TOscAddressBookController._Vacio: IBizOscAddressBook;
begin
  Result := Buscar(ID_NULO);
end;

procedure TOscAddressBookController.DescartarCambios(AOscAddressBook: IBizOscAddressBook);
begin
  if not Assigned(AOscAddressBook) then
    raise Exception.Create ('AddressBook no asignado');

  ShowHourglassCursor;
  try
    if (AOscAddressBook.State in dsEditModes) then
      AOscAddressBook.Cancel;

    AOscAddressBook.DataTable.CancelUpdates;
  finally
    HideHourglassCursor;
  end;
end;

destructor TOscAddressBookController.Destroy;
begin
  FDataModule := NIL;

  // Descomentar esto si hay detalles
  // FDetallesController := NIL;

  inherited;
end;


function TOscAddressBookController.Duplicar(AOscAddressBook: IBizOscAddressBook): IBizOscAddressBook;
begin
  Result := Self._Vacio;
  ShowHourglassCursor;
  try
    DuplicarRegistros(AOscAddressBook.DataTable, Result.DataTable, mdrActual);
    
    // Descomentar esto si hay detalles 
    // DuplicarRegistros(AOscAddressBook.Detalles.DataTable, Result.Detalles.DataTable, mdrTodos);

    // ¡CUIDADO! Hay que dejar algunos campos como si fuera todo nuevo
    Result.Edit;
    with Result do
    begin
    	// Ejemplos
      // ID_EMPRESA := dmUsuarios.IDEmpresaActual;
      // USUARIO := dmUsuarios.LoginInfo.Usuario;
      // REFERENCIA := ''; //Para que se asigne una nueva
      // FECHA_FACTURA := DateOf(Now);
      // SITUACION := SITUACION_PENDIENTE;
    end;

    Result.Post;
  finally
    HideHourglassCursor;
  end;
end;


function TOscAddressBookController.ValidarOscAddressBook(AOscAddressBook: IBizOscAddressBook): Boolean;
begin
  Result := False;

  if not Assigned(AOscAddressBook) then
    raise Exception.Create ('OscAddressBook no asignado');

  if (AOscAddressBook.DataTable.State in dsEditModes) then
    AOscAddressBook.DataTable.Post;

	// Ejemplos de validaciones
	{
  if (AOscAddressBook.ID_CLIENTE < 0) or
     (not Assigned(AOscAddressBook.Cliente)) or
     (AOscAddressBook.Cliente.IsEmpty) then
    raise Exception.Create('Debe indicar el cliente de esta factura');

  if (EsFechaVacia(AOscAddressBook.FECHA_FACTURA)) then
    raise Exception.Create('Debe indicar la fecha de esta factura');
	
  if Length(AOscAddressBook.REFERENCIA) = 0 then
    raise Exception.Create('Debe indicar una referencia para esta forma de pago.');

  if Length(AOscAddressBook.DESCRIPCION) = 0 then
    raise Exception.Create('Debe indicar una descripción para esta forma de pago.');
  }


  { Asegurarse de valores en campos "automáticos" tanto
    en MODIFICACIÓN como en INSERCIÓN. }
{  AOscAddressBook.Edit;
  try
    AOscAddressBook.USUARIO := dmUsuarios.LoginInfo.Usuario;
    Result := True;
  finally
    AOscAddressBook.Post;
  end;}

  Result := True;
end;

procedure TOscAddressBookController.Ver(AOscAddressBook: IBizOscAddressBook);
{var
  AEditor : IEditorOscAddressBook;}
begin
{  AEditor := NIL;
  ShowHourglassCursor;
  try
    CreateEditor('EditorOscAddressBook', IEditorOscAddressBook, AEditor);
    with AEditor do
      OscAddressBook := AOscAddressBook;
  finally
    HideHourglassCursor;
  end;

  if Assigned(AEditor) then
    try
      AEditor.ShowModal;
      AEditor.Release;
    finally
      AEditor := NIL;
    end;}
end;

procedure TOscAddressBookController.VerTodos(AOscAddressBook: IBizOscAddressBook);
{var
  AEditor : IEditorOscAddressBook;}
begin
{  AEditor := NIL;
  ShowHourglassCursor;
  try
    CreateEditor('EditorOscAddressBook', IEditorOscAddressBook, AEditor);
    with AEditor do
      OscAddressBook := AOscAddressBook;
  finally
    HideHourglassCursor;
  end;

  if Assigned(AEditor) then
    try
      AEditor.ShowModal;
      AEditor.Release;
    finally
      AEditor := NIL;
    end;}
end;

function TOscAddressBookController.Eliminar(AOscAddressBook: IBizOscAddressBook): Boolean;
begin
  Result := False;

  if not Assigned(AOscAddressBook) then
    raise Exception.Create ('OscAddressBook no asignado');

  ShowHourglassCursor;
  try
    if (AOscAddressBook.State in dsEditModes) then
      AOscAddressBook.Cancel;

    AOscAddressBook.Delete;
    AOscAddressBook.DataTable.ApplyUpdates;
    HideHourglassCursor;
    Result := True;
  finally
    HideHourglassCursor;
  end;
end;

procedure TOscAddressBookController.RecibirAviso(ASujeto: ISujeto; ADataTable: IDAStronglyTypedDataTable);
// Descomentar si hubiera detalles
{var
  AOscAddressBook : IBizOscAddressBook;
  ADetalles : IBizDetallesOscAddressBook;}
begin
  inherited;

  // Descomentar si hubiera detalles
  {if Supports(ADataTable, IBizDetallesOscAddressBook, ADetalles) and
     Supports(ADetalles.DataTable.MasterSource.DataTable, IBizOscAddressBook, AOscAddressBook) then
  begin
    AOscAddressBook.Edit;
    try
      AOscAddressBook.IMPORTE_TOTAL := FDetallesController.DarTotalImporteTotal(ADetalles);
    finally
      AOscAddressBook.Post;
    end;
  end;}
end;

function TOscAddressBookController.Guardar(AOscAddressBook: IBizOscAddressBook): Boolean;
{var
  NuevoID : Integer;}
begin
  Result := False;

  if ValidarOscAddressBook(AOscAddressBook) then
  begin
    ShowHourglassCursor;
    try
{      if AOscAddressBook.EsNuevo then
        NuevoID := FDataModule.GetNextID(AOscAddressBook.DataTable.LogicalName)
      else
        NuevoID := AOscAddressBook.ID;

      AsignarID(AOscAddressBook, NuevoID);}
      AOscAddressBook.DataTable.ApplyUpdates;

      Result := True;
    finally
      HideHourglassCursor;
    end;
  end;
end;

function TOscAddressBookController.Localizar(AOscAddressBook: IBizOscAddressBook; AIDLocal : Integer): Boolean;
begin
  Result := True;
  ShowHourglassCursor;
  try
    with AOscAddressBook.DataTable do
    begin
      DisableControls;
      First;
      if not Locate(fld_osc_AddressBookrdx_address_book_id_local, AIDLocal, []) then
         Result := False;
      EnableControls;
    end;
  finally
    HideHourglassCursor;
  end;
end;

function TOscAddressBookController.ExtraerSeleccionados(AOscAddressBook: IBizOscAddressBook): IBizOscAddressBook;
var
  ASeleccionados : IBizOscAddressBook;
begin
  ASeleccionados := (Self.Buscar(ID_NULO) as IBizOscAddressBook);
  CopyDataTable(AOscAddressBook.DataTable, ASeleccionados.DataTable, True);
  Result := ASeleccionados;
end;

function TOscAddressBookController.ElegirOscAddressBook(AOscAddressBook: IBizOscAddressBook; AMensaje: String; AMultiSelect: Boolean): IBizOscAddressBook;
{var
  AEditor : IEditorElegirOscAddressBook;}
begin
{  Result := NIL;

  CreateEditor('EditorElegirOscAddressBook', IEditorElegirOscAddressBook, AEditor);
  try
    with AEditor do
    begin
      OscAddressBook := AOscAddressBook;
      MultiSelect := AMultiSelect;
      Mensaje := AMensaje;
      if IsPositiveResult(ShowModal) then
        Result := OscAddressBookSeleccionados;
	  Release;
    end;
  finally
    AEditor := NIL;
  end;}
end;

// Descomentar esto si hay informe
// procedure TOscAddressBookController.Preview(AOscAddressBook: IBizOscAddressBook);
// var
//   AReportController : IOscAddressBookReportController;
// begin
//   AReportController := TOscAddressBookReportController.Create;
//   try
//     AReportController.Preview(AOscAddressBook.ID);
//   finally
//     AReportController := NIL;
//   end;
// end;

// Descomentar esto si hay informe
// procedure TOscAddressBookController.Print(AOscAddressBook: IBizOscAddressBook);
// var
//   AReportController : IOscAddressBookReportController;
// begin
//   AReportController := TOscAddressBookReportController.Create;
//   try
//     AReportController.Print(AOscAddressBook.ID);
//   finally
//     AReportController := NIL;
//   end;
// end;

end.
