unit CadUsuario;

interface

uses
  Windows, system.UItypes, IB_Access,  Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ModeloCadastro, IB_Components, Grids, IB_Grid, StdCtrls,
  Buttons, ExtCtrls, ComCtrls, IB_Controls, Mask, jpeg, AppEvnts, Menus,
  ImgList, Spin,UCBase,UserPermis_U, IB_EditButton, System.ImageList;

type
  TfrmCadUsuario = class(TFrModeloCadastro)
    edtSkype: TIB_Edit;
    edtDataCad: TIB_Edit;
    edtNome: TIB_Edit;
    edtEmail: TIB_Edit;
    qrSetor: TIB_Query;
    dstSetor: TIB_DataSource;
    edtSetor: TIB_LookupCombo;
    edtDataSaida: TIB_Date;
    GroupBox1: TGroupBox;
    edtCep: TIB_Edit;
    edtComplemento: TIB_Edit;
    edtCidade: TIB_Edit;
    edtBairro: TIB_Edit;
    edtEndereco: TIB_Edit;
    edtNumero: TIB_Edit;
    GroupBox2: TGroupBox;
    dbCodigo: TIB_Text;
    popSetor: TPopupMenu;
    CadastrarSetor1: TMenuItem;
    popPesquisaCep: TPopupMenu;
    PesquisaCEP1: TMenuItem;
    PesquisarSetor1: TMenuItem;
    qrPerfil: TIB_Query;
    dsrPerfil: TIB_DataSource;
    ComboStatus: TComboBox;
    Label4: TLabel;
    btnAcesso: TBitBtn;
    GroupBox3: TGroupBox;
    edtApelido: TIB_Edit;
    edtSenha: TIB_Edit;
    edtConfirmeSenha: TEdit;
    Label3: TLabel;
    edtPerfil: TIB_LookupCombo;
    btnPsquisaClienteOrigem: TBitBtn;
    ckUserExpired: TCheckBox;
    SpinExpira: TSpinEdit;
    ckPrivilegiado: TCheckBox;
    qrUF: TIB_Query;
    dsrUF: TIB_DataSource;
    edtUF: TIB_LookupCombo;
    BitBtn1: TBitBtn;
    edtcpf: TIB_Edit;
    IB_Edit4: TIB_Edit;
    dbAcesso: TIB_ComboBox;
    procedure edtCepExit(Sender: TObject);
    procedure BtGravarClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure AtualizaTela;
    procedure BtAnteriorClick(Sender: TObject);
    procedure BtProximoClick(Sender: TObject);
    procedure BtInserirClick(Sender: TObject);
    procedure BtEditarClick(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure edtSetorExit(Sender: TObject);
    procedure btnEditar2Click(Sender: TObject);
    procedure CadastrarSetor1Click(Sender: TObject);
    procedure edtCepKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure PesquisarSetor1Click(Sender: TObject);
    procedure edtSetorKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure btnAcessoClick(Sender: TObject);
    procedure BtCancelarClick(Sender: TObject);
    procedure btnPsquisaClienteOrigemClick(Sender: TObject);
    procedure FormActivate(Sender: TObject);
    procedure BtExcluirClick(Sender: TObject);
    procedure BitBtn1Click(Sender: TObject);
  private
   procedure SetWindowUserProfile;
   procedure ActionBtPermissUserDefault;

  public
    { Public declarations }
  end;

var
  frmCadUsuario: TfrmCadUsuario;

implementation

uses DataModulo, Rotinas, ModeloPesquisa, Principal, CadSetor;

{$R *.dfm}

procedure TfrmCadUsuario.edtCepExit(Sender: TObject);
begin
  inherited;
  if ValidarCep(edtCep.Text) = False then
  begin
    MessageDlg('CEP inválido', mtInformation, [mbOK], 0);
    edtCep.SetFocus;
    Exit;
  end;
  
  if edtEndereco.Text <> '' then
     Exit;
end;

procedure TfrmCadUsuario.BtGravarClick(Sender: TObject);
var
  ModificouSenha: Boolean;
  vNovaSenha:    String;
  vNome:         String;
  vLogin:        String;
  vEmail:        String;
  vUserExpired:  Integer;
  vPerfil:       Integer;
  vPrivilegiado: Boolean;
  vNovoIDUsuario : Integer;
  EncryptKey : Word;
begin
   if edtNome.Text = '' then
   begin
      MessageDlg('Informe o nome do usuário', mtWarning, [mbOK], 0);
      edtNome.SetFocus;
      Exit;
   end;

   if edtSenha.Text = '' then
   begin
      MessageDlg('A senha é obrigatória', mtWarning, [mbOK], 0);
      edtSenha.Clear;
      edtSenha.SetFocus;
      Exit;
   end;

   if edtSenha.Text <> edtConfirmeSenha.Text then
   begin
      MessageDlg('Confirmação de senha inválida'+#13+#10+'A senha e a confirmação de senha devem ser a mesma', mtWarning, [mbOK], 0);
      edtConfirmeSenha.Clear;
      edtSenha.Clear;
      edtSenha.SetFocus;
      Exit;
   end;

   if Trim(edtEmail.Text) <> '' then
   begin
      if Pos('@',edtEmail.text ) = 0 then
      begin
         MessageDlg('O E-mail cadastrado não é válido.', mtWarning, [mbOK], 0);
         Exit;
      end;
   end;

   if edtUF.Text <> '' then
      TbPrincipal.FieldByName('COD_UF').Value := qrUF.FieldByName('COD_UF').Value
   else
      TbPrincipal.FieldByName('COD_UF').Value := Null;
   
   vNovaSenha     := edtConfirmeSenha.Text;
   vNovoIDUsuario := TbPrincipal.FieldByName('COD_USUARIO').AsInteger;
   vNome          := edtNome.Text;
   vLogin         := edtApelido.Text;
   vEmail         := edtEmail.Text;
   vPerfil        := qrPerfil.FieldByName('COD_USUARIO').AsInteger;

   vPrivilegiado := ckPrivilegiado.Checked;
   vUserExpired  := StrToInt(BoolToStr(ckUserExpired.Checked));

   TbPrincipal.FieldByName('UCTYPEREC').Value     := 'U';
   TbPrincipal.FieldByName('UCPROFILE').AsInteger := qrPerfil.FieldByName('COD_USUARIO').AsInteger;

   if edtSenha.Field.IsModified then
      ModificouSenha := True
   else
      ModificouSenha := False;

   TbPrincipal.FieldByName('cod_setor').Value  := qrSetor.FieldByName('cod_setor').Value;

   if TbPrincipal.State in [dssInsert] then
   begin
      descricao_auditoria := 'CADASTROU O USUARIO '   + TbPrincipal.FieldByName('nome').AsString    + ' ' +
                            'LOGIN '+ TbPrincipal.FieldByName('LOGIN').AsString + ' ' +
                            'CÓDIGO ' +TbPrincipal.FieldByName('cod_usuario').AsString;
   end;

   if TbPrincipal.State in [dssedit] then
   begin
      descricao_auditoria := 'ALTEROU O USUARIO '   + TbPrincipal.FieldByName('nome').OldAsString    + ' ' +
                            'LOGIN '+ TbPrincipal.FieldByName('LOGIN').OldAsString + ' ' +
                            'CÓDIGO ' +TbPrincipal.FieldByName('cod_usuario').OldAsString;
   end;

   if (TbPrincipal.State in [dssInsert]) and (frmPrincipal.MailUserControl1.AdicionaUsuario.Ativo) then
   begin
      if Trim(edtEmail.Text )<> '' then
      begin
         EncryptKey :=  frmPrincipal.UserControl1.EncryptKey;
         try
            frmPrincipal.MailUserControl1.EnviaEmailAdicionaUsuario(vNome, vLogin, Encrypt(vNovaSenha, EncryptKey) , vEmail, IntToStr(vPerfil), EncryptKey);
            except
         end;
      end
   end;


   inherited;

   frmPrincipal.UserControl1.ChangeUser(vNovoIDUsuario, vLogin, vNome, vEmail, vPerfil, vUserExpired, SpinExpira.Value, ComboStatus.ItemIndex, vPrivilegiado);
   if ModificouSenha then
      frmPrincipal.UserControl1.ChangePassword(vNovoIDUsuario, vNovaSenha);
      
   AtualizaTela;
   btnAcesso.Visible := True;
end;

procedure TfrmCadUsuario.FormCreate(Sender: TObject);
begin
   if Dados.qrUsuario.FieldByName('LOGIN').AsString  <> 'SYSTEMS' then
   begin
      TbPrincipal.Filter := ' LOGIN <> ' + QuotedStr('SYSTEMS');
      TbPrincipal.Filtered := True;
   end;
   Gera_Codigo  := True;
   inherited;
   qrSetor.Open;
   qrPerfil.Open;
   qrUF.Open;

end;

procedure TfrmCadUsuario.AtualizaTela;
begin
   //================= Atualiza a visualizacao dos dados ===========
   if not qrSetor.Locate('cod_setor',TbPrincipal.FieldByName('cod_setor').Value , []) then
   begin
      if not qrSetor.Bof then
      begin
         qrSetor.First;
         qrSetor.Prior;
      end;
   end;

   edtConfirmeSenha.Text := TbPrincipal.FieldByName('SENHA').AsString;

   ComboStatus.ItemIndex := TbPrincipal.FieldByName('UCINATIVE').AsInteger;

   SpinExpira.Value := TbPrincipal.FieldByName('DIAS_PARA_EXPIRAR').AsInteger;

   if TbPrincipal.FieldByName('SENHA_EXPIRA').AsInteger = 0 then
      ckUserExpired.Checked := False
   else
      ckUserExpired.Checked := True;

   if TbPrincipal.FieldByName('UCPRIVILEGED').AsInteger = 0 then
      ckPrivilegiado.Checked := False
   else
      ckPrivilegiado.Checked := True;

   if not qrPerfil.Locate('cod_usuario', TbPrincipal.FieldByName('UCPROFILE').Value,[] ) then
   begin
      if not qrPerfil.Bof then
      begin
         qrPerfil.First;
         qrPerfil.Prior;
      end;
   end;

   if not qrUF.Locate('COD_UF', tbprincipal.FieldByName('COD_UF').Value , [] ) then
   begin
      if not qrUF.Bof then
      begin
         qrUF.First;
         qrUF.Prior;
      end;
   end;
   
end;

procedure TfrmCadUsuario.BtAnteriorClick(Sender: TObject);
begin
  inherited;
   AtualizaTela;
end;

procedure TfrmCadUsuario.BtProximoClick(Sender: TObject);
begin
   inherited;
   AtualizaTela;
end;

procedure TfrmCadUsuario.BtInserirClick(Sender: TObject);
begin
   inherited;

   TbPrincipal.FieldByName('data_cadastro').Value := Date;
   AtualizaTela;
   edtDataSaida.ReadOnly:=True;
   btnAcesso.Visible     := False;
end;

procedure TfrmCadUsuario.BtEditarClick(Sender: TObject);
begin
  inherited;
   AtualizaTela;
   btnAcesso.Visible := True;
end;

procedure TfrmCadUsuario.FormDestroy(Sender: TObject);
begin
  inherited;
   Dados.qrUsuario.Close;
   Dados.qrUsuario.Open;
   Dados.qrUsuario.Locate('COD_USUARIO' , frmPrincipal.UserControl1.CurrentUser.UserID , [] );
end;

procedure TfrmCadUsuario.edtSetorExit(Sender: TObject);
begin
  inherited;
   if TbPrincipal.State in [dssBrowse] then
   begin
      if not qrSetor.Locate('COD_SETOR',TbPrincipal.FieldByName('COD_SETOR').Value,[]) then
      begin
         if qrSetor.Bof then
         begin
            qrSetor.First;
            qrSetor.Prior;
         end;
      end;
   end;
end;

procedure TfrmCadUsuario.btnEditar2Click(Sender: TObject);
begin
  edtDataSaida.ReadOnly :=True;
  btnAcesso.Visible     := False;
  inherited;
end;

procedure TfrmCadUsuario.CadastrarSetor1Click(Sender: TObject);
var cod : Integer;
begin
  inherited;
   frmCadSetor := TfrmCadSetor.Create(Application);
   frmCadSetor.OutraTela := True;
   frmCadSetor.BtInserir.Click;
   frmCadSetor.ShowModal;
   cod := frmCadSetor.TbPrincipal.FieldByName('COD_SETOR').Value;
   frmCadSetor.Destroy;
   Screen.OnActiveControlChange := TrocaCor;
   qrSetor.RefreshAll;
   qrSetor.Locate('COD_SETOR',cod , []);
   Screen.OnActiveControlChange := TrocaCor;
end;

procedure TfrmCadUsuario.edtCepKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  inherited;
   if TbPrincipal.State in [dssBrowse] then
      Exit;
   if (Key =  VerificaAtalho(Dados.tbConfig.FieldByName('ATALHO_PESQUISA').AsString)) and (edtCep.Focused )then
      PesquisaCEP1.Click;
end;

procedure TfrmCadUsuario.PesquisarSetor1Click(Sender: TObject);
begin
  inherited;
   //==================== Pesquisa setores ============
   frmModeloPesquisa        := TfrmModeloPesquisa.Create(Application);
   frmModeloPesquisa.Tabela := qrSetor;
   frmModeloPesquisa.lbltitulo.Caption := 'Pesquisa Setores';
   if frmModeloPesquisa.ShowModal = mrok then
   begin
      qrSetor.Locate('COD_SETOR', frmModeloPesquisa.TbPrincipal.FieldByName('COD_SETOR').Value ,[]);

   end;
   frmModeloPesquisa.Destroy;
   Screen.OnActiveControlChange := TrocaCor;

end;

procedure TfrmCadUsuario.edtSetorKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  inherited;
   if TbPrincipal.State in [DssBrowse] then
      Exit;

   if (Key =  VerificaAtalho(Dados.tbConfig.FieldByName('ATALHO_PESQUISA').AsString)) and (edtSetor.Focused)then
    PesquisarSetor1Click(SELF)

end;

procedure TfrmCadUsuario.SetWindowUserProfile;
begin
  with   frmPrincipal.UserControl1.UserSettings.Rights do
  begin
    UserPermis.Caption              := WindowCaption;
    UserPermis.LbDescricao.Caption  := LabelUser;
    UserPermis.lbUser.Left          := UserPermis.LbDescricao.Left + UserPermis.LbDescricao.Width + 5;
    UserPermis.PageMenu.Caption     := PageMenu;
    UserPermis.PageAction.Caption   := PageActions;
    UserPermis.PageControls.Caption := PageControls; // By Vicente Barros Leonel
    UserPermis.BtLibera.Caption     := BtUnlock;
    UserPermis.BtBloqueia.Caption   := BtLOck;
    UserPermis.BtGrava.Caption      := BtSave;
    UserPermis.BtCancel.Caption     := BtCancel;
    UserPermis.Position             := frmPrincipal.UserControl1.UserSettings.WindowsPosition;
  end;
end;

procedure TfrmCadUsuario.ActionBtPermissUserDefault;
var
  TempCampos, TempCamposEX: String;
begin
  UserPermis.FTempIdUser := TbPrincipal.FieldByName('COD_USUARIO').AsInteger;
  with frmPrincipal.UserControl1 do
  begin
    TempCampos   := Format(' %s as IdUser, %s as Modulo, %s as ObjName, %s as UCKey ', [TableRights.FieldUserID,
      TableRights.FieldModule, TableRights.FieldComponentName, TableRights.FieldKey]);
    TempCamposEX := Format(' %s, %s as FormName ', [TempCampos, TableRights.FieldFormName]);

    UserPermis.DSPermiss := DataConnector.UCGetSQLDataset(Format('SELECT %s FROM %s TAB WHERE TAB.%s = %s AND TAB.%s = %s',
      [TempCampos, TableRights.TableName, TableRights.FieldUserID, TbPrincipal.FieldByName('COD_USUARIO').AsString,
      TableRights.FieldModule, QuotedStr(ApplicationID)]));
    UserPermis.DSPermiss.Open;

    UserPermis.DSPermissEX := DataConnector.UCGetSQLDataset(Format('SELECT %s FROM %s TAB1 WHERE TAB1.%s = %s AND TAB1.%s = %s',
      [TempCamposEX, TableRights.TableName + 'EX', TableRights.FieldUserID, TbPrincipal.FieldByName('COD_USUARIO').AsString,
      TableRights.FieldModule, QuotedStr(ApplicationID)]));
    UserPermis.DSPermissEX.Open;

    UserPermis.DSPerfil := DataConnector.UCGetSQLDataset(Format('Select %s from %s tab Where tab.%s = %s and tab.%s = %s',
      [TempCampos, TableRights.TableName, TableRights.FieldUserID, TbPrincipal.FieldByName('UCPROFILE').AsString,
      TableRights.FieldModule, QuotedStr(ApplicationID)]));
    UserPermis.DSPerfil.Open;

    UserPermis.DSPerfilEX := DataConnector.UCGetSQLDataset(Format('Select %s from %s tab1 Where tab1.%s = %s and tab1.%s = %s',
      [TempCamposEX, TableRights.TableName + 'EX', TableRights.FieldUserID, TbPrincipal.FieldByName('UCPROFILE').AsString,
      TableRights.FieldModule, QuotedStr(ApplicationID)]));

    UserPermis.DSPerfilEX.Open;

    UserPermis.ShowModal;

    TbPrincipal.Close;
    TbPrincipal.Open;

    TbPrincipal.Locate('COD_USUARIO', UserPermis.FTempIdUser, []);

    //FreeAndNil(UserPermis);
  end;
end;

procedure TfrmCadUsuario.btnAcessoClick(Sender: TObject);
begin
  inherited;
  if TbPrincipal.IsEmpty then
     Exit;

  UserPermis              := TUserPermis.Create(self);
  UserPermis.FUsercontrol := frmPrincipal.UserControl1;
  SetWindowUserProfile;
  UserPermis.lbUser.Caption :=  TbPrincipal.FieldByName('Login').AsString;
  ActionBtPermissUserDefault;
end;

procedure TfrmCadUsuario.BtCancelarClick(Sender: TObject);
begin
  inherited;
   btnAcesso.Visible := True;
   AtualizaTela;
end;

procedure TfrmCadUsuario.btnPsquisaClienteOrigemClick(Sender: TObject);
begin
  inherited;
   frmModeloPesquisa        := TfrmModeloPesquisa.Create(Application);
   frmModeloPesquisa.Tabela := qrPerfil;
   frmModeloPesquisa.lblTitulo.Caption  := 'Pesquisa Perfil de Acesso';
   if frmModeloPesquisa.ShowModal = mrOk then
      qrPerfil.Locate('COD_USUARIO' , frmModeloPesquisa.TbPrincipal.FieldByName('COD_USUARIO').Value , []);
   frmModeloPesquisa.Destroy;

   Screen.OnActiveControlChange := TrocaCor;
end;

procedure TfrmCadUsuario.FormActivate(Sender: TObject);
begin
  inherited;
  if frmPrincipal.UserControl1.CurrentUser.UserName = 'SYSTEMS' then
  begin
     BtEditar.Enabled   := True;
     BtInserir.Enabled  := True;
     btnEditar2.Enabled := True;
     btnAcesso.Enabled  := True;
     BtExcluir.Enabled  := True;
  end;
end;

procedure TfrmCadUsuario.BtExcluirClick(Sender: TObject);
begin
  inherited;
   AtualizaTela
end;

procedure TfrmCadUsuario.BitBtn1Click(Sender: TObject);
begin
  inherited;
   frmModeloPesquisa        := TfrmModeloPesquisa.Create(Application);
   frmModeloPesquisa.Tabela := qrSetor;
   frmModeloPesquisa.lblTitulo.Caption  := 'Pesquisa Setor';
   if frmModeloPesquisa.ShowModal = mrOk then
      qrSetor.Locate('COD_SETOR' , frmModeloPesquisa.TbPrincipal.FieldByName('COD_SETOR').Value , []);
   frmModeloPesquisa.Destroy;

   Screen.OnActiveControlChange := TrocaCor;

end;

end.
