409 lines
17 KiB
C#
409 lines
17 KiB
C#
using CPM;
|
|
using DAL;
|
|
using MLL;
|
|
using BLL;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Drawing;
|
|
using System.Windows.Forms;
|
|
|
|
namespace UI
|
|
{
|
|
public class UsuariosCadastroPanel : FormularioModelo
|
|
{
|
|
// ── CAMPOS DO FORMULÁRIO ──────────────────────────────────────────────
|
|
private LV_TEXTBOX1 txtId = null!;
|
|
private LV_TEXTBOX1 txtNome = null!;
|
|
private LV_TEXTBOX1 txtEmail = null!;
|
|
private LV_TEXTBOX1 txtUsuario = null!;
|
|
private LV_TEXTBOX1 txtSenha = null!;
|
|
private LV_TEXTBOX1 txtUltimoLogin = null!;
|
|
private LV_TEXTBOX1 txtCriadoEm = null!;
|
|
private CheckBox chkAtivo = null!;
|
|
private LV_COMBOBOXCUSTOM cmbPerfil = null!;
|
|
|
|
// ── ESTADO DO FORMULÁRIO ──────────────────────────────────────────────
|
|
private enum ModoFormulario { Visualizacao, Novo, Edicao }
|
|
private ModoFormulario _modo = ModoFormulario.Visualizacao;
|
|
private int _usuarioAtualId = 0;
|
|
|
|
// ── BLL ───────────────────────────────────────────────────────────────
|
|
// Substitua pelos seus serviços reais quando implementar
|
|
// private UsuarioBLL _usuarioBLL = null!;
|
|
// private PerfilBLL _perfilBLL = null!;
|
|
|
|
// ── CONSTRUTOR ────────────────────────────────────────────────────────
|
|
public UsuariosCadastroPanel()
|
|
{
|
|
Titulo = "Cadastro de Usuários";
|
|
BuildForm();
|
|
AplicarModo(ModoFormulario.Visualizacao);
|
|
}
|
|
|
|
// ── CONSTRUÇÃO DOS CAMPOS ─────────────────────────────────────────────
|
|
private void BuildForm()
|
|
{
|
|
// ── SEÇÃO: IDENTIFICAÇÃO ──────────────────────────────────────────
|
|
content.Controls.Add(CreateSectionHeader("Identificação", 20));
|
|
|
|
txtId = AddInput(content, "ID", 20, 58, 80, 32, readOnly: true);
|
|
|
|
txtNome = AddInput(content, "Nome completo", 120, 58, 320, 32);
|
|
txtNome.MaxLength = 255;
|
|
|
|
txtEmail = AddInput(content, "E-mail", 460, 58, 280, 32);
|
|
txtEmail.MaxLength = 150;
|
|
|
|
// ── SEÇÃO: ACESSO ─────────────────────────────────────────────────
|
|
content.Controls.Add(CreateSectionHeader("Acesso ao sistema", 120));
|
|
|
|
txtUsuario = AddInput(content, "Usuário (login)", 20, 158, 200, 32);
|
|
txtUsuario.MaxLength = 50;
|
|
|
|
txtSenha = AddInput(content, "Senha", 240, 158, 200, 32);
|
|
txtSenha.PasswordChar = '●';
|
|
txtSenha.MaxLength = 255;
|
|
|
|
// Perfil — LV_COMBOBOXCUSTOM
|
|
var lblPerfil = new Label
|
|
{
|
|
Text = "Perfil de acesso",
|
|
Location = new Point(460, 158),
|
|
Font = new Font("Segoe UI", 7.5f, FontStyle.Bold),
|
|
ForeColor = TextDark,
|
|
AutoSize = true
|
|
};
|
|
|
|
cmbPerfil = new LV_COMBOBOXCUSTOM
|
|
{
|
|
Location = new Point(460, 174),
|
|
Size = new Size(280, 32),
|
|
DropDownStyle = ComboBoxStyle.DropDownList,
|
|
BorderColor = BorderColor,
|
|
BackColor = Color.White,
|
|
ListBackColor = Color.White,
|
|
ListTextColor = TextDark,
|
|
IconColor = AccentBlue,
|
|
Font = new Font("Segoe UI", 9f)
|
|
};
|
|
|
|
content.Controls.Add(lblPerfil);
|
|
content.Controls.Add(cmbPerfil);
|
|
|
|
// ── SEÇÃO: STATUS ─────────────────────────────────────────────────
|
|
content.Controls.Add(CreateSectionHeader("Status", 230));
|
|
|
|
chkAtivo = CreateCheckBox("Usuário ativo", 20, 268);
|
|
chkAtivo.Checked = true;
|
|
content.Controls.Add(chkAtivo);
|
|
|
|
// ── SEÇÃO: AUDITORIA (somente leitura) ────────────────────────────
|
|
content.Controls.Add(CreateSectionHeader("Auditoria", 310));
|
|
|
|
txtUltimoLogin = AddInput(content, "Último login", 20, 348, 200, 32, readOnly: true);
|
|
txtCriadoEm = AddInput(content, "Criado em", 240, 348, 200, 32, readOnly: true);
|
|
|
|
// Ajusta altura do content
|
|
content.Height = 420;
|
|
}
|
|
|
|
// ── CARREGAR PERFIS DO BANCO ──────────────────────────────────────────
|
|
private void CarregarPerfis()
|
|
{
|
|
cmbPerfil.Items.Clear();
|
|
cmbPerfil.Items.Add(new ComboItem(0, "— Selecione um perfil —"));
|
|
|
|
try
|
|
{
|
|
// TODO: substituir pela chamada real à BLL
|
|
// var perfis = _perfilBLL.ListarAtivosPorEmpresa(empresaId);
|
|
// foreach (var p in perfis)
|
|
// cmbPerfil.Items.Add(new ComboItem(p.Id, p.Nome));
|
|
|
|
// ── Exemplo estático para desenvolvimento ──
|
|
cmbPerfil.Items.Add(new ComboItem(1, "Administrador"));
|
|
cmbPerfil.Items.Add(new ComboItem(2, "Técnico"));
|
|
cmbPerfil.Items.Add(new ComboItem(3, "Vendedor"));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
MessageBox.Show($"Erro ao carregar perfis:\n{ex.Message}",
|
|
"Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
|
}
|
|
|
|
cmbPerfil.SelectedIndex = 0;
|
|
}
|
|
|
|
// ── MODOS DO FORMULÁRIO ───────────────────────────────────────────────
|
|
private void AplicarModo(ModoFormulario modo)
|
|
{
|
|
_modo = modo;
|
|
|
|
bool editando = modo == ModoFormulario.Novo || modo == ModoFormulario.Edicao;
|
|
bool isNovo = modo == ModoFormulario.Novo;
|
|
|
|
// Campos editáveis conforme o modo
|
|
txtNome.ReadOnly = !editando;
|
|
txtEmail.ReadOnly = !editando;
|
|
txtUsuario.ReadOnly = !editando;
|
|
txtSenha.ReadOnly = !editando;
|
|
cmbPerfil.Enabled = editando;
|
|
cmbPerfil.BorderColor = editando ? BorderColor : ReadOnlyBorder;
|
|
cmbPerfil.BackColor = editando ? Color.White : ReadOnlyBg;
|
|
chkAtivo.Enabled = editando;
|
|
|
|
// Cor de fundo dos campos conforme readonly
|
|
Color bgAtivo = Color.White;
|
|
Color bgInativo = ReadOnlyBg;
|
|
|
|
txtNome.BackColor = editando ? bgAtivo : bgInativo;
|
|
txtEmail.BackColor = editando ? bgAtivo : bgInativo;
|
|
txtUsuario.BackColor = editando ? bgAtivo : bgInativo;
|
|
txtSenha.BackColor = editando ? bgAtivo : bgInativo;
|
|
|
|
// Senha: só obrigatória no cadastro novo
|
|
// Na edição, deixar em branco = manter senha atual
|
|
if (modo == ModoFormulario.Edicao)
|
|
{
|
|
var lblSenha = content.Controls.Find("lblSenhaInfo", true);
|
|
// Opcional: exibir aviso "deixe em branco para manter a senha"
|
|
}
|
|
|
|
// Botões
|
|
btnNovo.Enabled = !editando;
|
|
btnAlterar.Enabled = !editando && _usuarioAtualId > 0;
|
|
btnExcluir.Enabled = !editando && _usuarioAtualId > 0;
|
|
btnLocalizar.Enabled = !editando;
|
|
btnSalvar.Enabled = editando;
|
|
btnCancelar.Enabled = editando;
|
|
|
|
// No modo Novo limpa os campos
|
|
if (isNovo) LimparCampos();
|
|
}
|
|
|
|
// ── POPULAR CAMPOS COM UM USUÁRIO ─────────────────────────────────────
|
|
private void PopularCampos(ModeloUsuario u, int perfilId)
|
|
{
|
|
_usuarioAtualId = u.Id;
|
|
|
|
txtId.Text = u.Id.ToString();
|
|
txtNome.Text = u.Nome;
|
|
txtEmail.Text = u.Email;
|
|
txtUsuario.Text = u.Usuario;
|
|
txtSenha.Text = string.Empty; // nunca exibe hash
|
|
chkAtivo.Checked = u.Ativo;
|
|
txtUltimoLogin.Text = u.UltimoLogin.HasValue
|
|
? u.UltimoLogin.Value.ToString("dd/MM/yyyy HH:mm")
|
|
: "Nunca";
|
|
txtCriadoEm.Text = u.CriadoEm.ToString("dd/MM/yyyy HH:mm");
|
|
|
|
// Seleciona o perfil no ComboBox
|
|
for (int i = 0; i < cmbPerfil.Items.Count; i++)
|
|
{
|
|
if (cmbPerfil.Items[i] is ComboItem item && item.Id == perfilId)
|
|
{
|
|
cmbPerfil.SelectedIndex = i;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
private void LimparCampos()
|
|
{
|
|
_usuarioAtualId = 0;
|
|
txtId.Text = string.Empty;
|
|
txtNome.Text = string.Empty;
|
|
txtEmail.Text = string.Empty;
|
|
txtUsuario.Text = string.Empty;
|
|
txtSenha.Text = string.Empty;
|
|
chkAtivo.Checked = true;
|
|
txtUltimoLogin.Text = string.Empty;
|
|
txtCriadoEm.Text = string.Empty;
|
|
if (cmbPerfil.Items.Count > 0)
|
|
cmbPerfil.SelectedIndex = 0;
|
|
}
|
|
|
|
// ── VALIDAÇÃO ─────────────────────────────────────────────────────────
|
|
private bool Validar()
|
|
{
|
|
if (string.IsNullOrWhiteSpace(txtNome.Text))
|
|
{
|
|
MessageBox.Show("Informe o nome do usuário.", "Validação",
|
|
MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
|
txtNome.Focus();
|
|
return false;
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(txtEmail.Text))
|
|
{
|
|
MessageBox.Show("Informe o e-mail.", "Validação",
|
|
MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
|
txtEmail.Focus();
|
|
return false;
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(txtUsuario.Text))
|
|
{
|
|
MessageBox.Show("Informe o login do usuário.", "Validação",
|
|
MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
|
txtUsuario.Focus();
|
|
return false;
|
|
}
|
|
|
|
// Senha obrigatória apenas no cadastro novo
|
|
if (_modo == ModoFormulario.Novo && string.IsNullOrWhiteSpace(txtSenha.Text))
|
|
{
|
|
MessageBox.Show("Informe a senha para o novo usuário.", "Validação",
|
|
MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
|
txtSenha.Focus();
|
|
return false;
|
|
}
|
|
|
|
if (cmbPerfil.SelectedItem is not ComboItem perfil || perfil.Id == 0)
|
|
{
|
|
MessageBox.Show("Selecione um perfil de acesso.", "Validação",
|
|
MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
|
cmbPerfil.Focus();
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
// ── EVENTOS ABSTRATOS ─────────────────────────────────────────────────
|
|
protected override void OnNovo()
|
|
{
|
|
CarregarPerfis();
|
|
AplicarModo(ModoFormulario.Novo);
|
|
txtNome.Focus();
|
|
}
|
|
|
|
protected override void OnAlterar()
|
|
{
|
|
if (_usuarioAtualId == 0) return;
|
|
AplicarModo(ModoFormulario.Edicao);
|
|
txtNome.Focus();
|
|
}
|
|
|
|
protected override void OnExcluir()
|
|
{
|
|
if (_usuarioAtualId == 0) return;
|
|
|
|
var confirm = MessageBox.Show(
|
|
$"Deseja realmente excluir o usuário \"{txtNome.Text}\"?",
|
|
"Confirmar exclusão",
|
|
MessageBoxButtons.YesNo,
|
|
MessageBoxIcon.Warning);
|
|
|
|
if (confirm != DialogResult.Yes) return;
|
|
|
|
try
|
|
{
|
|
// TODO: _usuarioBLL.Excluir(_usuarioAtualId);
|
|
MessageBox.Show("Usuário excluído com sucesso.", "Sucesso",
|
|
MessageBoxButtons.OK, MessageBoxIcon.Information);
|
|
LimparCampos();
|
|
AplicarModo(ModoFormulario.Visualizacao);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
MessageBox.Show($"Erro ao excluir:\n{ex.Message}", "Erro",
|
|
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
|
}
|
|
}
|
|
|
|
protected override void OnLocalizar()
|
|
{
|
|
// TODO: abrir formulário de busca e retornar o usuário selecionado
|
|
// Exemplo de como receber o retorno:
|
|
// var frm = new FormularioBuscarUsuario();
|
|
// if (frm.ShowDialog() == DialogResult.OK)
|
|
// {
|
|
// var u = frm.UsuarioSelecionado;
|
|
// var perfilId = _usuarioBLL.ObterPerfilId(u.Id);
|
|
// CarregarPerfis();
|
|
// PopularCampos(u, perfilId);
|
|
// AplicarModo(ModoFormulario.Visualizacao);
|
|
// }
|
|
|
|
MessageBox.Show("Implemente o formulário de busca de usuários.",
|
|
"Localizar", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
|
}
|
|
|
|
protected override void OnSalvar()
|
|
{
|
|
if (!Validar()) return;
|
|
|
|
var perfil = (ComboItem)cmbPerfil.SelectedItem;
|
|
|
|
try
|
|
{
|
|
if (_modo == ModoFormulario.Novo)
|
|
{
|
|
// TODO: chamar BLL para criar usuário e vincular perfil
|
|
// var novoUsuario = new ModeloUsuario
|
|
// {
|
|
// EmpresaId = SessaoAtual.EmpresaId,
|
|
// Nome = txtNome.Text.Trim(),
|
|
// Email = txtEmail.Text.Trim(),
|
|
// Usuario = txtUsuario.Text.Trim(),
|
|
// SenhaHash = HashHelper.GerarHash(txtSenha.Text),
|
|
// Ativo = chkAtivo.Checked,
|
|
// CriadoEm = DateTime.Now,
|
|
// AtualizadoEm = DateTime.Now
|
|
// };
|
|
// int novoId = _usuarioBLL.Criar(novoUsuario);
|
|
// _usuarioBLL.VincularPerfil(novoId, perfil.Id);
|
|
|
|
MessageBox.Show("Usuário criado com sucesso!", "Sucesso",
|
|
MessageBoxButtons.OK, MessageBoxIcon.Information);
|
|
}
|
|
else // Edicao
|
|
{
|
|
// TODO: chamar BLL para atualizar usuário e perfil
|
|
// var u = new ModeloUsuario { Id = _usuarioAtualId, ... };
|
|
// if (!string.IsNullOrWhiteSpace(txtSenha.Text))
|
|
// u.SenhaHash = HashHelper.GerarHash(txtSenha.Text);
|
|
// _usuarioBLL.Atualizar(u);
|
|
// _usuarioBLL.AtualizarPerfil(_usuarioAtualId, perfil.Id);
|
|
|
|
MessageBox.Show("Usuário atualizado com sucesso!", "Sucesso",
|
|
MessageBoxButtons.OK, MessageBoxIcon.Information);
|
|
}
|
|
|
|
AplicarModo(ModoFormulario.Visualizacao);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
MessageBox.Show($"Erro ao salvar:\n{ex.Message}", "Erro",
|
|
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
|
}
|
|
}
|
|
|
|
protected override void OnCancelar()
|
|
{
|
|
if (_usuarioAtualId > 0)
|
|
{
|
|
// Volta para os dados que estavam antes
|
|
// TODO: recarregar do banco se necessário
|
|
}
|
|
LimparCampos();
|
|
AplicarModo(ModoFormulario.Visualizacao);
|
|
}
|
|
|
|
// ── CLASSE AUXILIAR PARA O COMBOBOX ──────────────────────────────────
|
|
private class ComboItem
|
|
{
|
|
public int Id { get; }
|
|
public string Nome { get; }
|
|
|
|
public ComboItem(int id, string nome)
|
|
{
|
|
Id = id;
|
|
Nome = nome;
|
|
}
|
|
|
|
public override string ToString() => Nome;
|
|
}
|
|
}
|
|
} |