Skip to content

Commit

Permalink
Merge pull request #28 from CristianoMends/app/feature/clientes
Browse files Browse the repository at this point in the history
Desenvolvimento da tela de Clientes
  • Loading branch information
Rafaelleit3 authored Jan 29, 2025
2 parents a8f1da8 + 7114ebc commit 0ae1701
Show file tree
Hide file tree
Showing 4 changed files with 188 additions and 22 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package edu.pies.sysaguaapp.controllers;

import com.fasterxml.jackson.databind.ObjectMapper;
import edu.pies.sysaguaapp.models.Address;
import edu.pies.sysaguaapp.models.Clientes;
import edu.pies.sysaguaapp.services.ClientesService;
Expand Down Expand Up @@ -31,27 +32,56 @@ public class ClientesController {
@FXML
private TextField nomeField;

@FXML
private Label nomeErrorLabel;

@FXML
private VBox addressBox;
@FXML
private TextField numberField;

@FXML
private Label numberErrorLabel;

@FXML
private TextField streetField;

@FXML
private Label streetErrorLabel;


@FXML
private TextField neighborhoodField;

@FXML
private Label neighborhoodErrorLabel;

@FXML
private TextField cityField;

@FXML
private Label cityErrorLabel;

@FXML
private TextField stateField;

@FXML
private Label stateErrorLabel;

private Address address;

@FXML
private TextField telefoneField;

@FXML
private Label telefoneErrorLabel;

@FXML
private TextField CNPJField;

@FXML
private Label cnpjErrorLabel;

@FXML
private BorderPane formCadastroClientes;

Expand Down Expand Up @@ -124,6 +154,18 @@ private void updateButtonText() {

@FXML
private void handleSalvar() {
StringBuilder erroMensagem = new StringBuilder();

// Verifica se há campos inválidos
if (!validarCamposComErros(erroMensagem)) {
// Caso algum campo tenha erro, não permite salvar
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Erro");
alert.setHeaderText("Campos inválidos");
alert.setContentText(erroMensagem.toString()); // Exibe a mensagem detalhada
alert.showAndWait();
return; // Interrompe o salvamento
}
String nome = nomeField.getText();
String telefoneStr = telefoneField.getText();
String cnpjStr = CNPJField.getText();
Expand All @@ -133,10 +175,7 @@ private void handleSalvar() {
String cidade = cityField.getText();
String estado = stateField.getText();

if (nomeField.getText().isEmpty() || CNPJField.getText().isEmpty()) {
mostrarAlerta("Campos obrigatórios", "Preencha todos os campos obrigatórios.", "");
return; // Sai do método se a validação falhar
}
validarCampos();

// Cria o objeto Address
Address clienteAddress = new Address();
Expand All @@ -146,10 +185,6 @@ private void handleSalvar() {
clienteAddress.setCity(cidade);
clienteAddress.setState(estado);

if (clienteAddress.getStreet().isEmpty() || clienteAddress.getCity().isEmpty() || clienteAddress.getState().isEmpty()) {
mostrarAlerta("Endereço inválido", "Certifique-se de preencher todos os campos do endereço.", "");
return; // Sai do método se o endereço não estiver completo
}

Clientes novoCliente = new Clientes();
novoCliente.setName(nome);
Expand All @@ -167,8 +202,7 @@ private void handleSalvar() {
}
else{
novoCliente.setActive(true);
Clientes novoClienteCriado = ClientesService.criarCliente(novoCliente, token);
novoCliente.setId(novoClienteCriado.getId());
ClientesService.criarCliente(novoCliente, token);
clientesObservable.add(novoCliente);
}
} catch (Exception e) {
Expand Down Expand Up @@ -440,11 +474,137 @@ private void configurarTabela() {
TableColumn<Clientes, String> colunaCnpj = new TableColumn<>("CNPJ");
colunaCnpj.setCellValueFactory(new PropertyValueFactory<>("cnpj"));


tabelaClientes.getColumns().addAll(colunaNome, colunaNumero, colunaRua, colunaBairro, colunaCidade,colunaEstado, colunaTelefone, colunaCnpj);
tabelaClientes.setItems(clientesObservable);
}

/*--------- validações ----------*/
private void validarCampos() {
// Validar números
configurarValidacaoNumerica(numberField);
configurarValidacaoTelefone(telefoneField);
configurarValidacaoCNPJ(CNPJField);
// Validar Textos
configurarValidacaoTexto(nomeField);
configurarValidacaoTexto(streetField);
configurarValidacaoTexto(neighborhoodField);
configurarValidacaoTexto(cityField);
configurarValidacaoTexto(stateField);
}
private boolean validarCamposComErros(StringBuilder erroMensagem) {
boolean isValid = true;

if (!validarCampoTexto(nomeField)) {
erroMensagem.append("- Nome\n");
isValid = false;
}

// Validando número
if (numberField.getText().isEmpty() || !numberField.getText().matches("[\\d\\s]*")) {
numberField.setStyle("-fx-border-color: red;");
erroMensagem.append("- Número\n");
isValid = false;
} else {
numberField.setStyle(null); // Remove o estilo de erro se válido
}

if (!validarCampoTexto(streetField)) {
erroMensagem.append("- Rua\n");
isValid = false;
}

if (!validarCampoTexto(neighborhoodField)) {
erroMensagem.append("- Bairro\n");
isValid = false;
}

if (!validarCampoTexto(cityField)) {
erroMensagem.append("- Cidade\n");
isValid = false;
}

if (!validarCampoTexto(stateField)) {
erroMensagem.append("- Estado\n");
isValid = false;
}

// Validando telefone
if (telefoneField.getText().isEmpty() || !telefoneField.getText().matches("(\\d{2})?(\\d{2})\\d{8,9}")) {
telefoneField.setStyle("-fx-border-color: red;");
erroMensagem.append("- Telefone\n");
isValid = false;
} else {
telefoneField.setStyle(null);
}

// Validando CNPJ
if (CNPJField.getText().isEmpty() || !CNPJField.getText().matches("\\d{2}\\.\\d{3}\\.\\d{3}/\\d{4}-\\d{2}")) {
CNPJField.setStyle("-fx-border-color: red;");
erroMensagem.append("- CNPJ\n");
isValid = false;
} else {
CNPJField.setStyle(null);
}

return isValid;
}

private boolean validarCampoTexto(TextField textField) {
if (textField.getText().isEmpty() || !textField.getText().matches("[\\p{L}\\s]*")) {
textField.setStyle("-fx-border-color: red;");
return false;
} else {
textField.setStyle(null); // Remove o estilo de erro se válido
return true;
}
}

private void configurarValidacaoNumerica(TextField textField) {
TextFormatter<String> formatter = new TextFormatter<>(change -> {
if (change.getText().matches(("[\\d\\s]*"))) { // Permite números e espaços
return change;
}
return null; // Rejeita mudanças inválidas
});
textField.setTextFormatter(formatter);
}

private void configurarValidacaoTelefone(TextField textField) {
TextFormatter<String> formatter = new TextFormatter<>(change -> {
String novoTexto = change.getControlNewText();

if (novoTexto.matches("(\\d{2})?(\\d{2})\\d{8,9}")) {
// Formato: Código do país (2 dígitos) + DDD (2 dígitos) + Número (8 ou 9 dígitos)
return change;
}

return null; // Rejeita mudanças inválidas
});
textField.setTextFormatter(formatter);
}

private void configurarValidacaoCNPJ(TextField textField) {
TextFormatter<String> formatter = new TextFormatter<>(change -> {
String novoTexto = change.getControlNewText();

// Regex para validar o formato de CNPJ
if (novoTexto.matches("\\d{2}\\.\\d{3}\\.\\d{3}/\\d{4}-\\d{2}")) {
return change; // Aceita formato válido
}

return null; // Rejeita mudanças inválidas
});
textField.setTextFormatter(formatter);
}
private void configurarValidacaoTexto(TextField textField) {
textField.textProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue.matches("[\\p{L}\\s\\d.,-]*")) { // Permite letras, espaços, números, '.', ',' e '-'
textField.setText(oldValue);
}
});
}


private void showSucessMessage() {
successMessage.setVisible(true);
successMessage.toFront();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,12 @@ public List<Clientes> buscarClientes(String token) throws Exception {
return objectMapper.readValue(response.body(), new TypeReference<List<Clientes>>() {
});
} else {
throw new Exception("Erro ao buscar clientes: " + response.body());
throw new Exception("Erro ao buscar clientes: ");
}
}

public static Clientes criarCliente(Clientes clientes, String token) throws Exception {
String clienteJson = objectMapper.writeValueAsString(clientes);
System.out.println("Sending client data: " + clienteJson);

HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(BASE_URL))
Expand All @@ -53,14 +52,21 @@ public static Clientes criarCliente(Clientes clientes, String token) throws Exce

// Verificar a resposta
if (response.statusCode() == 201) {
return objectMapper.readValue(response.body(), Clientes.class);
if (response.body() != null && !response.body().isEmpty()) {
// Se o corpo não estiver vazio, desserializar e retornar o cliente
return objectMapper.readValue(response.body(), Clientes.class);
} else {
// Se o corpo estiver vazio, apenas retornar o cliente que foi enviado
System.out.println("Cliente criado com sucesso, mas sem dados retornados.");
return clientes;
}
} else if (response.statusCode() == 400) {
System.out.println("Erro ao criar cliente: " + response.body());
throw new Exception("Erro ao criar cliente: ");
} else {
System.out.println("Server response: " + response.body());
throw new Exception("Erro ao criar cliente: " + response.body());
throw new Exception("Erro ao criar cliente: ");
}
return clientes;
}
public static Clientes editarCliente(Clientes cliente, String token) throws Exception {
String clienteJson = objectMapper.writeValueAsString(cliente);
Expand All @@ -81,11 +87,11 @@ public static Clientes editarCliente(Clientes cliente, String token) throws Exce
try {
return objectMapper.readValue(response.body(), Clientes.class); // Tenta converter a resposta para o objeto Cliente
} catch (IOException e) {
throw new Exception("Erro ao processar a resposta do servidor: " + e.getMessage());
throw new Exception("Erro ao processar a resposta do servidor: ");
}
}
} else {
throw new Exception("Erro ao editar cliente: " + response.body());
throw new Exception("Erro ao editar cliente: ");
}
}
public static Clientes inativarCliente(Clientes cliente, String token) throws Exception {
Expand All @@ -110,11 +116,11 @@ public static Clientes inativarCliente(Clientes cliente, String token) throws Ex
try {
return objectMapper.readValue(response.body(), Clientes.class);
} catch (IOException e) {
throw new Exception("Erro ao processar a resposta do servidor: " + e.getMessage());
throw new Exception("Erro ao processar a resposta do servidor: ");
}
}
} else {
throw new Exception("Erro ao inativar cliente: " + response.body());
throw new Exception("Erro ao inativar cliente: ");
}
}

Expand Down
4 changes: 2 additions & 2 deletions sysagua-app/src/main/resources/views/Clientes/Clientes.fxml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
</HBox>
</top>
<center>
<VBox fx:id="detailsFormCliente" managed="true" minHeight="205.0" minWidth="365.0" spacing="5.0">
<VBox fx:id="detailsFormCliente" managed="true" minHeight="400.0" minWidth="400.0" spacing="10.0">
<children>
<Label styleClass="label-field" text="Nome da Empresa" />
<TextField fx:id="nomeField" promptText="Nome da Empresa" styleClass="text-field" />
Expand All @@ -45,7 +45,7 @@
<VBox maxHeight="50.0" prefHeight="200.0">
<children>
<Label styleClass="label-field" text="Telefone" />
<TextField fx:id="telefoneField" promptText="5585982127976" styleClass="text-field" />
<TextField fx:id="telefoneField" promptText="5585000000000" styleClass="text-field" />
</children>
</VBox>
<Region maxWidth="120.0" prefHeight="200.0" prefWidth="120.0" />
Expand Down
Empty file.

0 comments on commit 0ae1701

Please sign in to comment.