Skip to content

Commit

Permalink
Merge branch 'main' into feat/480-replace-keycloak-by-fam-for-authent…
Browse files Browse the repository at this point in the history
…ication-on-fe
  • Loading branch information
craigyu authored Oct 25, 2023
2 parents 8dc0c36 + 8e5f9dd commit 656932c
Show file tree
Hide file tree
Showing 5 changed files with 203 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,39 @@ public ResponseEntity<SeedlotCreateResponseDto> createSeedlot(
return ResponseEntity.status(HttpStatus.CREATED).body(response);
}

/**
* Resource to fetch all seedlots to a given user id.
*
* @param userId user identification to fetch seedlots to
* @return A {@link List} of {@link Seedlot} populated or empty
*/
@GetMapping("/users/{userId}")
@PreAuthorize("hasRole('user_read')")
@Operation(
summary = "Fetch all seedlots registered by a given user.",
description = "Returns a paginated list containing the seedlots",
responses = {
@ApiResponse(
responseCode = "200",
description = "A list containing found Seedlots or an empty list"),
@ApiResponse(
responseCode = "401",
description = "Access token is missing or invalid",
content = @Content(schema = @Schema(implementation = Void.class)))
})
public List<Seedlot> getUserSeedlots(
@PathVariable
@Parameter(
name = "userId",
in = ParameterIn.PATH,
description = "User's identification",
example = "dev-abcdef123456@idir")
String userId,
@RequestParam(value = "page", required = false, defaultValue = "1") int page,
@RequestParam(value = "size", required = false, defaultValue = "10") int size) {
return seedlotService.getUserSeedlots(userId, page, size);
}

/**
* Get information from a single seedlot.
*
Expand All @@ -196,18 +229,17 @@ public ResponseEntity<SeedlotCreateResponseDto> createSeedlot(
@GetMapping(path = "/{seedlotNumber}")
@Operation(
summary = "Fetch a single seedlot information",
description = """
description =
"""
Fetch all current information from a single seedlot, identified by it's number
""")
@ApiResponses(
value = {
@ApiResponse(responseCode = "200", description = "The Seedlot info was correctly found"),
@ApiResponse(
responseCode = "200",
description = "The Seedlot info was correctly found"),
@ApiResponse(
responseCode = "401",
description = "Access token is missing or invalid",
content = @Content(schema = @Schema(implementation = Void.class))),
responseCode = "401",
description = "Access token is missing or invalid",
content = @Content(schema = @Schema(implementation = Void.class))),
@ApiResponse(
responseCode = "404",
description = "Could not find information for the given seedlot number")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package ca.bc.gov.backendstartapi.repository;

import ca.bc.gov.backendstartapi.entity.seedlot.Seedlot;
import java.util.List;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

Expand All @@ -14,4 +16,13 @@ select max(cast(s.id as int))
where cast(s.id as int) between ?1 and ?2
""")
Integer findNextSeedlotNumber(Integer min, Integer max);

/**
* Finds all {@link Seedlot} given a user's identification in a paginated search.
*
* @param userId user identification to fetch seedlots to
* @param pageable the pagination and sorting specifications
* @return A {@link List} of {@link Seedlot} populated or empty
*/
List<Seedlot> findAllByAuditInformation_EntryUserId(String userId, Pageable pageable);
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,15 @@
import ca.bc.gov.backendstartapi.repository.SeedlotStatusRepository;
import ca.bc.gov.backendstartapi.security.LoggedUserService;
import jakarta.transaction.Transactional;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

/** This class contains methods for handling Seedlots in the database. */
Expand Down Expand Up @@ -111,6 +116,28 @@ private String nextSeedlotNumber(Character seedlotClassCode) {
return String.valueOf(seedlotNumber);
}

/**
* Retrieve a paginated list of seedlot for a given user.
*
* @param userId the id of the user to fetch the seedlots for
* @param pageNumber the page number for the paginated search
* @param pageSize the size of the page
* @return a list of the user's seedlots
*/
public List<Seedlot> getUserSeedlots(String userId, int pageNumber, int pageSize) {
if (pageNumber == 0) {
pageNumber = 1;
}
if (pageSize == 0) {
pageSize = 10;
}

Pageable sortedPageable =
PageRequest.of(
pageNumber, pageSize, Sort.by(Direction.DESC, "AuditInformation_UpdateTimestamp"));
return seedlotRepository.findAllByAuditInformation_EntryUserId(userId, sortedPageable);
}

/**
* Retrieve a single seedlot information.
*
Expand All @@ -121,8 +148,7 @@ private String nextSeedlotNumber(Character seedlotClassCode) {
public Optional<Seedlot> getSingleSeedlotInfo(String seedlotNumber) {
log.info("Retrieving information for Seedlot number {}", seedlotNumber);

Optional<Seedlot> seedlotInfo =
seedlotRepository.findById(seedlotNumber);
Optional<Seedlot> seedlotInfo = seedlotRepository.findById(seedlotNumber);

if (seedlotInfo.isEmpty()) {
log.error("Nothing found for seedlot number: {}", seedlotNumber);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
import ca.bc.gov.backendstartapi.service.SeedlotService;
import ca.bc.gov.backendstartapi.service.parser.ConeAndPollenCountCsvTableParser;
import ca.bc.gov.backendstartapi.service.parser.SmpCalculationCsvTableParser;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
Expand Down Expand Up @@ -49,6 +51,8 @@ class SeedlotEndpointTest {

private final WebApplicationContext webApplicationContext;

private static final String USER_ID = "dev-123456789abcdef@idir";

SeedlotEndpointTest(WebApplicationContext webApplicationContext) {
this.webApplicationContext = webApplicationContext;
}
Expand Down Expand Up @@ -209,6 +213,82 @@ void createSeedlotBadRequestTest() throws Exception {
.andReturn();
}

@Test
@DisplayName("getUserSeedlotInfoTestDefaultPagination")
@WithMockUser(roles = "user_read")
void getUserSeedlotInfoTestDefaultPagination() throws Exception {
Seedlot seedlotEntity = new Seedlot("0000000");
List<Seedlot> userSeedlots = new ArrayList<>();
userSeedlots.add(seedlotEntity);

String url = String.format("/api/seedlots/users/%s", USER_ID);

when(seedlotService.getUserSeedlots(USER_ID, 1, 10)).thenReturn(userSeedlots);

mockMvc
.perform(get(url).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
}

@Test
@DisplayName("getUserSeedlotInfoTestChangePageNumber")
@WithMockUser(roles = "user_read")
void getUserSeedlotInfoTestChangePageNumber() throws Exception {
Seedlot seedlotEntity = new Seedlot("0000001");
List<Seedlot> userSeedlots = new ArrayList<>();
userSeedlots.add(seedlotEntity);

when(seedlotService.getUserSeedlots(USER_ID, 1, 10)).thenReturn(userSeedlots);

String url = String.format("/api/seedlots/users/%s?page={page}", USER_ID);
int page = 1;

mockMvc
.perform(
get(url, page)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
}

@Test
@DisplayName("getUserSeedlotInfoTestChangePageSize")
@WithMockUser(roles = "user_read")
void getUserSeedlotInfoTestChangePageSize() throws Exception {
Seedlot seedlotEntity = new Seedlot("0000002");
List<Seedlot> userSeedlots = new ArrayList<>();
userSeedlots.add(seedlotEntity);
userSeedlots.add(seedlotEntity);

String url = String.format("/api/seedlots/users/%s?page=1&size={size}", USER_ID);
int pageSize = 2;

when(seedlotService.getUserSeedlots(USER_ID, 1, pageSize)).thenReturn(userSeedlots);

mockMvc
.perform(
get(url, pageSize)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.length()").value(2))
.andReturn();
}

@Test
@DisplayName("getSingleSeedlotInfoNotFoundNoPageTest")
void getSingleSeedlotInfoNotFoundNoPageTest() throws Exception {
when(seedlotService.getUserSeedlots(USER_ID, 1, 10)).thenReturn(List.of());

String url = String.format("/api/seedlots/users/%s", USER_ID);

mockMvc
.perform(get(url).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.length()").value(0))
.andReturn();
}

@Test
@DisplayName("getSingleSeedlotInfoTest")
@WithMockUser(roles = "user_read")
Expand All @@ -218,9 +298,7 @@ void getSingleSeedlotInfoTest() throws Exception {
when(seedlotService.getSingleSeedlotInfo(any())).thenReturn(Optional.of(seedlotEntity));

mockMvc
.perform(
get("/api/seedlots/0000000")
.accept(MediaType.APPLICATION_JSON))
.perform(get("/api/seedlots/0000000").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
}
Expand All @@ -231,8 +309,7 @@ void getSingleSeedlotInfoNotFoundTest() throws Exception {
when(seedlotService.getSingleSeedlotInfo(any())).thenThrow(new SeedlotNotFoundException());

mockMvc
.perform(get("/api/seedlots/0000000")
.accept(MediaType.APPLICATION_JSON))
.perform(get("/api/seedlots/0000000").accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isNotFound())
.andReturn();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import ca.bc.gov.backendstartapi.repository.SeedlotStatusRepository;
import ca.bc.gov.backendstartapi.security.LoggedUserService;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
Expand Down Expand Up @@ -167,6 +168,48 @@ void createSeedlotTest_noSeedlotSource_shouldThrowException() {
}

@Test
@DisplayName("findSeedlotsByUserWithTwoSeedlots")
void getUserSeedlots_findsTwoSeedlots_shouldSucceed() {
String userId = "123456abcde@idir";

List<Seedlot> testList = List.of(new Seedlot("63001"), new Seedlot("63002"));

when(seedlotService.getUserSeedlots(userId, 0, 10)).thenReturn(testList);

List<Seedlot> responseFromService = seedlotService.getUserSeedlots(userId, 0, 10);

Assertions.assertNotNull(responseFromService);
Assertions.assertEquals(2, responseFromService.size());
Assertions.assertEquals("63001", responseFromService.get(0).getId());
Assertions.assertEquals("63002", responseFromService.get(1).getId());
}

@Test
@DisplayName("findSeedlotsByUserNoSeedlots")
void getUserSeedlots_noSeedlots_shouldSucceed() {
String userId = "userId";

when(seedlotService.getUserSeedlots(userId, 0, 10)).thenReturn(List.of());

List<Seedlot> responseFromService = seedlotService.getUserSeedlots(userId, 0, 10);

Assertions.assertNotNull(responseFromService);
Assertions.assertTrue(responseFromService.isEmpty());
}

@Test
@DisplayName("findSeedlotsByUserNoPageSize")
void getUserSeedlots_noPageSize_shouldSucceed() {
String userId = "userId";

when(seedlotService.getUserSeedlots(userId, 0, 10)).thenReturn(List.of());

List<Seedlot> responseFromService = seedlotService.getUserSeedlots(userId, 0, 0);

Assertions.assertNotNull(responseFromService);
Assertions.assertTrue(responseFromService.isEmpty());
}

@DisplayName("findSingleSeedlotSuccessTest")
void findSingleSeedlotSuccessTest() {
Seedlot seedlotEntity = new Seedlot("0000000");
Expand Down

0 comments on commit 656932c

Please sign in to comment.