Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature/edit-address #121

Open
wants to merge 11 commits into
base: develop
Choose a base branch
from
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import br.edu.utfpr.servicebook.service.*;
import br.edu.utfpr.servicebook.util.UserTemplateInfo;
import br.edu.utfpr.servicebook.util.TemplateUtil;
import br.edu.utfpr.servicebook.util.UserWizardUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
Expand All @@ -23,6 +24,7 @@
import javax.annotation.security.RolesAllowed;
import javax.persistence.EntityNotFoundException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Optional;

Expand Down Expand Up @@ -72,6 +74,9 @@ public class MyAccountController {
@Autowired
private AddressService addressService;

@Autowired
private UserWizardUtil userWizardUtil;

@GetMapping
public String home(HttpServletRequest request) {
return "redirect:/minha-conta/cliente";
Expand Down Expand Up @@ -227,20 +232,21 @@ public ModelAndView showMyAddress(@PathVariable Long id) throws IOException {
@RolesAllowed({RoleType.USER, RoleType.COMPANY})
public String saveAddress(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

É preciso receber um DTO como parâmetro para persistência

@PathVariable Long id,
HttpSession httpSession,
HttpServletRequest request,
RedirectAttributes redirectAttributes)
RedirectAttributes redirectAttributes,
@Validated(AddressDTO.RequestUserAddressInfoGroupValidation.class) AddressDTO dto,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Não precisa deste grupo: RequestUserAddressInfoGroupValidation

BindingResult errors)
throws IOException {
this.addressService.editAddress(id, request);

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Faltou usar o errors para mandar os erros de validação ao cliente, quando houver

this.addressService.editAddress(id, dto, errors, httpSession);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Poderia deixar no próprio controller, principalmente as validações e a emissão de exception ou encaminhamento em caso de erro


redirectAttributes.addFlashAttribute("msg", "Endereço editado com sucesso");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sempre vai mandar mensagem de sucesso, não está certo


return "redirect:/minha-conta/meu-endereco/{id}";
}

// tente rota endereço

/**
* FIXME Ao mudar o email, fazer logout para o usuário logar novamente, aí com o novo email
* @param id
* @param request
* @param redirectAttributes
Expand Down
39 changes: 24 additions & 15 deletions src/main/java/br/edu/utfpr/servicebook/service/AddressService.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
package br.edu.utfpr.servicebook.service;


import br.edu.utfpr.servicebook.model.dto.*;
import br.edu.utfpr.servicebook.model.entity.*;
import br.edu.utfpr.servicebook.model.mapper.CityMapper;
import br.edu.utfpr.servicebook.model.mapper.IndividualMapper;
import br.edu.utfpr.servicebook.model.mapper.UserMapper;
import br.edu.utfpr.servicebook.util.UserWizardUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Optional;

@Service
Expand All @@ -29,23 +35,26 @@ public Boolean compareAddres(Address address, Address addressUser) {
}
}

public void editAddress(Long id, HttpServletRequest request) {
public void editAddress(Long id, AddressDTO dto, BindingResult errors, HttpSession httpSession) {
try {
Optional<City> oCity = cityService.findByName(dto.getCity());

if (!oCity.isPresent()) {
errors.rejectValue("city", "error.dto", "Cidade não cadastrada! Por favor, insira uma cidade cadastrada.");
}

City cityMidDTO = oCity.get();

Address addressFullDTO = new Address();
Optional<User> oUser = this.userService.findById(id);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Faltou verificar se o usuário está logado.
E também se o id passado na URL corresponde ao id do usuário logado para ele não alterar dado de outro usuário

User user = oUser.get();
Optional<City> cities = this.cityService.findById(user.getAddress().getCity().getId());
City cityUser = cities.get();
Address addressEdit = new Address();
addressEdit.setNeighborhood(request.getParameter("neighborhood"));
addressEdit.setStreet(request.getParameter("street"));
addressEdit.setNumber(request.getParameter("number"));
addressEdit.setPostalCode(request.getParameter("postalCode").replaceAll("-", ""));
addressEdit.setCity(cityUser);

if (!compareAddres(addressEdit, user.getAddress())) {
user.setAddress(addressEdit);
this.userService.save(user);
}
user.getAddress().setStreet(dto.getStreet().trim());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Usar o Mapper para copiar os dados do DTO para entidade.
Como é edição, o id do Address já existe

user.getAddress().setNumber(dto.getNumber().trim());
user.getAddress().setPostalCode(dto.getPostalCode().trim());
user.getAddress().setNeighborhood(dto.getNeighborhood().trim());
user.getAddress().setCity(cityMidDTO);
this.userService.save(user);

} catch (Exception exception) {
System.out.println(exception.getMessage());
}
Expand Down