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

feat: CCT list calculations endpoint #499

Merged
merged 3 commits into from
Nov 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ plugins {
}

group = "uk.nhs.hee.trainee.details"
version = "1.15.1"
version = "1.16.0"

configurations {
compileOnly {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
package uk.nhs.hee.trainee.details.api;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
Expand All @@ -37,6 +38,10 @@
import com.jayway.jsonpath.JsonPath;
import io.awspring.cloud.sqs.operations.SqsTemplate;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.UUID;
import org.bson.types.ObjectId;
import org.junit.jupiter.api.AfterEach;
Expand Down Expand Up @@ -64,7 +69,10 @@
import org.testcontainers.junit.jupiter.Testcontainers;
import uk.nhs.hee.trainee.details.DockerImageNames;
import uk.nhs.hee.trainee.details.TestJwtUtil;
import uk.nhs.hee.trainee.details.dto.enumeration.CctChangeType;
import uk.nhs.hee.trainee.details.model.CctCalculation;
import uk.nhs.hee.trainee.details.model.CctCalculation.CctChange;
import uk.nhs.hee.trainee.details.model.CctCalculation.CctProgrammeMembership;

@SpringBootTest
@Testcontainers(disabledWithoutDocker = true)
Expand Down Expand Up @@ -117,6 +125,103 @@ void tearDown() {
template.findAllAndRemove(new Query(), CctCalculation.class);
}

@Test
void shouldBeForbiddenGettingCalculationsWhenNoToken() throws Exception {
mockMvc.perform(get("/api/cct/calculation", "1"))
.andExpect(status().isForbidden())
.andExpect(jsonPath("$").doesNotExist());
}

@Test
void shouldBeForbiddenGettingCalculationsWhenNoTraineeId() throws Exception {
String token = TestJwtUtil.generateToken("{}");
mockMvc.perform(get("/api/cct/calculation", "1")
.header(HttpHeaders.AUTHORIZATION, token))
.andExpect(status().isForbidden())
.andExpect(jsonPath("$").doesNotExist());
}

@Test
void shouldNotGetCalculationsWhenNotOwnedByUser() throws Exception {
ObjectId id = ObjectId.get();
CctCalculation entity = CctCalculation.builder()
.id(id)
.traineeId(TRAINEE_ID)
.build();
template.insert(entity);

String token = TestJwtUtil.generateTokenForTisId(UUID.randomUUID().toString());
mockMvc.perform(get("/api/cct/calculation")
.header(HttpHeaders.AUTHORIZATION, token))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$", hasSize(0)));
}

@Test
void shouldGetCalculationsWhenOwnedByUser() throws Exception {
UUID pmId = UUID.randomUUID();

CctCalculation entity = CctCalculation.builder()
.traineeId(TRAINEE_ID)
.name("Test Calculation")
.programmeMembership(CctProgrammeMembership.builder()
.id(pmId)
.build())
.build();
entity = template.insert(entity);

String token = TestJwtUtil.generateTokenForTisId(TRAINEE_ID);
mockMvc.perform(get("/api/cct/calculation")
.header(HttpHeaders.AUTHORIZATION, token))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$", hasSize(1)))
.andExpect(jsonPath("$[0].id").value(entity.id().toString()))
.andExpect(jsonPath("$[0].name").value("Test Calculation"))
.andExpect(jsonPath("$[0].programmeMembershipId").value(pmId.toString()))
.andExpect(jsonPath("$[0].created").value(
entity.created().truncatedTo(ChronoUnit.MILLIS).toString()))
.andExpect(jsonPath("$[0].lastModified").value(
entity.lastModified().truncatedTo(ChronoUnit.MILLIS).toString()));
}

@Test
void shouldGetCalculationsOrderedByLatestWhenOwnedByUser() throws Exception {
CctCalculation future = CctCalculation.builder()
.traineeId(TRAINEE_ID)
.name("Future")
.build();
future = template.insert(future);

CctCalculation past = CctCalculation.builder()
.traineeId(TRAINEE_ID)
.name("Past")
.build();
template.insert(past);

CctCalculation present = CctCalculation.builder()
.traineeId(TRAINEE_ID)
.name("Present")
.build();
template.insert(present);

template.save(future);

String token = TestJwtUtil.generateTokenForTisId(TRAINEE_ID);
mockMvc.perform(get("/api/cct/calculation")
.header(HttpHeaders.AUTHORIZATION, token))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$", hasSize(3)))
.andExpect(jsonPath("$[0].name").value("Past"))
.andExpect(jsonPath("$[1].name").value("Present"))
.andExpect(jsonPath("$[2].name").value("Future"));
}

@Test
void shouldBeForbiddenGettingCalculationWhenNoToken() throws Exception {
mockMvc.perform(get("/api/cct/calculation/{id}", "1"))
Expand Down Expand Up @@ -151,20 +256,49 @@ void shouldNotGetCalculationWhenNotOwnedByUser() throws Exception {

@Test
void shouldGetCalculationWhenOwnedByUser() throws Exception {
ObjectId id = ObjectId.get();
UUID pmId = UUID.randomUUID();

CctCalculation entity = CctCalculation.builder()
.id(id)
.traineeId(TRAINEE_ID)
.name("Test Calculation")
.programmeMembership(CctProgrammeMembership.builder()
.id(pmId)
.name("Test Programme")
.startDate(LocalDate.parse("2024-01-01"))
.endDate(LocalDate.parse("2025-01-01"))
.wte(1.0)
.build())
.changes(List.of(
CctChange.builder()
.type(CctChangeType.LTFT)
.startDate(LocalDate.parse("2024-07-01"))
.wte(0.5)
.build()))
.build();
template.insert(entity);
entity = template.insert(entity);

String token = TestJwtUtil.generateTokenForTisId(TRAINEE_ID);
mockMvc.perform(get("/api/cct/calculation/{id}", id)
mockMvc.perform(get("/api/cct/calculation/{id}", entity.id())
.header(HttpHeaders.AUTHORIZATION, token))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.id").value(id.toString()))
.andExpect(jsonPath("$.traineeId").doesNotExist());
.andExpect(jsonPath("$.id").value(entity.id().toString()))
.andExpect(jsonPath("$.traineeId").doesNotExist())
.andExpect(jsonPath("$.name").value("Test Calculation"))
.andExpect(jsonPath("$.programmeMembership").isMap())
.andExpect(jsonPath("$.programmeMembership.id").value(pmId.toString()))
.andExpect(jsonPath("$.programmeMembership.startDate").value("2024-01-01"))
.andExpect(jsonPath("$.programmeMembership.endDate").value("2025-01-01"))
.andExpect(jsonPath("$.programmeMembership.wte").value(1))
.andExpect(jsonPath("$.changes").isArray())
.andExpect(jsonPath("$.changes", hasSize(1)))
.andExpect(jsonPath("$.changes[0].type").value("LTFT"))
.andExpect(jsonPath("$.changes[0].startDate").value("2024-07-01"))
.andExpect(jsonPath("$.changes[0].wte").value(0.5))
.andExpect(
jsonPath("$.created").value(entity.created().truncatedTo(ChronoUnit.MILLIS).toString()))
.andExpect(jsonPath("$.lastModified").value(
entity.lastModified().truncatedTo(ChronoUnit.MILLIS).toString()));
}

@Test
Expand Down Expand Up @@ -376,16 +510,28 @@ void shouldFailCreateCalculationValidationWhenChangeWteNotValid(double wte) thro

@Test
void shouldReturnCreatedCalculationJsonWhenRequestValid() throws Exception {
Instant start = Instant.now();

String token = TestJwtUtil.generateTokenForTisId(TRAINEE_ID);
mockMvc.perform(post("/api/cct/calculation")
MvcResult result = mockMvc.perform(post("/api/cct/calculation")
.header(HttpHeaders.AUTHORIZATION, token)
.contentType(MediaType.APPLICATION_JSON)
.content(calculationJson.toString()))
.andExpect(status().isCreated())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.id").exists())
.andExpect(jsonPath("$.traineeId").doesNotExist())
.andExpect(jsonPath("$.name").value("Test Calculation"));
.andExpect(jsonPath("$.name").value("Test Calculation"))
.andExpect(jsonPath("$.created").exists())
.andExpect(jsonPath("$.lastModified").exists())
.andReturn();

String response = result.getResponse().getContentAsString();
Instant created = Instant.parse(JsonPath.read(response, "$.created"));
assertThat("Unexpected created timestamp.", created, greaterThan(start));

Instant lastModified = Instant.parse(JsonPath.read(response, "$.lastModified"));
assertThat("Unexpected last modified timestamp.", lastModified, greaterThan(start));
}

@Test
Expand Down
14 changes: 14 additions & 0 deletions src/main/java/uk/nhs/hee/trainee/details/api/CctResource.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

import com.amazonaws.xray.spring.aop.XRayEnabled;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
Expand All @@ -35,6 +36,7 @@
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import uk.nhs.hee.trainee.details.dto.CctCalculationDetailDto;
import uk.nhs.hee.trainee.details.dto.CctCalculationSummaryDto;
import uk.nhs.hee.trainee.details.dto.validation.Create;
import uk.nhs.hee.trainee.details.service.CctService;

Expand All @@ -58,6 +60,18 @@ public CctResource(CctService service) {
this.service = service;
}

/**
* Get a list of CCT calculation summaries for the current user.
*
* @return The found CCT calculation summaries.
*/
@GetMapping("/calculation")
public ResponseEntity<List<CctCalculationSummaryDto>> getCalculationSummaries() {
log.info("Request to get a summary for all CCT calculations");
List<CctCalculationSummaryDto> calculations = service.getCalculations();
return ResponseEntity.ok(calculations);
}

/**
* Get the details of a CCT calculation with the given ID.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,18 @@
import jakarta.annotation.PostConstruct;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.config.EnableMongoAuditing;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.index.IndexInfo;
import org.springframework.data.mongodb.core.index.IndexOperations;
import uk.nhs.hee.trainee.details.model.TraineeProfile;

/**
* Configuration for the Mongo database.
*/
@Configuration
@EnableMongoAuditing
public class MongoConfiguration {

private final MongoTemplate template;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Null;
import java.time.Instant;
import java.time.LocalDate;
import java.util.List;
import java.util.UUID;
Expand All @@ -44,6 +45,8 @@
* @param name A name for the calculation.
* @param programmeMembership The programme membership data for the calculation.
* @param changes The CCT changes to be calculated.
* @param created When the calculation was created (auto-generated).
* @param lastModified When the calculation was last modified (auto-generated).
*/
@Builder
public record CctCalculationDetailDto(
Expand All @@ -61,7 +64,9 @@ public record CctCalculationDetailDto(

@NotEmpty
@Valid
List<CctChangeDto> changes) {
List<CctChangeDto> changes,
Instant created,
Instant lastModified) {

/**
* Programme membership data for a calculation.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* The MIT License (MIT)
*
* Copyright 2024 Crown Copyright (Health Education England)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

package uk.nhs.hee.trainee.details.dto;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import java.time.Instant;
import java.util.UUID;
import lombok.Builder;
import org.bson.types.ObjectId;

/**
* A summary of a CCT calculation.
*
* @param id The ID of the calculation.
* @param name The name of the calculation.
* @param programmeMembershipId The ID of the associated programme membership.
*/
Judge40 marked this conversation as resolved.
Show resolved Hide resolved
@Builder
public record CctCalculationSummaryDto(

@JsonSerialize(using = ToStringSerializer.class)
ObjectId id,
String name,
UUID programmeMembershipId,
Instant created,
Instant lastModified) {

}
19 changes: 19 additions & 0 deletions src/main/java/uk/nhs/hee/trainee/details/mapper/CctMapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,11 @@

import static org.mapstruct.MappingConstants.ComponentModel.SPRING;

import java.util.List;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import uk.nhs.hee.trainee.details.dto.CctCalculationDetailDto;
import uk.nhs.hee.trainee.details.dto.CctCalculationSummaryDto;
import uk.nhs.hee.trainee.details.model.CctCalculation;

/**
Expand All @@ -34,6 +36,23 @@
@Mapper(componentModel = SPRING)
public interface CctMapper {

/**
* Convert a {@link CctCalculation} entity to a {@link CctCalculationSummaryDto} DTO.
*
* @param entity The entity to convert to a DTO.
* @return The equivalent summary DTO.
*/
@Mapping(target = "programmeMembershipId", source = "programmeMembership.id")
CctCalculationSummaryDto toSummaryDto(CctCalculation entity);

/**
* Convert a list of {@link CctCalculation} to a list of {@link CctCalculationDetailDto}.
*
* @param entities The entities to convert to DTOs.
* @return The equivalent summary DTOs.
*/
List<CctCalculationSummaryDto> toSummaryDtos(List<CctCalculation> entities);

/**
* Convert a {@link CctCalculation} entity to a {@link CctCalculationDetailDto} DTO.
*
Expand Down
Loading
Loading