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

interface

uses
  Classes, SysUtils, uDADataTable, uControllerBase,

  uOscOrderProductsController,
  uBizOscOrders, uIDataModuleTiendaWeb;

type
  IOscOrdersController = interface(IObservador)
  ['{17765BA6-400E-4809-8548-F8EFCB94E40E}']
    //function Nuevo : IBizOscOrder;
    //procedure Anadir(AOscOrders : IBizOscOrder);
    function Eliminar(AOscOrders : IBizOscOrder): Boolean; overload;
    function Guardar(AOscOrders : IBizOscOrder): Boolean;
    procedure DescartarCambios(AOscOrders : IBizOscOrder);
		//function Duplicar(AOscOrders: IBizOscOrder): IBizOscOrder;
		
	  function Buscar(const IDLocal: Integer): IBizOscOrder;
	  function BuscarTodos: IBizOscOrder;
    procedure VerTodos(AOscOrders: IBizOscOrder);
    procedure Ver(AOscOrders: IBizOscOrder);
    function Localizar(AOscOrders: IBizOscOrder; AIDLocal: Integer): Boolean;
    function ExtraerSeleccionados(AOscOrders: IBizOscOrder) : IBizOscOrder;
    function ElegirOscOrders(AOscOrders: IBizOscOrder; AMensaje: String; AMultiSelect: Boolean): IBizOscOrder;

    // Descomentar esto si hay informe
    // procedure Preview(AOscOrders : IBizOscOrder);
    // procedure Print(AOscOrders : IBizOscOrder);   
  end;

  TOscOrdersController = class(TObservador, IOscOrdersController)
  protected
    FDataModule : IDataModuleTiendaWeb;
    FOrderProductsController : IOscOrderProductsController;

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

    //function Nuevo : IBizOscOrder;
    //procedure Anadir(AOscOrders : IBizOscOrder);
    function Eliminar(AOscOrders : IBizOscOrder): Boolean; overload;
    function Guardar(AOscOrders : IBizOscOrder): Boolean;
    procedure DescartarCambios(AOscOrders : IBizOscOrder);
    //function Duplicar(AOscOrders: IBizOscOrder): IBizOscOrder;

	  function Buscar(const IDLocal: Integer): IBizOscOrder;
    function BuscarTodos: IBizOscOrder;
    procedure VerTodos(AOscOrders: IBizOscOrder);
    procedure Ver(AOscOrders: IBizOscOrder);
    function Localizar(AOscOrders: IBizOscOrder; AIDLocal: Integer): Boolean;
    function ExtraerSeleccionados(AOscOrders: IBizOscOrder) : IBizOscOrder;
    function ElegirOscOrders(AOscOrders: IBizOscOrder; AMensaje: String; AMultiSelect: Boolean): IBizOscOrder;

    // Descomentar esto si hay informe
    // procedure Preview(AOscOrders : IBizOscOrder);
    // procedure Print(AOscOrders : IBizOscOrder);   
  end;

implementation

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

{ TOscOrdersController }

{procedure TOscOrdersController.Anadir(AOscOrders: IBizOscOrder);
begin
  AOscOrders.Insert;
end;}

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

procedure TOscOrdersController.AsignarID(AOscOrders: IBizOscOrder;
  const IDNuevo: Integer);
var
  AContador : Integer;
begin
  if not Assigned(AOscOrders) then
    raise Exception.Create ('OscOrders no asignado');

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

  if AOscOrders.EsNuevo then
  begin
    AOscOrders.Edit;
    AOscOrders.customers_id := IDNuevo;
    AOscOrders.Post;
  end;
end;

function TOscOrdersController.BuscarTodos: IBizOscOrder;
begin
  Result := FDataModule.GetOSCOrders;
end;

constructor TOscOrdersController.Create;
begin
  AsignarDataModule;
  
  FOrderProductsController := TOscOrderProductsController.Create;
end;

function TOscOrdersController.Buscar(const IDLocal: Integer): IBizOscOrder;
begin
  Result := FDataModule.GetOSCOrder(IDLocal);
end;

function TOscOrdersController._Vacio: IBizOscOrder;
begin
  Result := Buscar(ID_NULO);
end;

procedure TOscOrdersController.DescartarCambios(AOscOrders: IBizOscOrder);
begin
  if not Assigned(AOscOrders) then
    raise Exception.Create ('OscOrders no asignado');

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

    AOscOrders.DataTable.CancelUpdates;
  finally
    HideHourglassCursor;
  end;
end;

destructor TOscOrdersController.Destroy;
begin
  FDataModule := NIL;
  FOrderProductsController := NIL;
  inherited;
end;


{function TOscOrdersController.Duplicar(AOscOrders: IBizOscOrder): IBizOscOrder;
begin
  Result := Self._Vacio;
  ShowHourglassCursor;
  try
    DuplicarRegistros(AOscOrders.DataTable, Result.DataTable, mdrActual);
    
    // Descomentar esto si hay detalles 
    // DuplicarRegistros(AOscOrders.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 TOscOrdersController.ValidarOscOrders(AOscOrders: IBizOscOrder): Boolean;
begin
  Result := False;

  if not Assigned(AOscOrders) then
    raise Exception.Create ('OscOrders no asignado');

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

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


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

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

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

  Result := True;
end;

procedure TOscOrdersController.Ver(AOscOrders: IBizOscOrder);
{var
  AEditor : IEditorOscOrders;}
begin
{  AEditor := NIL;
  ShowHourglassCursor;
  try
    CreateEditor('EditorOscOrders', IEditorOscOrders, AEditor);
    with AEditor do
      OscOrders := AOscOrders;
  finally
    HideHourglassCursor;
  end;

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

procedure TOscOrdersController.VerTodos(AOscOrders: IBizOscOrder);
{var
  AEditor : IEditorOscOrders;}
begin
{  AEditor := NIL;
  ShowHourglassCursor;
  try
    CreateEditor('EditorOscOrders', IEditorOscOrders, AEditor);
    with AEditor do
      OscOrders := AOscOrders;
  finally
    HideHourglassCursor;
  end;

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

function TOscOrdersController.Eliminar(AOscOrders: IBizOscOrder): Boolean;
begin
  Result := False;

  if not Assigned(AOscOrders) then
    raise Exception.Create ('OscOrders no asignado');

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

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

procedure TOscOrdersController.RecibirAviso(ASujeto: ISujeto; ADataTable: IDAStronglyTypedDataTable);
// Descomentar si hubiera detalles
{var
  AOscOrders : IBizOscOrder;
  ADetalles : IBizDetallesOscOrders;}
begin
  inherited;

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

function TOscOrdersController.Guardar(AOscOrders: IBizOscOrder): Boolean;
var
  NuevoID : Integer;
begin
  Result := False;

  if ValidarOscOrders(AOscOrders) then
  begin
    ShowHourglassCursor;
    try
      if AOscOrders.EsNuevo then
        NuevoID := FDataModule.GetNextIDOSC('customers')
      else
        NuevoID := AOscOrders.customers_id;

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

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

function TOscOrdersController.ExtraerSeleccionados(AOscOrders: IBizOscOrder): IBizOscOrder;
var
  ASeleccionados : IBizOscOrder;
begin
  ASeleccionados := (Self.Buscar(ID_NULO) as IBizOscOrder);
  CopyDataTable(AOscOrders.DataTable, ASeleccionados.DataTable, True);
  Result := ASeleccionados;
end;

function TOscOrdersController.ElegirOscOrders(AOscOrders: IBizOscOrder; AMensaje: String; AMultiSelect: Boolean): IBizOscOrder;
{var
  AEditor : IEditorElegirOscOrders;}
begin
  Result := NIL;

{  CreateEditor('EditorElegirOscOrders', IEditorElegirOscOrders, AEditor);
  try
    with AEditor do
    begin
      OscOrders := AOscOrders;
      MultiSelect := AMultiSelect;
      Mensaje := AMensaje;
      if IsPositiveResult(ShowModal) then
        Result := OscOrdersSeleccionados;
	  Release;
    end;
  finally
    AEditor := NIL;
  end;}
end;

// Descomentar esto si hay informe
// procedure TOscOrdersController.Preview(AOscOrders: IBizOscOrder);
// var
//   AReportController : IOscOrdersReportController;
// begin
//   AReportController := TOscOrdersReportController.Create;
//   try
//     AReportController.Preview(AOscOrders.ID);
//   finally
//     AReportController := NIL;
//   end;
// end;

// Descomentar esto si hay informe
// procedure TOscOrdersController.Print(AOscOrders: IBizOscOrder);
// var
//   AReportController : IOscOrdersReportController;
// begin
//   AReportController := TOscOrdersReportController.Create;
//   try
//     AReportController.Print(AOscOrders.ID);
//   finally
//     AReportController := NIL;
//   end;
// end;

end.
