-
Notifications
You must be signed in to change notification settings - Fork 3
feature/edit-address #121
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
Open
PabloC5
wants to merge
11
commits into
develop
Choose a base branch
from
Feature/edit-address
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
feature/edit-address #121
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
8f36e58
feat: adicionado a nova pagina de edição de endereço e tambem criado …
PabloC5 5c2e503
feat: feito mais alguns ajustes no metodo da rota para editar o ender…
PabloC5 16e06a3
feat: adicionado novo arquivo addressService e colocado a logica todo…
PabloC5 e62bfad
feat: adicionado a mensagem flash ao html e também reformulado o meto…
PabloC5 665a2a7
refactor: ajustes
PabloC5 deba64b
ajustes
PabloC5 2509680
refactor: concluido os ajustes pedidos no review, entre eles estão a …
PabloC5 f418f2f
refactor: fiz os ajuste que foram pedidos menos o uso do mapper que d…
PabloC5 f499876
refactor: ajustei a tela de edição de cadastro para adicionar o botão…
PabloC5 9fb1e03
refactor: ajustes gerais
ronifabio 92cdbb1
refactor: implementei os ajustes que foram pedidos, a validação do js…
PabloC5 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,21 +1,23 @@ | ||
| package br.edu.utfpr.servicebook.controller; | ||
|
|
||
| import br.edu.utfpr.servicebook.model.dto.*; | ||
| import br.edu.utfpr.servicebook.model.entity.City; | ||
| import br.edu.utfpr.servicebook.model.entity.Individual; | ||
| import br.edu.utfpr.servicebook.model.entity.User; | ||
| import br.edu.utfpr.servicebook.model.entity.UserCode; | ||
| import br.edu.utfpr.servicebook.model.entity.*; | ||
| import br.edu.utfpr.servicebook.model.mapper.*; | ||
| import br.edu.utfpr.servicebook.security.IAuthentication; | ||
| import br.edu.utfpr.servicebook.security.RoleType; | ||
| 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.apache.coyote.Response; | ||
| import org.cloudinary.json.JSONObject; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
| import org.springframework.beans.factory.annotation.Autowired; | ||
| import org.springframework.http.ResponseEntity; | ||
| import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; | ||
| import org.springframework.stereotype.Controller; | ||
| import org.springframework.ui.Model; | ||
| import org.springframework.validation.BindingResult; | ||
| import org.springframework.validation.annotation.Validated; | ||
| import org.springframework.web.bind.annotation.*; | ||
|
|
@@ -26,8 +28,11 @@ | |
| 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.List; | ||
| import java.util.Optional; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| @RequestMapping("/minha-conta") | ||
| @Controller | ||
|
|
@@ -72,6 +77,16 @@ public class MyAccountController { | |
| @Autowired | ||
| private TemplateUtil templateUtil; | ||
|
|
||
| @Autowired | ||
| private UserWizardUtil userWizardUtil; | ||
|
|
||
| @Autowired | ||
| private AddressMapper addressMapper; | ||
| @Autowired | ||
| private StateService stateService; | ||
| @Autowired | ||
| private StateMapper stateMapper; | ||
|
|
||
| @GetMapping | ||
| public String home(HttpServletRequest request) { | ||
| return "redirect:/minha-conta/cliente"; | ||
|
|
@@ -186,8 +201,139 @@ public ModelAndView showMyEmail(@PathVariable Long id) throws IOException { | |
| return mv; | ||
| } | ||
|
|
||
| //edita endereço | ||
|
|
||
| /** | ||
| * Apresenta a tela de endereço do usuário. | ||
| * @param id | ||
| * @return | ||
| * @throws IOException | ||
| */ | ||
| @GetMapping("/meu-endereco/{id}") | ||
| @RolesAllowed({RoleType.USER, RoleType.COMPANY}) | ||
| public String showMyAddress(@PathVariable Long id, Model model) throws IOException { | ||
|
|
||
| Optional<User> oUser = this.userService.findById(id); | ||
|
|
||
| if (!oUser.isPresent()) { | ||
| throw new EntityNotFoundException("Usuário não encontrado pelo id informado."); | ||
| } | ||
|
|
||
| Optional<User> oUserAuthenticated = this.userService.findByEmail(authentication.getEmail()); | ||
| if(!oUserAuthenticated.isPresent()){ | ||
| throw new AuthenticationCredentialsNotFoundException("Usuário não autenticado! Por favor, realize sua autenticação no sistema."); | ||
| } | ||
|
|
||
| User userAuthenticated = oUserAuthenticated.get(); | ||
|
|
||
| //verifica se o usuario autenticado é o mesmo que está tentando atualizar as informações | ||
| if (id != userAuthenticated.getId()) { | ||
| throw new AuthenticationCredentialsNotFoundException("Você não tem permissão para atualizar essas informações"); | ||
| } | ||
|
|
||
| Address address = userAuthenticated.getAddress(); | ||
| City city = address.getCity(); | ||
| State state = city.getState(); | ||
|
|
||
| UserDTO userDTO = userMapper.toDto(oUser.get()); | ||
|
|
||
| List<City> cities = this.cityService.findAll(); | ||
| List<State> states = this.stateService.findAll(); | ||
|
|
||
| model.addAttribute("professional", userDTO); | ||
| model.addAttribute("cities", cities); | ||
| model.addAttribute("states", states); | ||
|
|
||
| return "professional/account/my-address"; | ||
| } | ||
|
|
||
|
|
||
| /** | ||
| * @param id | ||
| * @param redirectAttributes | ||
| * @return | ||
| * @throws IOException | ||
| */ | ||
| @PatchMapping("/meu-endereco/{id}") | ||
| @RolesAllowed({RoleType.USER, RoleType.COMPANY}) | ||
| public String saveAddress( | ||
| @PathVariable Long id, | ||
| @Validated AddressUpdateDTO dto, | ||
| BindingResult errors, | ||
| RedirectAttributes redirectAttributes) | ||
| throws IOException { | ||
|
|
||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
| Optional<User> oUser = this.userService.findById(id); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Verificar se o id recebido por parâmetro é o mesmo do usuário logado. |
||
|
|
||
| if (!oUser.isPresent()) { | ||
| throw new EntityNotFoundException("Usuário não encontrado pelo id informado."); | ||
| } | ||
|
|
||
| Optional<User> oUserAuthenticated = this.userService.findByEmail(authentication.getEmail()); | ||
| if(!oUserAuthenticated.isPresent()){ | ||
| throw new AuthenticationCredentialsNotFoundException("Usuário não autenticado! Por favor, realize sua autenticação no sistema."); | ||
| } | ||
|
|
||
| User userAuthenticated = oUserAuthenticated.get(); | ||
|
|
||
| //verifica se o usuario autenticado é o mesmo que está tentando atualizar as informações | ||
| if (id != userAuthenticated.getId()) { | ||
| throw new AuthenticationCredentialsNotFoundException("Você não tem permissão para atualizar essas informações"); | ||
| } | ||
|
|
||
| //verifica se o estado está cadastrado | ||
| if(!stateService.findById(dto.getState()).isPresent()){ | ||
| errors.rejectValue("state", "error.dto", "Estado não cadastrado! Por favor, insira um estado cadastrado."); | ||
| redirectAttributes.addFlashAttribute("errors", errors.getAllErrors()); | ||
| return "redirect:/minha-conta/meu-endereco/{id}"; | ||
| } | ||
|
|
||
| //verifica se a cidade existe para o estado informado | ||
| if(!cityService.findByIdAndState_Id(dto.getCity(), dto.getState()).isPresent()){ | ||
| errors.rejectValue("city", "error.dto", "Cidade não cadastrada para o estado informado! Por favor, insira uma cidade cadastrada."); | ||
| redirectAttributes.addFlashAttribute("errors", errors.getAllErrors()); | ||
| return "redirect:/minha-conta/meu-endereco/{id}"; | ||
| } | ||
|
|
||
| try { | ||
| //atualiza o endereço do usuário | ||
| Address address = userAuthenticated.getAddress(); | ||
| address.setCity(cityService.findById(dto.getCity()).get()); | ||
| address.setStreet(dto.getStreet().trim()); | ||
| address.setNumber(dto.getNumber().trim()); | ||
| address.setPostalCode(dto.getPostalCode().trim()); | ||
| address.setNeighborhood(dto.getNeighborhood().trim()); | ||
|
|
||
| userAuthenticated.setAddress(address); | ||
|
|
||
| this.userService.save(userAuthenticated); | ||
| redirectAttributes.addFlashAttribute("msg", "Endereço editado com sucesso"); | ||
| } catch (Exception exception) { | ||
| errors.rejectValue(null, "not-found", "Erro ao editar endereço: " + exception.getMessage()); | ||
| redirectAttributes.addFlashAttribute("errors", errors.getAllErrors()); | ||
| return "redirect:/minha-conta/meu-endereco/{id}"; | ||
| } | ||
|
|
||
| return "redirect:/minha-conta/meu-endereco/{id}"; | ||
| } | ||
|
|
||
| @PostMapping("/meu-endereco/{id}") | ||
| @RolesAllowed({RoleType.USER, RoleType.ADMIN}) | ||
| @ResponseBody | ||
| public ResponseEntity<?> getExpertiseData(@PathVariable("id") Long userId, @RequestBody String data,BindingResult errors, | ||
| RedirectAttributes redirectAttributes) { | ||
| Response response = new Response(); | ||
| Optional<User> oUser = this.userService.findById(userId); | ||
| JSONObject jsonObject = new JSONObject(data); | ||
| if(!cityService.findByName(jsonObject.getString("localidade")).isPresent()){ | ||
| response.setMessage("Cidade não cadastrada! Por favor, insira uma cidade cadastrada."); | ||
| return ResponseEntity.status(401).body(response.getMessage()); | ||
| } | ||
| response.setMessage("Cidade cadastrada no sistema!!"); | ||
| return ResponseEntity.status(200).body(response.getMessage()); | ||
| } | ||
|
|
||
| /** | ||
| * FIXME Ao mudar o email, fazer logout para o usuário logar novamente, aí com o novo email | ||
| * @param id | ||
| * @param request | ||
| * @param redirectAttributes | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
34 changes: 34 additions & 0 deletions
34
src/main/java/br/edu/utfpr/servicebook/model/dto/AddressUpdateDTO.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| package br.edu.utfpr.servicebook.model.dto; | ||
|
|
||
| import lombok.AllArgsConstructor; | ||
| import lombok.Data; | ||
| import lombok.NoArgsConstructor; | ||
|
|
||
| import javax.validation.constraints.NotBlank; | ||
| import javax.validation.constraints.NotNull; | ||
| import java.io.Serializable; | ||
|
|
||
| @Data | ||
| @NoArgsConstructor | ||
| @AllArgsConstructor | ||
| public class AddressUpdateDTO implements Serializable { | ||
|
|
||
| @NotBlank(message = "Rua inválida! Por favor, insira a rua do endereço.") | ||
| private String street; | ||
|
|
||
| private String number; | ||
|
|
||
| @NotBlank(message = "CEP inválido! Por favor, insira o CEP do endereço.") | ||
| private String postalCode; | ||
|
|
||
| @NotBlank(message = "Bairro inválido! Por favor, insira o bairro do endereço.") | ||
| private String neighborhood; | ||
|
|
||
| @NotNull(message = "Cidade Inválida! Por favor, insira a cidade do endereço.") | ||
| private Long city; | ||
|
|
||
| @NotNull(message = "Estado inválido! Por favor, insira o estado do endereço.") | ||
| private Long state; | ||
|
|
||
|
|
||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -11,6 +11,7 @@ | |
| @AllArgsConstructor | ||
| public class StateMinDTO implements Serializable { | ||
|
|
||
| private Long id; | ||
| private String uf; | ||
|
|
||
| } | ||
35 changes: 35 additions & 0 deletions
35
src/main/java/br/edu/utfpr/servicebook/model/mapper/AddressMapper.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| package br.edu.utfpr.servicebook.model.mapper; | ||
|
|
||
| import br.edu.utfpr.servicebook.model.dto.AddressDTO; | ||
| import br.edu.utfpr.servicebook.model.dto.UserDTO; | ||
| import br.edu.utfpr.servicebook.model.entity.Address; | ||
| import br.edu.utfpr.servicebook.model.entity.City; | ||
| import br.edu.utfpr.servicebook.model.entity.User; | ||
| import org.modelmapper.ModelMapper; | ||
| import org.springframework.beans.factory.annotation.Autowired; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| @Component | ||
| public class AddressMapper { | ||
|
|
||
| @Autowired | ||
| private ModelMapper mapper; | ||
|
|
||
| public AddressDTO toDto(Address entity) { | ||
| AddressDTO dto = mapper.map(entity, AddressDTO.class); | ||
| return dto; | ||
| } | ||
|
|
||
| public Address toEntity(AddressDTO dto) { | ||
| Address entity = mapper.map(dto, Address.class); | ||
| return entity; | ||
| } | ||
|
|
||
| public Address toUpdate(AddressDTO dto, Long id, City city) { | ||
| Address entity = mapper.map(dto, Address.class); | ||
| entity.setId(id); | ||
| entity.setCity(city); | ||
| return entity; | ||
| } | ||
|
|
||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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