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

interface

uses
  Classes, SysUtils, uDADataTable, uControllerBase,

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

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

    function Buscar(const ID: Integer): IBizOscOrderProducts;
	  function BuscarTodos: IBizOscOrderProducts;
    procedure VerTodos(AOscOrderProducts: IBizOscOrderProducts);
    procedure Ver(AOscOrderProducts: IBizOscOrderProducts);
    function Localizar(AOscOrderProducts: IBizOscOrderProducts; ADescripcion:String): Boolean;
    function DarListaOscOrderProducts: TStringList;
    function ExtraerSeleccionados(AOscOrderProducts: IBizOscOrderProducts) : IBizOscOrderProducts;
    function ElegirOscOrderProducts(AOscOrderProducts: IBizOscOrderProducts; AMensaje: String; AMultiSelect: Boolean): IBizOscOrderProducts;}

    // Descomentar esto si hay informe
    // procedure Preview(AOscOrderProducts : IBizOscOrderProducts);
    // procedure Print(AOscOrderProducts : IBizOscOrderProducts);   
  end;

  TOscOrderProductsController = class(TObservador, IOscOrderProductsController)
  protected
    FDataModule : IDataModuleTiendaWeb;
  
  	// Descomentar esto si hay detalles 
    // FDetallesController : IOscOrderProductsDetallesController;

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

    function ValidarOscOrderProducts(AOscOrderProducts: IBizOscOrderProducts): Boolean;
    procedure AsignarDataModule;
    procedure AsignarID(AOscOrderProducts: IBizOscOrderProducts; IDCabecera: Integer; AEsNuevo:Boolean);
  public
    constructor Create; virtual;
    destructor Destroy; override;

    procedure Anadir(AOscOrderProducts : IBizOscOrderProducts);
    function Eliminar(AOscOrderProducts : IBizOscOrderProducts): Boolean; overload;
    function Guardar(AOscOrderProducts : IBizOscOrderProducts): Boolean;
    procedure DescartarCambios(AOscOrderProducts : IBizOscOrderProducts);
    function Duplicar(AOscOrderProducts: IBizOscOrderProducts): IBizOscOrderProducts;

	  function Buscar(const ID: Integer): IBizOscOrderProducts;
    function BuscarTodos: IBizOscOrderProducts;
    procedure VerTodos(AOscOrderProducts: IBizOscOrderProducts);
    procedure Ver(AOscOrderProducts: IBizOscOrderProducts);
    function Localizar(AOscOrderProducts: IBizOscOrderProducts; AIDLocal : Integer): Boolean;
    function DarListaOscOrderProducts: TStringList;
    function ExtraerSeleccionados(AOscOrderProducts: IBizOscOrderProducts) : IBizOscOrderProducts;
    function ElegirOscOrderProducts(AOscOrderProducts: IBizOscOrderProducts; AMensaje: String; AMultiSelect: Boolean): IBizOscOrderProducts;

    // Descomentar esto si hay informe
    // procedure Preview(AOscOrderProducts : IBizOscOrderProducts);
    // procedure Print(AOscOrderProducts : IBizOscOrderProducts);   
  end;

implementation

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

{ TOscOrderProductsController }

procedure TOscOrderProductsController.Anadir(AOscOrderProducts: IBizOscOrderProducts);
begin
  AOscOrderProducts.Insert;
end;

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

procedure TOscOrderProductsController.AsignarID(AOscOrderProducts: IBizOscOrderProducts;
  IDCabecera: Integer; AEsNuevo:Boolean);
var
  AContador : Integer;
begin
  if not Assigned(AOscOrderProducts) then
    raise Exception.Create ('OrderProducts no asignado');

  if AOscOrderProducts.EsNuevo then
  begin
    AOscOrderProducts.Edit;
    AOscOrderProducts.orders_id := IDCabecera;
    AOscOrderProducts.Post;
  end;
end;

function TOscOrderProductsController.BuscarTodos: IBizOscOrderProducts;
begin
//  Result := FDataModule.Get_
end;

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

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

function TOscOrderProductsController._Vacio: IBizOscOrderProducts;
begin
  Result := Buscar(ID_NULO);
end;

function TOscOrderProductsController.DarListaOscOrderProducts: TStringList;
var
  AOscOrderProducts: IBizOscOrderProducts;
begin
{  AOscOrderProducts := BuscarTodos;
  AOscOrderProducts.DataTable.Active := True;
  Result := TStringList.Create;
  try
    with Result do
    begin
      AOscOrderProducts.DataTable.First;
      while not AOscOrderProducts.DataTable.EOF do
      begin
        Add(AOscOrderProducts.DESCRIPCION);
        AOscOrderProducts.DataTable.Next;
      end;
    end;
  finally
    AOscOrderProducts := NIL;
  end;}
end;

procedure TOscOrderProductsController.DescartarCambios(AOscOrderProducts: IBizOscOrderProducts);
begin
  if not Assigned(AOscOrderProducts) then
    raise Exception.Create ('OrderProducts no asignado');

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

    AOscOrderProducts.DataTable.CancelUpdates;
  finally
    HideHourglassCursor;
  end;
end;

destructor TOscOrderProductsController.Destroy;
begin
  FDataModule := NIL;

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

  inherited;
end;


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

  if not Assigned(AOscOrderProducts) then
    raise Exception.Create ('OscOrderProducts no asignado');

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

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


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

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

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

  Result := True;
end;

procedure TOscOrderProductsController.Ver(AOscOrderProducts: IBizOscOrderProducts);
{var
  AEditor : IEditorOscOrderProducts;}
begin
{  AEditor := NIL;
  ShowHourglassCursor;
  try
    CreateEditor('EditorOscOrderProducts', IEditorOscOrderProducts, AEditor);
    with AEditor do
      OscOrderProducts := AOscOrderProducts;
  finally
    HideHourglassCursor;
  end;

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

procedure TOscOrderProductsController.VerTodos(AOscOrderProducts: IBizOscOrderProducts);
{var
  AEditor : IEditorOscOrderProducts;}
begin
{  AEditor := NIL;
  ShowHourglassCursor;
  try
    CreateEditor('EditorOscOrderProducts', IEditorOscOrderProducts, AEditor);
    with AEditor do
      OscOrderProducts := AOscOrderProducts;
  finally
    HideHourglassCursor;
  end;

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

function TOscOrderProductsController.Eliminar(AOscOrderProducts: IBizOscOrderProducts): Boolean;
begin
  Result := False;

  if not Assigned(AOscOrderProducts) then
    raise Exception.Create ('OscOrderProducts no asignado');

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

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

procedure TOscOrderProductsController.RecibirAviso(ASujeto: ISujeto; ADataTable: IDAStronglyTypedDataTable);
// Descomentar si hubiera detalles
{var
  AOscOrderProducts : IBizOscOrderProducts;
  ADetalles : IBizDetallesOscOrderProducts;}
begin
  inherited;

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

function TOscOrderProductsController.Guardar(AOscOrderProducts: IBizOscOrderProducts): Boolean;
var
  NuevoID : Integer;
begin
  Result := False;

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

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

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

function TOscOrderProductsController.ExtraerSeleccionados(AOscOrderProducts: IBizOscOrderProducts): IBizOscOrderProducts;
var
  ASeleccionados : IBizOscOrderProducts;
begin
  ASeleccionados := (Self.Buscar(ID_NULO) as IBizOscOrderProducts);
  CopyDataTable(AOscOrderProducts.DataTable, ASeleccionados.DataTable, True);
  Result := ASeleccionados;
end;

function TOscOrderProductsController.ElegirOscOrderProducts(AOscOrderProducts: IBizOscOrderProducts; AMensaje: String; AMultiSelect: Boolean): IBizOscOrderProducts;
{var
  AEditor : IEditorElegirOscOrderProducts;}
begin
{  Result := NIL;

  CreateEditor('EditorElegirOscOrderProducts', IEditorElegirOscOrderProducts, AEditor);
  try
    with AEditor do
    begin
      OscOrderProducts := AOscOrderProducts;
      MultiSelect := AMultiSelect;
      Mensaje := AMensaje;
      if IsPositiveResult(ShowModal) then
        Result := OscOrderProductsSeleccionados;
	  Release;
    end;
  finally
    AEditor := NIL;
  end;}
end;

// Descomentar esto si hay informe
// procedure TOscOrderProductsController.Preview(AOscOrderProducts: IBizOscOrderProducts);
// var
//   AReportController : IOscOrderProductsReportController;
// begin
//   AReportController := TOscOrderProductsReportController.Create;
//   try
//     AReportController.Preview(AOscOrderProducts.ID);
//   finally
//     AReportController := NIL;
//   end;
// end;

// Descomentar esto si hay informe
// procedure TOscOrderProductsController.Print(AOscOrderProducts: IBizOscOrderProducts);
// var
//   AReportController : IOscOrderProductsReportController;
// begin
//   AReportController := TOscOrderProductsReportController.Create;
//   try
//     AReportController.Print(AOscOrderProducts.ID);
//   finally
//     AReportController := NIL;
//   end;
// end;

end.
