Skip to content

Commit

Permalink
Implementação do endpoint /accounts.
Browse files Browse the repository at this point in the history
Adição do fluxo de criação de contas bancárias e autenticação de usuários nas requisições.
  • Loading branch information
GabrielFDuarte authored Oct 3, 2021
1 parent b223b1a commit a04d0a7
Show file tree
Hide file tree
Showing 4 changed files with 274 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.maida.desafio.bankapi.controller;

import br.com.maida.desafio.bankapi.model.Account;
import br.com.maida.desafio.bankapi.model.AccountResponse;
import br.com.maida.desafio.bankapi.model.User;
import br.com.maida.desafio.bankapi.service.AccountService;
import br.com.maida.desafio.bankapi.service.AuthService;
import javax.validation.Valid;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
*
* @author Gabriel Duarte
*/
@RestController
@RequestMapping("/accounts")
public class AccountController {

@Autowired
private AccountService accountService;

@Autowired
private AuthService authService;

@PostMapping
@ResponseBody
public ResponseEntity<Object> addAccount(@Valid @RequestBody Account jsonAccountString) {

final HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);

if (accountService.validateNumberExists(jsonAccountString.getNumber())) {
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).headers(httpHeaders).body(
new JSONObject()
.put("erro", "Já existe uma conta com o número informado")
.toString());
}

User tempUser = authService.getUserByEmail(SecurityContextHolder.getContext().getAuthentication().getName());
if (tempUser == null) {
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).headers(httpHeaders).body(
new JSONObject()
.put("message", "Acesso negado.")
.toString());
}

jsonAccountString.setUserEmail(tempUser.getEmail());
jsonAccountString.setUserName(tempUser.getName());

accountService.add(jsonAccountString);

AccountResponse accountResponse = new AccountResponse(
jsonAccountString.getNumber(),
jsonAccountString.getBalance(),
jsonAccountString.getUserEmail(),
jsonAccountString.getUserName());

JSONObject jsonAccountReturn = new JSONObject();
jsonAccountReturn.put("number", jsonAccountString.getNumber());
jsonAccountReturn.put("balance", jsonAccountString.getBalance());
jsonAccountReturn.put("user", accountResponse.getUser());

return ResponseEntity.status(HttpStatus.OK).headers(httpHeaders).body(jsonAccountReturn.toString());
}

}
74 changes: 74 additions & 0 deletions src/main/java/br/com/maida/desafio/bankapi/model/Account.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.maida.desafio.bankapi.model;

import java.math.BigDecimal;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

/**
*
* @author Gabriel Duarte
*/
public class Account {

@NotNull(message = "Campo number ausente.")
@NotEmpty(message = "Campo number vazio.")
private String number;

@NotNull(message = "Campo balance ausente.")
@DecimalMin(value = "0.0", inclusive = true, message = "Saldo deve ser maior ou igual a zero.")
private BigDecimal balance;

private String userEmail;

private String userName;

public Account() {

}

public Account(String number, BigDecimal balance, String userEmail, String userName) {
this.number = number;
this.balance = balance;
this.userEmail = userEmail;
this.userName = userName;
}

public String getNumber() {
return number;
}

public void setNumber(String number) {
this.number = number;
}

public BigDecimal getBalance() {
return balance;
}

public void setBalance(BigDecimal balance) {
this.balance = balance;
}

public String getUserEmail() {
return userEmail;
}

public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.maida.desafio.bankapi.model;

import java.math.BigDecimal;
import org.json.JSONObject;

/**
*
* @author Gabriel Duarte
*/
public class AccountResponse {

private String number;
private BigDecimal balance;
private JSONObject user;

public AccountResponse(String number, BigDecimal balance, String email, String name) {
this.number = number;
this.balance = balance;

JSONObject jsonUserAccount = new JSONObject();

jsonUserAccount.put("email", email);
jsonUserAccount.put("name", name);

this.user = jsonUserAccount;
}

public String getNumber() {
return number;
}

public BigDecimal getBalance() {
return balance;
}

public JSONObject getUser() {
return user;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.maida.desafio.bankapi.service;

import br.com.maida.desafio.bankapi.model.Account;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;

/**
*
* @author Gabriel Duarte
*/
@Service
public class AccountService {

private List<Account> accounts;

// Cria a lista de contas bancárias caso ainda não tenha sido criada
public void createAccountList() {
if (accounts == null) {
accounts = new ArrayList<>();
}
}

// Valida se o número de conta enviado para cadastro já existe entre as contas.
public boolean validateNumberExists(String number) {
if (accounts != null) {
for (Account account : accounts) {
if (account.getNumber().equals(number)) {
return true;
}
}
}
return false;
}

// Valida se a conta é do usuário.
public boolean validateAccountEmail(String number, String email) {
if (accounts != null) {
for (Account account : accounts) {
if (account.getNumber().equals(number)) {
return account.getUserEmail().equals(email);
}
}
}
return false;
}

// Adição do objeto Account na list de contas cadastradas.
public void add(Account account) {
createAccountList();
accounts.add(account);
}

// Retorna o objeto Account buscado pelo número
public Account getAccountByNumber(String number) {
if (accounts == null) {
return null;
}

for (Account account : accounts) {
if (account.getNumber().equals(number)) {
return account;
}
}
return null;
}

}

0 comments on commit a04d0a7

Please sign in to comment.