Skip to content

Commit

Permalink
Adding ordering and sorting in findBetweenDates route.
Browse files Browse the repository at this point in the history
  • Loading branch information
Mariana Azevedo committed Aug 23, 2020
1 parent d7383a2 commit 706fcd0
Show file tree
Hide file tree
Showing 13 changed files with 142 additions and 71 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,7 @@

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
Expand Down Expand Up @@ -57,7 +53,8 @@ public void testCreateTransactionNSU123456() throws ParseException {
TransactionDTO dtoNsu123456 = new TransactionDTO();
dtoNsu123456.setNsu("123456");
dtoNsu123456.setAuthorizationNumber("014785");
dtoNsu123456.setTransactionDate(getMockTransactionDate());
dtoNsu123456.setTransactionDate(FinancialApiUtil.
getLocalDateTimeFromString("2020-08-21T18:32:04.150Z"));
dtoNsu123456.setAmount(new BigDecimal(100d));
dtoNsu123456.setType(TransactionTypeEnum.CARD);

Expand All @@ -81,7 +78,8 @@ public void testCreateTransactionNSU258963() throws ParseException {
//id=2
TransactionDTO dtoNsu258963 = new TransactionDTO();
dtoNsu258963.setNsu("258963");
dtoNsu258963.setTransactionDate(getMockTransactionDate());
dtoNsu258963.setTransactionDate(FinancialApiUtil.
getLocalDateTimeFromString("2020-08-21T18:32:04.150Z"));
dtoNsu258963.setAmount(new BigDecimal(2546.93));
dtoNsu258963.setType(TransactionTypeEnum.MONEY);

Expand All @@ -100,16 +98,20 @@ public void testCreateTransactionNSU258963() throws ParseException {

@Test
@Order(3)
public void testFindAllTransactions() {
public void testFindAllTransactions() throws ParseException {

final HttpHeaders headers = new HttpHeaders();
headers.set("X-api-key", "FX001-ZBSY6YSLP");

//Create a new HttpEntity
final HttpEntity<String> entity = new HttpEntity<>(headers);

String startDate = LocalDate.now().minusDays(1).format(FinancialApiUtil.getDateFormater());
String endDate = LocalDate.now().plusDays(5).format(FinancialApiUtil.getDateFormater());
LocalDateTime startDateTime = FinancialApiUtil.
getLocalDateTimeFromString("2020-08-21T18:32:04.150Z");
LocalDateTime endDateTime = startDateTime.plusDays(5);

String startDate = startDateTime.format(FinancialApiUtil.getDateFormater());
String endDate = endDateTime.format(FinancialApiUtil.getDateFormater());

ResponseEntity<String> responseEntity = this.restTemplate
.exchange("http://localhost:" + port + "/financial/v1/transactions?startDate=" + startDate + "&endDate=" + endDate,
Expand Down Expand Up @@ -207,11 +209,5 @@ public void testRequestExceedingRateLimitCapacity() throws Exception {
//Too many requests
assertEquals(429, responseEntity.getStatusCodeValue());
}

private LocalDateTime getMockTransactionDate() throws ParseException{
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date dateISO8601 = inputFormat.parse("2020-08-21T18:32:04.150Z");
return dateISO8601.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

Expand Down Expand Up @@ -37,6 +38,7 @@
import io.github.mariazevedo88.financialjavaapi.exception.NotParsableContentException;
import io.github.mariazevedo88.financialjavaapi.exception.TransactionInvalidUpdateException;
import io.github.mariazevedo88.financialjavaapi.exception.TransactionNotFoundException;
import io.github.mariazevedo88.financialjavaapi.model.enumeration.PageOrderEnum;
import io.github.mariazevedo88.financialjavaapi.model.transaction.Transaction;
import io.github.mariazevedo88.financialjavaapi.service.transaction.TransactionService;
import io.github.mariazevedo88.financialjavaapi.util.FinancialApiUtil;
Expand Down Expand Up @@ -204,15 +206,20 @@ public ResponseEntity<Response<TransactionDTO>> update(@RequestHeader(value=Fina
@ApiOperation(value = "Route to find all transactions of the API in a period of time")
public ResponseEntity<Response<Page<TransactionDTO>>> findAllBetweenDates(@RequestHeader(value=FinancialApiUtil.HEADER_FINANCIAL_API_VERSION, defaultValue="${api.version}")
String apiVersion, @RequestHeader(value=FinancialApiUtil.HEADER_API_KEY, defaultValue="${api.key}") String apiKey, @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd")
LocalDate startDate, @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate, @RequestParam(name="page", defaultValue = "0") int page)
throws TransactionNotFoundException {
LocalDate startDate, @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate, @RequestParam(name="page", defaultValue = "0") int page,
@RequestParam(name="order", defaultValue = "ASC") String order) throws TransactionNotFoundException {

Response<Page<TransactionDTO>> response = new Response<>();

Page<Transaction> transactions = transactionService.findBetweenDates(startDate.atTime(0, 0, 0), endDate.atTime(0, 0, 0), page);
LocalDateTime startDateTime = FinancialApiUtil.convertLocalDateToLocalDateTime(startDate);
LocalDateTime endDateTime = FinancialApiUtil.convertLocalDateToLocalDateTime(endDate);

Page<Transaction> transactions = transactionService.findBetweenDates(startDateTime, endDateTime,
page, PageOrderEnum.getDirection(order));

if (transactions.isEmpty()) {
throw new TransactionNotFoundException("There are no transactions registered between startDate=" + startDate + " and endDate=" + endDate);
throw new TransactionNotFoundException("There are no transactions registered between startDate=" + startDate
+ " and endDate=" + endDate);
}

Page<TransactionDTO> itemsDTO = transactions.map(this::convertEntityToDTO);
Expand Down Expand Up @@ -274,7 +281,7 @@ public ResponseEntity<Response<List<TransactionDTO>>> findByNsu(@RequestHeader(v
try {
createSelfLinkInCollections(apiVersion, apiKey, dto);
} catch (TransactionNotFoundException e) {
log.error("There are no transactions registered with the nsu=" + transactionNSU);
log.error("There are no transactions registered with the nsu= {}", transactionNSU);
}
});

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package io.github.mariazevedo88.financialjavaapi.model.enumeration;

public enum PageOrderEnum {

ASC("ASC"), DESC("DESC");

private String value;

private PageOrderEnum(String value) {
this.value = value;
}

public String getValue() {
return value;
}

public static PageOrderEnum getDirection(String value){
if(ASC.getValue().equals(value)) {
return ASC;
}
return DESC;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@
public interface TransactionRepository extends JpaRepository<Transaction, Long> {

/**
* Method to search for all the transactions in the API.
* Method to search for all the transactions in the API in a period of time.
*
* @author Mariana Azevedo
* @since 21/08/2020
*
* @return <code>Page<Transaction></code> object
*/
Page<Transaction> findAllByTransactionDateGreaterThanEqualAndTransactionDateLessThanEqual(LocalDateTime startDate,
LocalDateTime endDate, Pageable pg);
Page<Transaction> findAllByTransactionDateGreaterThanEqualAndTransactionDateLessThanEqual
(LocalDateTime startDate, LocalDateTime endDate, Pageable pg);

/**
* Method to search for all the transactions in the same NSU (unique sequential number).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import org.springframework.data.domain.Page;

import io.github.mariazevedo88.financialjavaapi.exception.TransactionNotFoundException;
import io.github.mariazevedo88.financialjavaapi.model.enumeration.PageOrderEnum;
import io.github.mariazevedo88.financialjavaapi.model.transaction.Transaction;

/**
Expand Down Expand Up @@ -70,13 +71,14 @@ public interface TransactionService {
List<Transaction> findAll();

/**
* Method that find all transactions.
* Method that find all transactions in a period of time
*
* @author Mariana Azevedo
* @since 08/09/2019
* @since 21/08/2020
*
* @return <code>Page<Transaction></code> object
*/
Page<Transaction> findBetweenDates(LocalDateTime startDate, LocalDateTime endDate, int page);
Page<Transaction> findBetweenDates(LocalDateTime startDate, LocalDateTime endDate, int page,
PageOrderEnum order);

}
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,12 @@
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import io.github.mariazevedo88.financialjavaapi.exception.TransactionNotFoundException;
import io.github.mariazevedo88.financialjavaapi.model.enumeration.PageOrderEnum;
import io.github.mariazevedo88.financialjavaapi.model.transaction.Transaction;
import io.github.mariazevedo88.financialjavaapi.repository.transaction.TransactionRepository;
import io.github.mariazevedo88.financialjavaapi.service.transaction.TransactionService;
Expand Down Expand Up @@ -66,16 +69,22 @@ public void deleteById(Long transactionId) {
@Override
@Cacheable(value="transactionIdCache", key="#id")
public Transaction findById(Long id) throws TransactionNotFoundException {
return transactionRepository.findById(id).orElseThrow(() -> new TransactionNotFoundException("Transaction id=" + id + " not found"));
return transactionRepository.findById(id).orElseThrow(() ->
new TransactionNotFoundException("Transaction id=" + id + " not found"));
}

/**
* @see TransactionService#findBetweenDates()
*/
@Override
public Page<Transaction> findBetweenDates(LocalDateTime startDate, LocalDateTime endDate, int page) {
PageRequest pg = PageRequest.of(page, itemsPerPage);
return transactionRepository.findAllByTransactionDateGreaterThanEqualAndTransactionDateLessThanEqual(startDate, endDate, pg);
public Page<Transaction> findBetweenDates(LocalDateTime startDate, LocalDateTime endDate, int page,
PageOrderEnum order) {
Sort sort = Direction.ASC.name().equals(order.getValue()) ?
Sort.by("id").ascending() : Sort.by("id").descending();
PageRequest pg = PageRequest.of(page, itemsPerPage, sort);
return transactionRepository.
findAllByTransactionDateGreaterThanEqualAndTransactionDateLessThanEqual(startDate,
endDate, pg);
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
package io.github.mariazevedo88.financialjavaapi.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

import io.github.mariazevedo88.financialjavaapi.dto.model.transaction.TransactionDTO;
import io.github.mariazevedo88.financialjavaapi.model.transaction.Transaction;
Expand Down Expand Up @@ -86,4 +91,34 @@ public static DateTimeFormatter getDateTimeFormater() {
return DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
}

/**
* Method that converts a string to a LocalDateTime.
*
* @author Mariana Azevedo
* @since 23/08/2020
*
* @param dateAsString
*
* @return <code>LocalDateTime</code> object
* @throws ParseException
*/
public static LocalDateTime getLocalDateTimeFromString(String dateAsString) throws ParseException{
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date dateISO8601 = inputFormat.parse(dateAsString);
return dateISO8601.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
}

/**
* Method that converts a local date to a local date time.
*
* @author Mariana Azevedo
* @since 23/08/2020
*
* @param date
* @return <code>LocalDateTime</code> object
*/
public static LocalDateTime convertLocalDateToLocalDateTime(LocalDate date) {
return date.atTime(0, 0, 0);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
import io.github.mariazevedo88.financialjavaapi.service.statistic.StatisticService;

/**
* Class that implements tests of the StatisticController funcionalities
* Class that implements tests of the StatisticController features
*
* @author Mariana Azevedo
* @since 05/04/2020
Expand Down Expand Up @@ -64,7 +64,7 @@ private void setUp() {
}

/**
* Method that tests to save an Statistic in the API
* Method that tests to save a Statistic in the API
*
* @author Mariana Azevedo
* @since 05/04/2020
Expand Down Expand Up @@ -99,16 +99,7 @@ public void testSave() throws Exception {
* @return <code>Statistic</code> object
*/
private Statistic getMockStatistic() {

Statistic statistic = new Statistic();
statistic.setId(ID);
statistic.setSum(SUM);
statistic.setAvg(AVG);
statistic.setMin(MIN);
statistic.setMax(MAX);
statistic.setCount(COUNT);

return statistic;
return new Statistic(ID, SUM, AVG, MAX, MIN, COUNT);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,7 @@

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -38,6 +35,7 @@
import io.github.mariazevedo88.financialjavaapi.model.enumeration.TransactionTypeEnum;
import io.github.mariazevedo88.financialjavaapi.model.transaction.Transaction;
import io.github.mariazevedo88.financialjavaapi.service.transaction.TransactionService;
import io.github.mariazevedo88.financialjavaapi.util.FinancialApiUtil;

/**
* Class that implements tests of the TransactionController features
Expand Down Expand Up @@ -88,7 +86,8 @@ public void testSave() throws Exception {
BDDMockito.given(service.save(Mockito.any(Transaction.class))).willReturn(getMockTransaction());

mockMvc.perform(MockMvcRequestBuilders.post(URL)
.content(getJsonPayload(ID, NSU, AUTH, getMockTransactionDate(), VALUE, TYPE))
.content(getJsonPayload(ID, NSU, AUTH, FinancialApiUtil.
getLocalDateTimeFromString(TRANSACTION_DATE.concat("Z")), VALUE, TYPE))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.headers(headers))
Expand Down Expand Up @@ -116,7 +115,8 @@ public void testSaveInvalidTransaction() throws Exception {
BDDMockito.given(service.save(Mockito.any(Transaction.class))).willReturn(getMockTransaction());

mockMvc.perform(MockMvcRequestBuilders.post(URL)
.content(getJsonPayload(ID, null, AUTH, getMockTransactionDate(), VALUE, TYPE))
.content(getJsonPayload(ID, null, AUTH, FinancialApiUtil.
getLocalDateTimeFromString(TRANSACTION_DATE.concat("Z")), VALUE, TYPE))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.headers(headers))
Expand All @@ -136,7 +136,8 @@ public void testSaveInvalidTransaction() throws Exception {
private Transaction getMockTransaction() throws ParseException {

Transaction transaction = new Transaction(ID, NSU, AUTH,
getMockTransactionDate(), VALUE, TYPE);
FinancialApiUtil.getLocalDateTimeFromString(TRANSACTION_DATE.concat("Z")),
VALUE, TYPE);

return transaction;
}
Expand All @@ -148,9 +149,11 @@ private Transaction getMockTransaction() throws ParseException {
* @since 05/04/2020
*
* @param id
* @param name
* @param email
* @param password
* @param nsu
* @param authorization
* @param transactionDate
* @param amount
* @param type
* @return <code>String</code> with the TransactionDTO payload
*
* @throws JsonProcessingException
Expand All @@ -170,11 +173,5 @@ private String getJsonPayload(Long id, String nsu, String authorization, LocalDa
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return mapper.writeValueAsString(dto);
}

private LocalDateTime getMockTransactionDate() throws ParseException{
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date dateISO8601 = inputFormat.parse(TRANSACTION_DATE.concat("Z"));
return dateISO8601.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
}

}
Loading

0 comments on commit 706fcd0

Please sign in to comment.