{
===============================================================================
  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 uOscProductsController;

interface

uses
  Classes, SysUtils, uDADataTable, uControllerBase,

  uBizOscProducts, uIDataModuleTiendaWeb;

type
  IOscProductsController = interface(IObservador)
  ['{D22CB0C3-D0E2-4B34-B1B2-AE27815680C1}']
    function Nuevo : IBizOscProduct;
    procedure Anadir(AOscProducts : IBizOscProduct);
    function Eliminar(AOscProducts : IBizOscProduct): Boolean; overload;
    function Guardar(AOscProducts : IBizOscProduct): Boolean;
    procedure DescartarCambios(AOscProducts : IBizOscProduct);
		function Duplicar(AOscProducts: IBizOscProduct): IBizOscProduct;

	  function Buscar(const IDLocal: Integer): IBizOscProduct;
	  function BuscarTodos: IBizOscProduct;
    procedure VerTodos(AOscProducts: IBizOscProduct);
    procedure Ver(AOscProducts: IBizOscProduct);
    function Localizar(AOscProducts: IBizOscProduct; AIDLocal: Integer): Boolean;
    function DarListaOscProducts: TStringList;
    function ExtraerSeleccionados(AOscProducts: IBizOscProduct) : IBizOscProduct;
    function ElegirOscProducts(AOscProducts: IBizOscProduct; AMensaje: String; AMultiSelect: Boolean): IBizOscProduct;

    // Descomentar esto si hay informe
    // procedure Preview(AOscProducts : IBizOscProduct);
    // procedure Print(AOscProducts : IBizOscProduct);   
  end;

  TOscProductsController = class(TObservador, IOscProductsController)
  protected
    FDataModule : IDataModuleTiendaWeb;

    procedure RecibirAviso(ASujeto: ISujeto; ADataTable: IDAStronglyTypedDataTable); override;
	function _Vacio : IBizOscProduct;
	
    function ValidarOscProducts(AOscProducts: IBizOscProduct): Boolean;
    procedure AsignarDataModule;
    procedure AsignarID(AOscProducts: IBizOscProduct; const IDNuevo: Integer);
  public
    constructor Create; virtual;
    destructor Destroy; override;

    function Nuevo : IBizOscProduct;
    procedure Anadir(AOscProducts : IBizOscProduct);
    function Eliminar(AOscProducts : IBizOscProduct): Boolean; overload;
    function Guardar(AOscProducts : IBizOscProduct): Boolean;
    procedure DescartarCambios(AOscProducts : IBizOscProduct);
    function Duplicar(AOscProducts: IBizOscProduct): IBizOscProduct;

	  function Buscar(const IDLocal: Integer): IBizOscProduct;
    function BuscarTodos: IBizOscProduct;
    procedure VerTodos(AOscProducts: IBizOscProduct);
    procedure Ver(AOscProducts: IBizOscProduct);
    function Localizar(AOscProducts: IBizOscProduct; AIDLocal: Integer): Boolean;
    function DarListaOscProducts: TStringList;
    function ExtraerSeleccionados(AOscProducts: IBizOscProduct) : IBizOscProduct;
    function ElegirOscProducts(AOscProducts: IBizOscProduct; AMensaje: String; AMultiSelect: Boolean): IBizOscProduct;

    // Descomentar esto si hay informe
    // procedure Preview(AOscProducts : IBizOscProduct);
    // procedure Print(AOscProducts : IBizOscProduct);   
  end;

implementation

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

{ TOscProductsController }

procedure TOscProductsController.Anadir(AOscProducts: IBizOscProduct);
begin
  AOscProducts.Insert;
end;

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

procedure TOscProductsController.AsignarID(AOscProducts: IBizOscProduct;
  const IDNuevo: Integer);
var
  AContador : Integer;
begin
  if not Assigned(AOscProducts) then
    raise Exception.Create ('OscProducts no asignado');

  // { Los detalles hay que comprobarlos siempre
  //   tanto en inserción como en modificación. }
  {if Assigned(AOscProducts.Detalles) then
    FDetallesController.AsignarID(AOscProducts.Detalles, IDNuevo, AOscProducts.EsNuevo);}

  if AOscProducts.EsNuevo then
  begin
    AOscProducts.Edit;
    AOscProducts.manufacturers_id := IDNuevo;
    AOscProducts.Post;
  end;
end;

function TOscProductsController.BuscarTodos: IBizOscProduct;
begin
  Result := FDataModule.GetOSCProducts;
end;

constructor TOscProductsController.Create;
begin
  AsignarDataModule;
end;

function TOscProductsController.Buscar(const IDLocal: Integer): IBizOscProduct;
begin
  Result := FDataModule.GetOSCProduct(IDLocal);
end;

function TOscProductsController._Vacio: IBizOscProduct;
begin
  Result := Buscar(ID_NULO);
end;

function TOscProductsController.DarListaOscProducts: TStringList;
{var
  AOscProducts: IBizOscProduct;}
begin
{  AOscProducts := BuscarTodos;
  AOscProducts.DataTable.Active := True;
  Result := TStringList.Create;
  try
    with Result do
    begin
      AOscProducts.DataTable.First;
      while not AOscProducts.DataTable.EOF do
      begin
        Add(AOscProducts.DESCRIPCION);
        AOscProducts.DataTable.Next;
      end;
    end;
  finally
    AOscProducts := NIL;
  end;}
end;

procedure TOscProductsController.DescartarCambios(AOscProducts: IBizOscProduct);
begin
  if not Assigned(AOscProducts) then
    raise Exception.Create ('OscProducts no asignado');

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

    AOscProducts.DataTable.CancelUpdates;
  finally
    HideHourglassCursor;
  end;
end;

destructor TOscProductsController.Destroy;
begin
  FDataModule := NIL;
  inherited;
end;


function TOscProductsController.Duplicar(AOscProducts: IBizOscProduct): IBizOscProduct;
begin
  Result := Self._Vacio;
  ShowHourglassCursor;
  try
    DuplicarRegistros(AOscProducts.DataTable, Result.DataTable, mdrActual);
    
    // Descomentar esto si hay detalles 
    // DuplicarRegistros(AOscProducts.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 TOscProductsController.ValidarOscProducts(AOscProducts: IBizOscProduct): Boolean;
begin
  Result := False;

  if not Assigned(AOscProducts) then
    raise Exception.Create ('OscProducts no asignado');

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

	// Descomentar esto si hay detalles 
  // // Tambien hacemos post de sus tablas hija
  // if (AOscProducts.Detalles.DataTable.State in dsEditModes) then
      // AOscProducts.Detalles.DataTable.Post;


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

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

  if Length(AOscProducts.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. }
{  AOscProducts.Edit;
  try
    AOscProducts.USUARIO := dmUsuarios.LoginInfo.Usuario;
    Result := True;
  finally
    AOscProducts.Post;
  end;}

  Result := True;
end;

procedure TOscProductsController.Ver(AOscProducts: IBizOscProduct);
{var
  AEditor : IEditorOscProducts;}
begin
{  AEditor := NIL;
  ShowHourglassCursor;
  try
    CreateEditor('EditorOscProducts', IEditorOscProducts, AEditor);
    with AEditor do
      OscProducts := AOscProducts;
  finally
    HideHourglassCursor;
  end;

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

procedure TOscProductsController.VerTodos(AOscProducts: IBizOscProduct);
{var
  AEditor : IEditorOscProducts;}
begin
{  AEditor := NIL;
  ShowHourglassCursor;
  try
    CreateEditor('EditorOscProducts', IEditorOscProducts, AEditor);
    with AEditor do
      OscProducts := AOscProducts;
  finally
    HideHourglassCursor;
  end;

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

function TOscProductsController.Eliminar(AOscProducts: IBizOscProduct): Boolean;
begin
  Result := False;

  if not Assigned(AOscProducts) then
    raise Exception.Create ('OscProducts no asignado');

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

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

procedure TOscProductsController.RecibirAviso(ASujeto: ISujeto; ADataTable: IDAStronglyTypedDataTable);
// Descomentar si hubiera detalles
{var
  AOscProducts : IBizOscProduct;
  ADetalles : IBizDetallesOscProducts;}
begin
  inherited;

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

function TOscProductsController.Guardar(AOscProducts: IBizOscProduct): Boolean;
var
  NuevoID : Integer;
begin
  Result := False;

  if ValidarOscProducts(AOscProducts) then
  begin
    ShowHourglassCursor;
    try
{      if AOscProducts.EsNuevo then
        NuevoID := FDataModule.GetNextID(AOscProducts.DataTable.LogicalName)
      else}
        NuevoID := AOscProducts.manufacturers_id;

      AsignarID(AOscProducts, NuevoID);
      AOscProducts.DataTable.ApplyUpdates;
      
      Result := True;
    finally
      HideHourglassCursor;
    end;
  end;
end;

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

function TOscProductsController.Nuevo: IBizOscProduct;
var
  AOSCProduct : IBizOscProduct;
begin
  AOSCProduct := (FDataModule as IDataModuleTiendaWeb).NewOSCProduct;
  AOSCProduct.DataTable.Active := True;
  AOSCProduct.Insert;
  Result := AOSCProduct;
end;

function TOscProductsController.ExtraerSeleccionados(AOscProducts: IBizOscProduct): IBizOscProduct;
var
  ASeleccionados : IBizOscProduct;
begin
  ASeleccionados := (Self.Buscar(ID_NULO) as IBizOscProduct);
  CopyDataTable(AOscProducts.DataTable, ASeleccionados.DataTable, True);
  Result := ASeleccionados;
end;

function TOscProductsController.ElegirOscProducts(AOscProducts: IBizOscProduct; AMensaje: String; AMultiSelect: Boolean): IBizOscProduct;
{var
  AEditor : IEditorElegirOscProducts;}
begin
  Result := NIL;

{  CreateEditor('EditorElegirOscProducts', IEditorElegirOscProducts, AEditor);
  try
    with AEditor do
    begin
      OscProducts := AOscProducts;
      MultiSelect := AMultiSelect;
      Mensaje := AMensaje;
      if IsPositiveResult(ShowModal) then
        Result := OscProductsSeleccionados;
	  Release;
    end;
  finally
    AEditor := NIL;
  end;}
end;

// Descomentar esto si hay informe
// procedure TOscProductsController.Preview(AOscProducts: IBizOscProduct);
// var
//   AReportController : IOscProductsReportController;
// begin
//   AReportController := TOscProductsReportController.Create;
//   try
//     AReportController.Preview(AOscProducts.ID);
//   finally
//     AReportController := NIL;
//   end;
// end;

// Descomentar esto si hay informe
// procedure TOscProductsController.Print(AOscProducts: IBizOscProduct);
// var
//   AReportController : IOscProductsReportController;
// begin
//   AReportController := TOscProductsReportController.Create;
//   try
//     AReportController.Print(AOscProducts.ID);
//   finally
//     AReportController := NIL;
//   end;
// end;

end.
