LevelOS-Core/Dashboards/Cadastros/EmpresaConfiguracoesPanel.cs
2026-04-17 21:09:19 -03:00

591 lines
25 KiB
C#

using BLL;
using CCH;
using CustomMessageBox;
using DAL;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace UI
{
public class EmpresaConfiguracoesPanel : UserControl
{
//Variaveis de ambiente
private int _idEmpresa;
private int _idConfig;
private string _connectionString = DadosDaConexao.ObterConexao();
private readonly Color AccentBlue = Color.FromArgb(37, 99, 235);
private readonly Color TextDark = Color.FromArgb(30, 41, 59);
private readonly Color BorderColor = Color.FromArgb(226, 232, 240);
private Panel pnlToolbar = null!;
private Panel mainScroll = null!;
private Panel content = null!;
private RoundTextBox txtId = null!, txtEmpresaId = null!, txtNomeSistema = null!;
private RoundTextBox txtCorPrimaria = null!, txtCorSecundaria = null!;
private RoundTextBox txtLogo = null!, txtFavicon = null!;
private RoundTextBox txtDiasGarantiaPadrao = null!;
private CheckBox chkExibirCPF = null!, chkExibirTelefone = null!, chkExibirGarantia = null!;
private CheckBox chkGerarRecibo = null!, chkExibirValoresOS = null!;
private CheckBox chkEmailAuto = null!, chkWhatsAuto = null!, chkModoEscuro = null!;
private CheckBox chkPermitirEdicaoOS = null!;
private RoundTextBox txtCriadoEm = null!, txtAtualizadoEm = null!;
public EmpresaConfiguracoesPanel()
{
Dock = DockStyle.Fill;
BackColor = Color.White;
DoubleBuffered = true;
InitializeLayout();
this.CarregarConfig();
}
private void InitializeLayout()
{
this.Controls.Clear();
// ── TOOLBAR ───────────────────────────────────────────────────────
pnlToolbar = new Panel
{
Dock = DockStyle.Top,
Height = 55,
BackColor = Color.FromArgb(248, 250, 252)
};
var flowButtons = new FlowLayoutPanel
{
Dock = DockStyle.Fill,
Padding = new Padding(12, 10, 0, 0)
};
var btnNovo = CreateToolbarButton("Novo", Color.FromArgb(34, 197, 94));
var btnAlterar = CreateToolbarButton("Alterar", Color.FromArgb(245, 158, 11));
var btnExcluir = CreateToolbarButton("Excluir", Color.FromArgb(239, 68, 68));
var btnLocalizar = CreateToolbarButton("Localizar", AccentBlue);
var btnSalvar = CreateToolbarButton("Salvar", AccentBlue);
var btnCancelar = CreateToolbarButton("Cancelar", Color.FromArgb(148, 163, 184));
var btnConfigEmpresa = CreateToolbarButton("Gerar Config", Color.FromArgb(148, 163, 184));
btnNovo.Click += (s, e) => BtnNovo_Click();
btnAlterar.Click += (s, e) => BtnAlterar_Click();
btnExcluir.Click += (s, e) => BtnExcluir_Click();
btnLocalizar.Click += (s, e) => BtnLocalizar_Click();
btnSalvar.Click += (s, e) => BtnSalvar_Click();
btnCancelar.Click += (s, e) => BtnCancelar_Click();
btnConfigEmpresa.Click += (s, e) => BtnGerarConfig_Click();
flowButtons.Controls.AddRange(new Control[]
{ btnNovo, btnAlterar, btnExcluir, btnLocalizar, btnSalvar,btnConfigEmpresa,btnCancelar });
pnlToolbar.Controls.Add(flowButtons);
this.Controls.Add(pnlToolbar);
// ── SCROLL + CONTENT ──────────────────────────────────────────────
mainScroll = new Panel { Dock = DockStyle.Fill, AutoScroll = true };
this.Controls.Add(mainScroll);
mainScroll.BringToFront();
content = new Panel { Width = 1100, Height = 850, Location = new Point(0, 0) };
mainScroll.Controls.Add(content);
int y = 10;
const int rowH = 52;
// ── 1. IDENTIDADE DO SISTEMA ──────────────────────────────────────
content.Controls.Add(CreateSectionHeader("IDENTIDADE DO SISTEMA", y));
y += 32;
txtId = AddInput(content, "ID", 20, y, 60, 28, readOnly: true);
txtEmpresaId = AddInput(content, "Empresa ID", 90, y, 80, 28);
txtNomeSistema = AddInput(content, "Nome Personalizado do Sistema", 180, y, 350, 28);
y += rowH;
txtCorPrimaria = AddInput(content, "Cor Primária (Hex)", 20, y, 150, 28);
txtCorSecundaria = AddInput(content, "Cor Secundária (Hex)", 180, y, 150, 28);
// Logo com botão lupa
txtLogo = AddInput(content, "Caminho da Logo", 340, y, 260, 28);
var btnLogo = CreateIconButton("🔍", 608, y + 16);
btnLogo.Click += (s, e) => SelecionarImagem(txtLogo, "Logo");
content.Controls.Add(btnLogo);
// Favicon com botão lupa
txtFavicon = AddInput(content, "Caminho do Favicon", 650, y, 240, 28);
var btnFavicon = CreateIconButton("🔍", 898, y + 16);
btnFavicon.Click += (s, e) => SelecionarImagem(txtFavicon, "Favicon");
content.Controls.Add(btnFavicon);
// ── 2. REGRAS DE NEGÓCIO E EXIBIÇÃO ──────────────────────────────
y += rowH + 15;
content.Controls.Add(CreateSectionHeader("REGRAS DE NEGÓCIO E EXIBIÇÃO", y));
y += 32;
chkExibirCPF = CreateCheckBox("Exibir CPF Cliente na OS", 20, y + 15);
chkExibirTelefone = CreateCheckBox("Exibir Telefone na OS", 230, y + 15);
chkExibirValoresOS = CreateCheckBox("Exibir Valores na OS", 460, y + 15);
content.Controls.AddRange(new Control[] { chkExibirCPF, chkExibirTelefone, chkExibirValoresOS });
y += rowH;
chkExibirGarantia = CreateCheckBox("Utilizar Garantia", 20, y + 15);
txtDiasGarantiaPadrao = AddInput(content, "Dias Garantia (Padrão)", 180, y, 120, 28);
content.Controls.Add(chkExibirGarantia);
// ── 3. AUTOMAÇÕES E COMUNICAÇÃO ───────────────────────────────────
y += rowH + 15;
content.Controls.Add(CreateSectionHeader("AUTOMAÇÕES E COMUNICAÇÃO", y));
y += 32;
chkGerarRecibo = CreateCheckBox("Gerar Recibo Automático", 20, y + 15);
chkEmailAuto = CreateCheckBox("Enviar E-mail Automático", 230, y + 15);
chkWhatsAuto = CreateCheckBox("Enviar WhatsApp Automático", 460, y + 15);
content.Controls.AddRange(new Control[] { chkGerarRecibo, chkEmailAuto, chkWhatsAuto });
// ── 4. PREFERÊNCIAS TÉCNICAS ──────────────────────────────────────
y += rowH + 15;
content.Controls.Add(CreateSectionHeader("PREFERÊNCIAS TÉCNICAS", y));
y += 32;
chkModoEscuro = CreateCheckBox("Habilitar Modo Escuro", 20, y + 15);
chkPermitirEdicaoOS = CreateCheckBox("Permitir Edição de OS Finalizada", 230, y + 15);
content.Controls.AddRange(new Control[] { chkModoEscuro, chkPermitirEdicaoOS });
// ── 5. INFORMAÇÕES DO REGISTRO ────────────────────────────────────
y += rowH + 15;
content.Controls.Add(CreateSectionHeader("INFORMAÇÕES DO REGISTRO", y));
y += 32;
txtCriadoEm = AddInput(content, "Criado Em", 20, y, 180, 28, readOnly: true);
txtAtualizadoEm = AddInput(content, "Atualizado Em", 210, y, 180, 28, readOnly: true);
y += rowH;
content.Height = y + 20;
SetCamposStatus(false);
}
// ── SELEÇÃO DE IMAGEM ─────────────────────────────────────────────────
//private void SelecionarImagem(RoundTextBox destino, string tipo)
//{
// using var dlg = new OpenFileDialog
// {
// Title = $"Selecionar {tipo}",
// Filter = "Imagens|*.png;*.jpg;*.jpeg;*.bmp;*.ico;*.gif|Todos os arquivos|*.*"
// };
// if (dlg.ShowDialog() == DialogResult.OK)
// {
// var arquivo = dlg.FileName;
// destino.Text = arquivo;
// // Valida tamanho máximo (2MB)
// var info = new FileInfo(arquivo);
// if (info.Length > 2 * 1024 * 1024)
// {
// MessageBox.Show(
// $"O arquivo selecionado para {tipo} é maior que 2MB.\nRecomendamos imagens menores para melhor desempenho.",
// "Atenção",
// MessageBoxButtons.OK,
// MessageBoxIcon.Warning);
// }
// }
//}
private void SelecionarImagem(RoundTextBox destino, string tipo)
{
using var dlg = new OpenFileDialog
{
Title = $"Selecionar {tipo}",
Filter = "Imagens|*.png;*.jpg;*.jpeg;*.bmp;*.ico;*.gif|Todos os arquivos|*.*"
};
if (dlg.ShowDialog() == DialogResult.OK)
{
try
{
var arquivoOriginal = dlg.FileName;
// 📁 Pasta destino fixa
string pastaDestino = @"C:\Levelcode\LevelOS\Uploads\Images";
// Cria a pasta se não existir
if (!Directory.Exists(pastaDestino))
Directory.CreateDirectory(pastaDestino);
// 🔥 Gera nome único (evita sobrescrever)
string extensao = Path.GetExtension(arquivoOriginal);
string nomeNovo = $"{tipo}_{Guid.NewGuid()}{extensao}";
string caminhoFinal = Path.Combine(pastaDestino, nomeNovo);
// Copia o arquivo
File.Copy(arquivoOriginal, caminhoFinal, false);
// Atualiza o campo
destino.Text = caminhoFinal;
// ⚠️ Valida tamanho (2MB)
var info = new FileInfo(caminhoFinal);
if (info.Length > 2 * 1024 * 1024)
{
MessageBox.Show(
$"O arquivo selecionado para {tipo} é maior que 2MB.\nRecomendamos imagens menores para melhor desempenho.",
"Atenção",
MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
}
catch (Exception ex)
{
MessageBox.Show(
"Erro ao copiar imagem: " + ex.Message,
"Erro",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}//Copiar com mais precisão
// ── EVENTOS DOS BOTÕES ────────────────────────────────────────────────
private void BtnNovo_Click()
{
LimparFormulario();
SetCamposStatus(true);
txtNomeSistema.Focus();
BLLEmpresaConfig empresaConfig = new BLLEmpresaConfig(_connectionString);
this.txtEmpresaId.Text = empresaConfig.ObterEmpresaAtivaId().ToString();
}
private void BtnAlterar_Click()
{
if (string.IsNullOrWhiteSpace(txtId.Text))
{
MessageBox.Show(
"Nenhum registro selecionado para alterar.",
"Atenção",
MessageBoxButtons.OK,
MessageBoxIcon.Warning);
return;
}
SetCamposStatus(true);
}
private void BtnExcluir_Click()
{
// Solicita confirmação e exclui o registro
}
private void BtnLocalizar_Click()
{
// Abre tela de busca e preenche os campos
}
private void BtnGerarConfig_Click()
{
var config = new ModeloEmpresaConfig
{
IdEmpresaConfig = Convert.ToInt32(txtId.Text), // você precisa ter isso carregado
IdEmpresa = Convert.ToInt32(txtEmpresaId.Text), // idem (empresa logada)
NomeSistema = txtNomeSistema.Text,
CorPrimaria = txtCorPrimaria.Text,
CorSecundaria = txtCorSecundaria.Text,
Logo = txtLogo.Text,
Favicon = txtFavicon.Text,
ExibirCPFCliente = chkExibirCPF.Checked,
ExibirTelefoneCliente = chkExibirTelefone.Checked,
ExibirGarantia = chkExibirGarantia.Checked,
DiasGarantiaPadrao = Convert.ToInt32(txtDiasGarantiaPadrao.Text),
GerarReciboAutomatico = chkGerarRecibo.Checked,
ExibirValoresOS = chkExibirValoresOS.Checked,
EnviarEmailAutomatico = chkEmailAuto.Checked,
EnviarWhatsappAutomatico = chkWhatsAuto.Checked,
ModoEscuro = chkModoEscuro.Checked,
PermitirEdicaoOSFinalizada = chkPermitirEdicaoOS.Checked
};
bool result = JsonHelper.SalvarBoolean(config, AppFileSystem.AppFileConfigEmpresa);
if (result)
{
NT_MessageBox.Show("Arquivo de configuração gerado com sucesso.","Arquivo gerado",MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
NT_MessageBox.Show("Não foi possivel gerar o arquivo de configuração", "falha ao gerar arquivo", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void BtnSalvar_Click()
{
try
{
// Valida campos obrigatórios
if (string.IsNullOrWhiteSpace(txtNomeSistema.Text))
{
MessageBox.Show(
"O campo 'Nome do Sistema' é obrigatório.",
"Atenção",
MessageBoxButtons.OK,
MessageBoxIcon.Warning);
txtNomeSistema.Focus();
return;
}
// Valida cores HEX
if (!string.IsNullOrWhiteSpace(txtCorPrimaria.Text) && !ValidarHex(txtCorPrimaria.Text))
{
MessageBox.Show("Cor Primária inválida. Ex: #3B82F6", "Atenção");
txtCorPrimaria.Focus();
return;
}
if (!string.IsNullOrWhiteSpace(txtCorSecundaria.Text) && !ValidarHex(txtCorSecundaria.Text))
{
MessageBox.Show("Cor Secundária inválida. Ex: #64748B", "Atenção");
txtCorSecundaria.Focus();
return;
}
// Valida arquivos
if (!string.IsNullOrWhiteSpace(txtLogo.Text) && !File.Exists(txtLogo.Text))
{
MessageBox.Show("Logo não encontrada.", "Atenção");
return;
}
if (!string.IsNullOrWhiteSpace(txtFavicon.Text) && !File.Exists(txtFavicon.Text))
{
MessageBox.Show("Favicon não encontrado.", "Atenção");
return;
}
// 🔥 Monta o modelo
var config = new ModeloEmpresaConfig
{
IdEmpresaConfig = Convert.ToInt32(txtId.Text), // você precisa ter isso carregado
IdEmpresa = Convert.ToInt32(txtEmpresaId.Text), // idem (empresa logada)
NomeSistema = txtNomeSistema.Text,
CorPrimaria = txtCorPrimaria.Text,
CorSecundaria = txtCorSecundaria.Text,
Logo = txtLogo.Text,
Favicon = txtFavicon.Text,
ExibirCPFCliente = chkExibirCPF.Checked,
ExibirTelefoneCliente = chkExibirTelefone.Checked,
ExibirGarantia = chkExibirGarantia.Checked,
DiasGarantiaPadrao =Convert.ToInt32(txtDiasGarantiaPadrao.Text),
GerarReciboAutomatico = chkGerarRecibo.Checked,
ExibirValoresOS = chkExibirValoresOS.Checked,
EnviarEmailAutomatico = chkEmailAuto.Checked,
EnviarWhatsappAutomatico = chkWhatsAuto.Checked,
ModoEscuro = chkModoEscuro.Checked,
PermitirEdicaoOSFinalizada = chkPermitirEdicaoOS.Checked
};
var bll = new BLLEmpresaConfig(_connectionString);
// 🔥 Decide se cria ou atualiza
_idConfig = Convert.ToInt32(txtId.Text);
if (_idConfig == 0 || _idConfig == null)
{
bll.Inserir(config);
JsonHelper.Salvar(config, AppFileSystem.AppFileConfigEmpresa);
}
else
{
bll.Alterar(config);
JsonHelper.Salvar(config, AppFileSystem.AppFileConfigEmpresa);
}
MessageBox.Show(
"Configurações salvas com sucesso!",
"LevelOS",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
SetCamposStatus(false);
}
catch (Exception ex)
{
MessageBox.Show(
ex.Message,
"Erro",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void BtnCancelar_Click()
{
LimparFormulario();
SetCamposStatus(false);
}
// ── HELPERS DE ESTADO ─────────────────────────────────────────────────
private void SetCamposStatus(bool active)
{
var campos = new Control[]
{
txtEmpresaId, txtNomeSistema, txtCorPrimaria, txtCorSecundaria,
txtLogo, txtFavicon, txtDiasGarantiaPadrao,
chkExibirCPF, chkExibirTelefone, chkExibirGarantia, chkGerarRecibo,
chkExibirValoresOS, chkEmailAuto, chkWhatsAuto, chkModoEscuro, chkPermitirEdicaoOS
};
foreach (var c in campos)
{
c.Enabled = active;
if (c is RoundTextBox r)
r.BackColor = active ? Color.White : Color.FromArgb(241, 245, 249);
}
// ID e datas nunca editáveis
txtId.Enabled = false;
txtId.BackColor = Color.FromArgb(241, 245, 249);
txtCriadoEm.Enabled = false;
txtAtualizadoEm.Enabled = false;
}
private void LimparFormulario()
{
var todos = new RoundTextBox[]
{
txtId, txtEmpresaId, txtNomeSistema, txtCorPrimaria, txtCorSecundaria,
txtLogo, txtFavicon, txtDiasGarantiaPadrao, txtCriadoEm, txtAtualizadoEm
};
foreach (var t in todos) t.Text = string.Empty;
foreach (Control c in content.Controls)
if (c is CheckBox chk) chk.Checked = false;
}
private static bool ValidarHex(string valor)
{
var v = valor.TrimStart('#');
return v.Length == 6 && System.Text.RegularExpressions.Regex.IsMatch(v, @"^[0-9A-Fa-f]{6}$");
}
// ── HELPERS DE UI ─────────────────────────────────────────────────────
private Panel CreateSectionHeader(string title, int y)
{
var pnl = new Panel { Location = new Point(20, y), Width = 1000, Height = 26 };
pnl.Controls.Add(new Label
{
Text = title,
Font = new Font("Segoe UI", 8.5f, FontStyle.Bold),
ForeColor = AccentBlue,
AutoSize = true
});
pnl.Controls.Add(new Panel
{
BackColor = BorderColor,
Height = 1,
Width = 980,
Location = new Point(0, 20)
});
return pnl;
}
private RoundTextBox AddInput(Control parent, string label,
int x, int y, int w, int h,
bool readOnly = false)
{
parent.Controls.Add(new Label
{
Text = label,
Location = new Point(x, y),
Font = new Font("Segoe UI", 7.5f, FontStyle.Bold),
ForeColor = readOnly ? Color.Gray : TextDark,
AutoSize = true
});
var txt = new RoundTextBox
{
Location = new Point(x, y + 16),
Size = new Size(w, h),
Radius = 4,
BorderColor = readOnly ? Color.FromArgb(203, 213, 225) : BorderColor,
FocusColor = AccentBlue,
ReadOnly = readOnly,
BackColor = readOnly ? Color.FromArgb(241, 245, 249) : Color.White
};
parent.Controls.Add(txt);
return txt;
}
private Button CreateIconButton(string icon, int x, int y) => new Button
{
Text = icon,
Location = new Point(x, y),
Size = new Size(28, 28),
FlatStyle = FlatStyle.Flat,
Font = new Font("Segoe UI", 10f),
Cursor = Cursors.Hand,
FlatAppearance = { BorderColor = BorderColor, BorderSize = 1 },
BackColor = Color.FromArgb(241, 245, 249)
};
private CheckBox CreateCheckBox(string text, int x, int y) => new CheckBox
{
Text = text,
Location = new Point(x, y),
Font = new Font("Segoe UI", 8.25f, FontStyle.Bold),
ForeColor = TextDark,
AutoSize = true
};
private RoundButton CreateToolbarButton(string text, Color color) => new RoundButton
{
Text = text,
Size = new Size(95, 32),
BackColor = color,
ForeColor = Color.White,
Font = new Font("Segoe UI Semibold", 8.5f),
Margin = new Padding(0, 0, 6, 0),
Cursor = Cursors.Hand
};
private void CarregarConfig()
{
BLLEmpresaConfig empresaConfig = new BLLEmpresaConfig(_connectionString);
int codEmpresa = empresaConfig.ObterEmpresaAtivaId();
if (codEmpresa > 0)
{
ModeloEmpresaConfig modelo = empresaConfig.ObterPorEmpresa(codEmpresa);
this.txtId.Text = modelo.IdEmpresaConfig.ToString();
this.txtEmpresaId.Text = modelo.IdEmpresa.ToString();
this.txtNomeSistema.Text = modelo.NomeSistema;
this.txtCorPrimaria.Text = modelo.CorPrimaria;
this.txtCorSecundaria.Text = modelo.CorSecundaria;
this.txtLogo.Text = modelo.Logo;
this.txtFavicon.Text = modelo.Favicon;
this.txtDiasGarantiaPadrao.Text = modelo.DiasGarantiaPadrao.ToString();
this.chkExibirCPF.Checked = modelo.ExibirCPFCliente;
this.chkExibirTelefone.Checked = modelo.ExibirTelefoneCliente;
this.chkExibirGarantia.Checked = modelo.ExibirGarantia;
this.chkGerarRecibo.Checked = modelo.GerarReciboAutomatico;
this.chkExibirValoresOS.Checked = modelo.ExibirValoresOS;
this.chkEmailAuto.Checked = modelo.EnviarEmailAutomatico;
this.chkWhatsAuto.Checked = modelo.EnviarWhatsappAutomatico;
this.chkModoEscuro.Checked = modelo.ModoEscuro;
this.chkPermitirEdicaoOS.Checked = modelo.PermitirEdicaoOSFinalizada;
this.txtCriadoEm.Text = modelo.CriadoEm.ToString();
this.txtAtualizadoEm.Text = modelo.AtualizadoEm.ToString();
}
else
{
NT_MessageBox.Show("Erro ao recuperar configuração da empresa, por favor contacte o administrador do sistema","Erro",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
}
}