{*******************************************************************************
Title: T2Ti ERP                                                                 
Description: Controller do lado Cliente relacionado à tabela [FUNCAO] 
                                                                                
The MIT License                                                                 
                                                                                
Copyright: Copyright (C) 2014 T2Ti.COM                                          
                                                                                
Permission is hereby granted, free of charge, to any person                     
obtaining a copy of this software and associated documentation                  
files (the "Software"), to deal in the Software without                         
restriction, including without limitation the rights to use,                    
copy, modify, merge, publish, distribute, sublicense, and/or sell               
copies of the Software, and to permit persons to whom the                       
Software is furnished to do so, subject to the following                        
conditions:                                                                     
                                                                                
The above copyright notice and this permission notice shall be                  
included in all copies or substantial portions of the Software.                 
                                                                                
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,                 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES                 
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND                        
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT                     
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,                    
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING                    
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR                   
OTHER DEALINGS IN THE SOFTWARE.                                                 
                                                                                
       The author may be contacted at:                                          
           t2ti.com@gmail.com                                                   
                                                                                
@author Albert Eije (t2ti.com@gmail.com)                    
@version 2.0                                                                    
*******************************************************************************}
unit FuncaoController;

interface

uses
  Classes, Dialogs, SysUtils, DBClient, DB,  Windows, Forms, Controller, Rtti,
  Atributos, VO, Generics.Collections, FuncaoVO, AdministrativoFormularioVO,
  PapelVO, PapelFuncaoVO;

type
  TFuncaoController = class(TController)
  private
    class var FDataSet: TClientDataSet;
  public
    class procedure VincularFuncoesAosPapeis;

    class procedure Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean = False);
    class function ConsultaLista(pFiltro: String): TObjectList<TFuncaoVO>;
    class function ConsultaObjeto(pFiltro: String): TFuncaoVO;

    class function ConsultaListaFuncao(pFiltro: String): TObjectList<TFuncaoVO>;
    class function ConsultaListaFuncaoComAcesso(pFiltro: String): TObjectList<TFuncaoVO>;

    class procedure Insere(pObjeto: TFuncaoVO);
    class function Altera(pObjeto: TFuncaoVO): Boolean;
    class function VerificaAtualizaFuncoes(pFormularios: TObjectList<TAdministrativoFormularioVO>): Boolean;


    class function Exclui(pId: Integer): Boolean;

    class function GetDataSet: TClientDataSet; override;
    class procedure SetDataSet(pDataSet: TClientDataSet); override;
    class procedure TratarListaRetorno(pListaObjetos: TObjectList<TVO>);
  end;

implementation

uses UDataModule, T2TiORM;

class function TFuncaoController.VerificaAtualizaFuncoes(pFormularios: TObjectList<TAdministrativoFormularioVO>): Boolean;
var
  i, j: Integer;
  objFormulario: TAdministrativoFormularioVO;
  objFuncao: TFuncaoVO;
  Filtro: String;
  ListaFuncoes: TObjectList<TFuncaoVO>;
begin
  try
    for i := 0 to pFormularios.Count - 1 do
    begin
      objFormulario := pFormularios[i];
      for j := 0 to objFormulario.ListaFuncaoVO.Count - 1 do
      begin
        Filtro := 'NOME = ' +  QuotedStr(objFormulario.ListaFuncaoVO[j].Nome) + ' AND FORMULARIO = ' + QuotedStr(objFormulario.NomeFormulario);

        ListaFuncoes := TT2TiORM.Consultar<TFuncaoVO>(Filtro, '-1', False);
        try
          if ListaFuncoes.Count = 0 then
          begin
            objFuncao := objFormulario.ListaFuncaoVO[j];
            TT2TiORM.Inserir(objFuncao);
          end;
        finally
          ListaFuncoes.Free;
        end;
      end;
    end;
  finally
  end;

  VincularFuncoesAosPapeis;
end;

class procedure TFuncaoController.VincularFuncoesAosPapeis;
var
  IdPapel: Integer;
  IdFuncao: Integer;
  ListaPapel: TObjectList<TPapelVO>;
  ListaFuncao: TObjectList<TFuncaoVO>;
  ListaPapelFuncao: TObjectList<TPapelFuncaoVO>;
  EnumeratorPapel: TEnumerator<TPapelVO>;
  EnumeratorFuncao: TEnumerator<TFuncaoVO>;
  PapelFuncao: TPapelFuncaoVO;
begin
  // Lista todos os Papeis
  ListaPapel := TT2TiORM.Consultar<TPapelVO>('', '-1', False);
  try
    ListaFuncao := TT2TiORM.Consultar<TFuncaoVO>('', '-1', False);
    try
      // Percorre lista de Papeis
      EnumeratorPapel := ListaPapel.GetEnumerator;
      try
        with EnumeratorPapel do
        begin
          while MoveNext do
          begin
            if Current.AcessoCompleto <> 'S' then
            begin
              // Armazena o ID do Papel
              IdPapel := Current.Id;

              // Percorre funções para verificar e existe alguma sem vinculo
              EnumeratorFuncao := ListaFuncao.GetEnumerator;
              try
                with EnumeratorFuncao do
                begin
                  while MoveNext do
                  begin
                    // Armazena o ID da função
                    IdFuncao := Current.Id;

                    // Lista Funcoes e Papeis Vinculados
                    ListaPapelFuncao := TT2TiORM.Consultar<TPapelFuncaoVO>('ID_PAPEL = ' + IntToStr(IdPapel) + ' AND ID_FUNCAO = ' + IntToStr(IdFuncao), '-1', False);
                    try
                      // Se a função não estiver vinculada, vincula...
                      if ListaPapelFuncao.Count = 0 then
                      begin
                        PapelFuncao := TPapelFuncaoVO.Create;
                        try
                          PapelFuncao.IdPapel := IdPapel;
                          PapelFuncao.IdFuncao := IdFuncao;
                          PapelFuncao.Habilitado := 'N';
                          TT2TiORM.Inserir(PapelFuncao);
                        finally
                          PapelFuncao.Free;
                        end;
                      end;
                    finally
                      ListaPapelFuncao.Free;
                    end;
                  end;
                end;
              finally
                EnumeratorFuncao.Free;
              end;
            end;
          end;
        end;
      finally
        EnumeratorPapel.Free;
      end;
    finally
      ListaFuncao.Free;
    end;
  finally
    ListaPapel.Free;
  end;
end;

class procedure TFuncaoController.Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean);
var
  Retorno: TObjectList<TFuncaoVO>;
begin
  try
    Retorno := TT2TiORM.Consultar<TFuncaoVO>(pFiltro, pPagina, pConsultaCompleta);
    TratarRetorno<TFuncaoVO>(Retorno);
  finally
  end;
end;

class function TFuncaoController.ConsultaLista(pFiltro: String): TObjectList<TFuncaoVO>;
begin
  try
    Result := TT2TiORM.Consultar<TFuncaoVO>(pFiltro, '-1', True);
  finally
  end;
end;

class function TFuncaoController.ConsultaListaFuncao(pFiltro: String): TObjectList<TFuncaoVO>;
var
  SQL: String;
begin
  try
    SQL := 'SELECT DISTINCT F.ID, F.FORMULARIO, F.NOME, PF.HABILITADO ' +
           'FROM USUARIO U ' +
           'INNER JOIN PAPEL P ON (P.ID = U.ID_PAPEL) ' +
           'INNER JOIN PAPEL_FUNCAO PF ON (PF.ID_PAPEL = P.ID) ' +
           'INNER JOIN FUNCAO F ON (F.ID = PF.ID_FUNCAO) ';

    Result := TT2TiORM.Consultar<TFuncaoVO>(SQL, 'U.ID = ' + IntToStr(Sessao.Usuario.Id), -1);
  finally
  end;
end;

class function TFuncaoController.ConsultaListaFuncaoComAcesso(pFiltro: String): TObjectList<TFuncaoVO>;
var
  SQL: String;
begin
  try
    SQL := 'SELECT DISTINCT F.ID, F.FORMULARIO, F.NOME, PF.HABILITADO ' +
           'FROM USUARIO U ' +
           'INNER JOIN PAPEL P ON (P.ID = U.ID_PAPEL) ' +
           'INNER JOIN PAPEL_FUNCAO PF ON (PF.ID_PAPEL = P.ID) ' +
           'INNER JOIN FUNCAO F ON (F.ID = PF.ID_FUNCAO) ';

    Result := TT2TiORM.Consultar<TFuncaoVO>(SQL, 'PF.HABILITADO = ' + QuotedStr('S') + ' AND U.ID = ' + IntToStr(Sessao.Usuario.Id), -1);
  finally
  end;
end;

class function TFuncaoController.ConsultaObjeto(pFiltro: String): TFuncaoVO;
begin
  try
    Result := TT2TiORM.ConsultarUmObjeto<TFuncaoVO>(pFiltro, True);
  finally
  end;
end;

class procedure TFuncaoController.Insere(pObjeto: TFuncaoVO);
var
  UltimoID: Integer;
begin
  try
    UltimoID := TT2TiORM.Inserir(pObjeto);
    Consulta('ID = ' + IntToStr(UltimoID), '0');
  finally
  end;
end;

class function TFuncaoController.Altera(pObjeto: TFuncaoVO): Boolean;
begin
  try
    Result := TT2TiORM.Alterar(pObjeto);
  finally
  end;
end;

class function TFuncaoController.Exclui(pId: Integer): Boolean;
var
  ObjetoLocal: TFuncaoVO;
begin
  try
    ObjetoLocal := TFuncaoVO.Create;
    ObjetoLocal.Id := pId;
    Result := TT2TiORM.Excluir(ObjetoLocal);
    TratarRetorno(Result);
  finally
    FreeAndNil(ObjetoLocal)
  end;
end;

class function TFuncaoController.GetDataSet: TClientDataSet;
begin
  Result := FDataSet;
end;

class procedure TFuncaoController.SetDataSet(pDataSet: TClientDataSet);
begin
  FDataSet := pDataSet;
end;

class procedure TFuncaoController.TratarListaRetorno(pListaObjetos: TObjectList<TVO>);
begin
  try
    TratarRetorno<TFuncaoVO>(TObjectList<TFuncaoVO>(pListaObjetos));
  finally
    FreeAndNil(pListaObjetos);
  end;
end;

initialization
  Classes.RegisterClass(TFuncaoController);

finalization
  Classes.UnRegisterClass(TFuncaoController);

end.
